body:
I am trying to use a nested for loop to evaluate and change numbers within the two dimensional array. Basically these numbers are minutes, or hours. This function is meant to reset the button controlled numbers when they go above 23 (hours) or above 59 (minutes) and also from going below 0. The two dimensional array that I made also has three arrays that need to be skipped (P1[0], P1[2] and P1[10] because they do not contain any time variables. When I click the buttons and increment the numbers nothing unusual happens they just don't bounce back like they are supposed to.

Here is the two dimensional array:

    int P1[][12] = { //0-10
      {0}, //MODE
      {0, 0, 0, 0,}, //TOD variables
      // OnHR, OnMin, OffHr, OffMin
      {0}, //DOW
      {0, 0, 0, 0,},  //Sunday
      {0, 0, 0, 0,},    // OnHR, OnMin, OffHr, OffMin
      {0, 0, 0, 0,},
      {0, 0, 0, 0,},
      {0, 0, 0, 0,},
      {0, 0, 0, 0,},
      {0, 0, 0, 0,},  //Saturday
      {0, 0, 0, 0, 0,} // Temperature variables
      //Sensor, GreaterThan/LessThan, Temp, Buffer, State
    };

Here is the for loop that doesn't seem to work:

    void HrMinBounce() {
      int i = 0;
      int q = 0;

      for (int i; i < 10; i++) { //iterating down Plug arrays
        for (int q; q < 4; q++) {
          if (i != 0 || i != 2) { //non time arrays
            if (q == 0 || q == 2) { //hours
              if (P1[i][q] > 23) {
                P1[i][q] = 0;
              }
              if (P1[i][q] < 0) {
                P1[i][q] = 23;
              }
            }//End of hours
            if (q == 1 || q == 3) { //minutes
              if (P1[i][q] > 59) {
                P1[i][q] = 0;
              }
              if (P1[i][q] < 0) {
                P1[i][q] = 59;
              }
            }//End of minutes
          }
        }
      }
    }

I have 5 of these arrays, so I was hoping to make one loop that could take care of all 5 at once. Here is my previous loop that works but I would have to copy and paste a whole lot to get the result without the extra for loop.

    void MinHrLimit() {
      int i = 0;

      for (int i; i < 3; i++) {
        if (i == 0 || i == 2) {
          if (P1[1][i] > 23) {
            P1[1][i] = 0;
          }
          if (P1[1][i] < 0) {
            P1[1][i] = 23;
          }
        }
      }
    }

title: Nested for loop used to evaluate a two dimensional array of integers

Answers: 3

body:
                if(i != 0 || i != 2){ //non time arrays

Let's see.

* If i is 0 then that is true (it isn't 2)
* If i is 1 then that is true (it isn't 0 or 2)
* If i is 2 then that is true (it isn't 0)
* If i is 3 then that is true (it isn't 0 or 2)

In fact that expression is always true. You probably want:

                if(i != 0 && i != 2){ //non time arrays

---

       void MinHrLimit(){
          int i = 0;

          for(int i; i < 3; i++){

You don't need the declaration of `i` there, because it is redefined in the `for` loop. In the `for` loop the variable `i` has an undefined value. You really want:

       void MinHrLimit(){

          for(int i = 0; i < 3; i++){

body:
a few pointers:

1) your array has unevent number of items. so an array of struct is likely more useful here;

2) use brackets liberally, if you want to be sure of sequence of computation, like:

    if ((i == 0) || (i == 2)) {

3) if you are going to use a lot of date / time types, think about unix time_t data type. it simplifies coding considerably, and makes your code much more portable.

body:
Your problem here is not in your code. It's in the data structures: you
are doing it the wrong way. Of course, it _can_ work, but not only is
your approach wasteful of RAM, it will also inevitably lead to code that
is difficult to write, to understand, to debug and to maintain.

You should really try hard to make your data structures as clean as
possible. I would argue that clean data is even more important than
clean code. If your data mode is clear and makes sense, then clean code
flows naturally. If your data model is contrived, your code will always
look awkward.

Here is how I would go about structuring your data. First thing: you are
using (hour, minute) pairs to represent times. Thus, here is the obvious
way to put them:

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

    struct Time {
        int8_t hour, minute;
    };

Notice the variable type: `uint8_t` takes only one byte, and it can
represent numbers from −128 to +127. Now, this is the right place to
write a function that clamps the numbers to the allowed values. In C,
this would be a plain function. But since we are writing C++, it makes
more sense to make it a method of the `struct`. Thus:

    struct Time {
        int8_t hour, minute;
        void limit() {
            if (hour > 23)   hour = 0;
            if (hour < 0)    hour = 23;
            if (minute > 59) minute = 0;
            if (minute < 0)  minute = 59;
        }
    };

It seems all your times come in pairs, with an “on time” and an “off
time”. So here is a data structure for such a pair:

    struct OnOffTime {
        Time on_time, off_time;
        void limit() {
            on_time.limit();
            off_time.limit();
        }
    };

I added the convenience method `limit()`, so you can limit an
`OnOffTime` rather than having to always explicitly limit moth times.

Then, you have a “mode” variable. A mode is normally represented as an
`enum`, where each possible mode is given a name. Using names instead of
numbers makes everything clearer. For the temperatures and the day of
week, I would use the type `uint8_t`, which takes only one byte and can
represent a number from 0 to 255. Then, your 2D array becomes an
instance of this:

    struct Settings {
        enum { MODE_FOO, MODE_BAR, MODE_BAZ, MODE_QUX } mode;
        uint8_t doy;
        OnOffTime tod, days[7];
        uint8_t temperatures[5];
    };

You can probably find better names for the fields of the struct. And you
should.

So, back to the original problem: how to apply the `limit()` method to
all the times in all your 5 settings. Here it goes:

    const int settings_count = 5;

    Settings P[settings_count];

    void HrMinBounce()
    {
        for (int i = 0; i < settings_count; i++) {
            P[i].tod.limit();
            for (int j = 0; j < 7; j++) {
                P[i].days[j].limit();
            }
        }
    }

As you see here, the code is short and easy to understand. This is the
benefit of well though data structures: the code that follows is more
natural.


body:
I'm looking for a timer interrupt library for the new Arduinos based on MCU SAMD21.

I want to wake up periodically the MCU form sleep state, do some task and go sleep again. Using one timer interrupt Arduino wakes up. For new Arduino MKR family.

Do you know a library to do this?

title: Timer interrupt library for new Arduino based on MCU SAMD21

Answers: 1

body:
> Do you know a library to do this?

it is generally very difficult to find a library that does precisely what your application wants. in fact, the purpose of a library is so that it is generic enough for you to tailor it for your specific application.

in this particular case, what you wanted to do is quite simple:

1) read through the datasheet;

2) figure out how the timer works;

3) figure out how the power management works;

4) configure timer isr to wake up the mcu periodically; an overflow isr is typically all you need;

5) run the task directly in the isr if is it short or set a flag for its execution in the loop;

6) upon completion, put the mcu to sleep.

all you need is to tackle the little steps above and you will get it done in no time, and learn a ton about your device.

device datasheet is the best friend of any embedded engineer, not the worst enemy.


body:
I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

Code:

    const int ledrood = 9;
    const int ledgroen = 10;
    const int ledblauw = 11;
    const int buttonPreset = 2;
    const int buttonMix = 4;
    float sensorWaarde = 0;
    int switchtel = 1;

    int roodval;
    int groenval;
    int blauwval;
    int buttonState = LOW;

    void setup() {
    Serial.begin(9600);
    pinMode(ledrood, OUTPUT);
    pinMode(ledgroen, OUTPUT);
    pinMode(ledrood, OUTPUT);
    pinMode(sensorWaarde, INPUT);
    pinMode(buttonPreset, INPUT);
    pinMode(buttonMix, INPUT);

    }

    void loop() {
    int sensorWaarde = analogRead(A0);
    buttonState = digitalRead(buttonMix);
    if (buttonState == HIGH) {

    delay(200);
    switch (switchtel) {
      case 1:
      roodval = 255;
      roodval = sensorWaarde / 4;

        groenval = 0;
        blauwval = 0;
        analogWrite( ledgroen, groenval );
        analogWrite( ledrood, roodval );
        analogWrite( ledblauw, blauwval);
        Serial.println(roodval);
        switchtel = switchtel + 1;
        break;

      case 2:

        roodval = 0; // cyaan
        groenval = 255;
        blauwval = 255;
        analogWrite( ledgroen, groenval );
        analogWrite( ledrood, roodval );
        analogWrite( ledblauw, blauwval);
        Serial.println("2");
        switchtel = switchtel + 1;
        break;

      case 3:

        roodval = 255; // magenta
        groenval = 0;
        blauwval = 255;
        analogWrite( ledgroen, groenval );
        analogWrite( ledrood, roodval );
        analogWrite( ledblauw, blauwval);
        Serial.println("3");
        switchtel = switchtel + 1;
        break;
        switch (switchtel) {

        }
       }
     }
    }

title: Loop one specific case inside of a switch

Answers: 2

body:
You need to split your cases into multiple parts.

For example, you have a case which sets up a mode, and a case that runs a mode, and if needed a case that finishes a mode.

For example:

    switch (mode) {
        case 0: // Idle
            break;
        case 1: // Start - do whatever to set up the mode here
            redValue = 100;
            greenvalue = 200;
            mode = 2; // Switch to the next case
            break;
        case 2: // Run - this is the bit that repeats
            if (digitalRead(3) == HIGH) {
                mode = 3; // Finish it
            }
            // Do whatever for each loop here.
            break;
        case 3: // It is finished.
            redValue = 0;
            greenValue = 0;
            // etc.
            mode = 0; // Or whatever you want to do next
            break;
    }

The key thing here is that case 1 is equivalent to a mini `setup()` and case 2 is equivalent to a mini `loop()`. You switch to case 1, which does the setup, and that case then switches to case 2, which it stays at until you tell it otherwise. That case will keep getting executed until you tell it to move to another case.

body:
> I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

not sure why it needs to be anything more complicated than this:

      if (isPressed2x(btn)) do_something(); //if button is pressed twich, execute do_someting()

there are lots of ways to implement isPressed2x(). the simplest would be to use a static variable to keep track of it:

    char isPressed2x(uint8_t btn) {
      static char cnt=0; //button press counter
      if (isPressed(btn)) {  //button is pressed
        cnt+=1; //increment counter
        if ((cnt&0x01) == 0) return 1; //button has been pressed twich
      }
      return 0; //button not pressed, or not pressed twice
    }

similarly, isPressed(btn) can be implemented, with or without debouncing.

the key is to break down any task into small, simple and well defined blocks so when re-assembled together, those small, simple and well defined blocks can perform tasks as complicated as you wish them to be.

the alternative is to jumbo all of them into one routine, making it hard to understand, hard to debug and hard to port.


body:
I'm trying to pass variable addresses to functions/methods within a custom library that should change the values at the specified addresses.  However, I think I'm missing something as it's taking me ages to tweak things just to get it to compile, let alone gather some useful information from it.

Note:
I've not tested the code as I'm focused on understanding (1.) through to (5.) and is just a quick example of the current pipeline:

Main.ino

    #include <customLibrary.h>

    CustomLibrary cLib();

    byte someByte[6];
    unsigned int theAddress;

    setup(){};

    loop(){

        // (1.)
        theAddress = &someByte; // normally need this here, or before setup(), for it to work.

        cLib.setValues(theAddress);

        // because:
        // cLib.setValues(&someByte);
        // doesn't seem to work
    };

customLibrary.h

    #ifndef CustomLib
    #define CustomLib
    #if(ARDUINO > 100)
        #include "Arduino.h"
    #else
        #include "WProgram.h"
    #endif

    class CustomLibrary {
        public:
            CustomLibrary();
            void setValues(unsigned int theAddress); // (2.)
        private:
    };
    #endif

customLibrary.cpp

    #include <customLibrary.h>

    CustomLibrary::CustomLibrary(){
    };

    void CustomLibrary::setValues(unsigned int theAddress){ // (3.)

        byte _someNewValues[6] = {a,b,c,d,e,f};

        // Assign the variable from _someNewValues[_x] to (theAddress + _x)
        int _x = 0;
        for(unsigned int i = theAddress;i < (theAddress + 6);i++){ // (4.)
            // (5.)
            _x++;
        };

    };

(1.) - Feels like it should be simpler.

(2-3-4-5.) - I have left out any "*" and "&" hoping that someone can provide the preferred way of doing this, or provide a better solution as it's taking far too long to get this working with everything else leading me to think I'm missing something basic.

There are some excellent tutorials out there which I have been
following with great success, but, only when all the pointers are within the same file.  Once I try and use them in a library it's a constant headache at the moment and I don't understand it enough to know what's wrong.

Need to go before I can proof-read and check it, but I think it's all there.  I'll be back later/tomorrow if there's anything that needs clearing up.

Edit:
I didn't know who to mark for the answer as both @dannyf and @KIIV answered perfectly.  I considered marking the answer based on the time it was posted, but decided instead to let @dannyf have it as his reputation was only 1.

Thank you both! Much appreciated!

title: Pointers, libraries, and arrays:

Answers: 2

body:
somebyte itself is a pointer. so "&somebyte" doesn't make sense.

instead, use "&somebyte[0]" (or "&somebyte[5]" if you want an offset), or "somebyte" (or "somebyte + 5" if you want an offset).

arrays are actually pointers.

body:
I'm not sure how it could ever work for you in both variants.
There is simple example how to work with arrays:

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

    class CustomLibrary {
        public:
            CustomLibrary() {;}

            void setValues(byte * address);

            template <class T, int SIZE>
            void setValuesTemplate(T(&bytes)[SIZE])
            {
              for (int8_t i=0; i<SIZE; ++i)
              {
                ++bytes[i]; // just increment the value
              };
            }
     };

    void CustomLibrary::setValues(byte * address){
        byte somethingNew[] = {'a','b','c','d','e','f'};

        for (int8_t i=0; i<6; ++i)
        {
          address[i] = somethingNew[i];
        }

    };

    CustomLibrary lib;

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

    void loop(){
      byte someByte[6] = {'z','y','x','w','v','u'};

      Serial.println("Values before:");
      for (byte b : someByte) Serial.print(b, HEX);
      Serial.println();

      lib.setValuesTemplate(someByte);

      Serial.println("Values after templated method:");
      for (byte b : someByte) Serial.print(b, HEX);
      Serial.println();

      lib.setValues(someByte);

      Serial.println("Values after method:");
      for (byte b : someByte) Serial.print(b, HEX);
      Serial.println();

      delay(5000);
    };

It's in single .ino file for testing purposes. If you want to use templates, you have to place template method definition into the header file (it doesn't have to be inside class definition, it just have to be in header file).

Range based for loop was introduced by C++11 standard (suported by Arduino IDE for a while - since about version 1.6.5?). It's realy handy on static arrays (like int arr[] = {......}), so you don't have to care about it size. But it's basically everything it can do on `avr-g++`, as there are no containers, no iterators and so on.

Templates are quite huge topic on C++, in this case it's working with T as array element type and SIZE as its size (it won't work on pointers, it only works on static arrays).

I could've use range based for loop in int too:

        template <class T, int SIZE>
        void setValuesTemplate(T(&arr)[SIZE])
        {
          for (T& item : arr) // it must be a reference type, if you don't want to change local value only
          {
            ++item; // just increment the value
          };
        }

And I didn't even needed that class T part. If you need byte array only:

        template <int SIZE>
        void setValuesTemplate(byte(&arr)[SIZE])
        {
          for (byte& item : arr)
          {
            ++item;
          };
        }

But there is a downside for using templates -> there will one instance of that method for each type/size. But it's possible to use it as a "proxy" and pass it to function that expects just pointer and the size.


body:
I have just got a new pair of HC-05 Bluetooth modules. I am working on a simple project. I'm trying to move two servo motors using two potentiometers. I followed [a simple tutorial][1] to move one servo, and it worked successfully.

How to make the same thing with 2 potentiometers and two servos?

UPDATE:

I have successfully managed to write down something that get to read values from two potentiometers, but I'am still facing problems with the slave part.
Can't figure out the problem.

(Master)

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

    //Master
    int potValuePins[] = { A0, A1 };
    void setup() {
      Serial.begin(9600); // Default communication rate of the Bluetooth module
       for (auto pin : potValuePins) {
         pinMode(pin, INPUT);
       }
    }

    void loop() {
     for (auto pin : potValuePins) {
       Serial.write(pin); // Send the pin number
       Serial.write(analogRead(pin)); // Send the pin value with a trailing
     newline as a delimiter
       int value=analogRead(pin);
       Serial.print(" Pin is: ");
       Serial.print(pin);
       Serial.print("\t");
       Serial.print("Value is: ");
       Serial.println(value);
       }
     }

(Slave)

    //Slave
    #include <Servo.h>
    Servo myServo1;
    Servo myServo2;

    void setup() {
    Serial.begin(9600);
    myServo1.attach(9);
    myServo2.attach(10);
    }

    void loop() {
    if (Serial.available()) {
     char input[3];
     Serial.readBytes(input, 2);
     int pin = input[0];
     int angle = input[1];
     Serial.print("the pin:");
     Serial.print(pin);
     Serial.print("\t");
     Serial.print("the angle:");
     Serial.println( angle);

     switch (pin) {
      case A0:
        myServo1.write(angle);
        break;
      case A1:
        myServo2.write(angle);
        break;
      default:
        Serial.println("Unknown value");
        break;
       }
      }
     }

  [1]: http://howtomechatronics.com/tutorials/arduino/how-to-configure-pair-two-hc-05-bluetooth-module-master-slave-commands/

title: A clarification needed about the HC-05

Answers: 1

body:
Looking at the example you linked to, the "communication" between the two ends is just writing a (byte) value between `0` and `255`, and reading that on the other end.

One simple (out of many possibilities) to extend this to handle a set of two is just to send 2 bytes in sequence, with the first byte being an identifier of which servo you are denoting.

Where the example master code shows:

    // Reading the potentiometer
    potValue = analogRead(A0);
    int potValueMapped = map(potValue, 0, 1023, 0, 255);
    Serial.write(potValueMapped); // Sends potValue to servo motor

You instead write:

    // Reading the potentiometer 1
    pot1Value = analogRead(A1);
    int pot1ValueMapped = map(pot1Value, 0, 1023, 0, 255);
    Serial.write(1);
    Serial.write(pot1ValueMapped); // Sends pot1Value to servo motor

    // Reading the potentiometer 2
    pot2Value = analogRead(A0);
    int pot2ValueMapped = map(pot2Value, 0, 1023, 0, 255);
    Serial.write(2);
    Serial.write(pot2ValueMapped); // Sends pot2Value to servo motor

And on the slave side, where the example has:

    if (Serial.available() > 0) { // Checks whether data is comming from the serial port
      state = Serial.read(); // Reads the data from the serial port
    }
    // Controlling the servo motor
    myServo.write(state);

You have to separate out the two possible choices:

    if (Serial.available() > 0) {
      servo_num = Serial.read();
    }
    if (Serial.available() > 0) {
      state = Serial.read();
    }

    switch (servo_num) {
      case 1:
        myServo1.write(state);
        break;
      case 2:
        myServo2.write(state);
        break;
    }

Note that you'll also have to declare the servo_num variable, and instantiate two of the Servo objects. The code above is just a guide.

The simple expansion above is *not* robust, as it's possible that the 2nd byte is not received by the time the 2nd `Serial.read()` is called, and then that byte would be caught next time around the `loop()` by the first `Serial.read()` call and you'd be out of sync. But hopefully, this shows the general concept of how to start developing a protocol that is more complex than just single values.

**Edit:** What's probably happening is the system is getting out of sync. As I noted, it's not a robust protocol, but I think you may now understand the idea.

You can re-map the servo values to go from 2-255, rather than 0-255, and set the `servo_num` to either `0` or `1`. In the slave, if you get a number `<2`, then it's a servo selector, otherwise it's a servo value. but then you lose the ability to set the servo to 0 or 1.

Also, you may want to space out the master sending the values, as you are likely sending data faster than the servo could respond. You could put a `delay(100)` or something in the `loop()` function, or change your code to use a `millis()`-based state machine (see the "BlinkWithoutDelay" Arduino example).


body:
I started a new project with an ESP8266-01 module. I want to use it as stand-alone circuit to send an Email at the press of a button.

The wiring is:

 - VCC    -  3.3v VCC
 - CH_PD  -  3.3v VCC
 - GND    -  GND
 - GPIO_2 -  Push down button (internal pullup)

I've the sketch (Arduino IDE), I've upload it and it essentially works. However:

 - If I call the `sendEmail();` method inside the `void setup(){}`, it works like a charm.
 - If I add an push down button on Pin #2 (GPIO_2) it only works if I previously have removed VCC from the CH_PD pin and reattached it again shortly after.

Now, I would bet I read something regarding (or similar) this situation a couple of days back, but I am unable to find it again, now that I need it.

Is there a solution for this or am I missing something?

Any help will be greatly appreciate it!

Thanks in advance!

title: ESP8266 only executes Sketch after switching on/off CH_PD pin

Answers: 1

body:
Well, after literally spending hours trying to figure out what the heck is going on, I decided to test the setup with a ESP8266-12 NodeMcu, which is essentially the same but more resembling to an Arduino in that it has more in/out pins and it's better for testing.

On this platform I got a different behavior. I was able to send an Email by the push of the button but... only once. So apparently, contrary to what I believed, something was wrong with the code.

In the code there is this method, which essentially initiates the WiFi connection:

    void initializeWifi(){

      WiFi.begin(WIFI, PASSWORD);

      // allow time to make connection
     while (WiFi.status() != WL_CONNECTED)  delay(5000);

      }

Somehow the `delay(5000);` didn't seem right as delay usually freezes the whole thing. When I commented out the line, everything worked as expected. With the NodeMcu as well as with the ESP8266-01.

However, I still have to figure out how to give time to the WiFi to connect without freezing out all together. Probably it's the time for `millis()`;

I hope this becomes useful to somebody else in the future.


body:
I am working on a DIY home automation project using a Wemos D1 Mini as the controller, and I ordered some 4-channel 5v-triggered relay boards. The ESP8266 that Wemos D1 Mini's are built on has GPIO output voltage of 3.3v, ostensibly too low to trigger the relays.

I've read a [Reddit post](https://www.reddit.com/r/arduino/comments/2aq28u/how_to_switch_a_5v_relay_board_using_a_33v_arduino/) that was saying that as long as you use a separate 5v power suppy for the relay board, 3.3v should be enough to trigger the relays. Is that accurate, or do I need to use a transistor or something to provide the relay board inputs with 5v?

title: Can I use a 3.3v GPIO to control an opto-isolated 5v relay board?

Answers: 2

body:
Yes, the [Reddit post's approach](https://www.reddit.com/r/arduino/comments/2aq28u/how_to_switch_a_5v_relay_board_using_a_33v_arduino/) is likely to work ok, as long as you correctly follow the cautions in it:  • connect the VCC pin of the relay board to a 5V source,
•  connect together the Arduino ground,  the relay ground, and the  5v-source ground.

Here is a typical relay-module circuit diagram (for one channel):[![typical relay-module circuit diagram (for one channel)][1]][1]

(Note, this diagram is from [a home automation blog](http://internetofthings-pune.blogspot.com/2013/07/this-is-open-source-home-automation.html); for more discussion and similar diagrams, see eg
[4-relay-shield-diagram](http://arduino-direct.com/docs/4-relay-shield-diagram.jpg) at [yourduino.com](http://www.yourduino.com/sunshop/index.php?l=product_detail&p=171) and [stripboard-shield-relay-sm](https://startingelectronics.org/projects/arduino-projects/arduino-tiny-relay-shield/stripboard-shield-relay-sm.png) at [startingelectronics.org](https://startingelectronics.org/projects/arduino-projects/arduino-tiny-relay-shield/).)

As you can see in the diagram, the Arduino pin that connects to JP2-2 will not be exposed to voltages.  (The base of an NPN transistor effectively is at the junction of two back-to-back diodes.)

When the Arduino or ESP pin at JP2-2 is at about 0 V (ie, when the Arduino pin is off) IBE=0; that is, no Q2 base-emitter current will flow; thus, Q2 will be off, so that both of LED1 and relay U1 will remain off.

When the Arduino or ESP pin at JP2-2 is at about 3.3 V (ie, when the Arduino pin is on) IBE is about 2.5 mA, which should be enough to reduce VCE to about 1 V, leaving 4 V across the relay coil, or enough to turn it on.

Note, the 2.5 mA figure for this circuit is calculated as follows:  IBE = (3.3-VBE)/1000 - VBE/10000 = (3.3-0.7)/1000 - 0.7/10000 = .00260 - .00007 = .00253 A = 2.53 mA.  Note that the alternate circuit diagrams linked above don't have a 10KΩ resistor like that in the diagram above, so instead of about 2.5 mA would have about 2.6 mA drive.

If for some reason you don't have quite enough base drive – in which case you might be able to hear a slight click from the relay, even if it doesn't switch – you could increase the "5 V" line into the LED and relay to say 5.5 V or 6 V.  As noted before, the  back-to-back diodes structure of the NPN transistor will isolate that voltage from your Arduino or ESP.

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

body:
Short answer : it will probably work.

If your relay board is opto-isolated, there is a small potential risk that 3V3 may not be enough to lit the optocoupler sufficiently, you will have to test it.

The reddit board is not using optical separation but only a transistor, like on the schematic of the answer above,. In that case, 3V3 is always enough to saturate the transistor. Anything above around 1V5 would probably do, but this can vary according to the resistors, relay consumption and transistor gain.

There is an extensive discussion of this topic at https://www.forward.com.au/pfod/HomeAutomation/OnOffAddRelay/index.html#Mods3v3


body:
I’d like to connect two Arduinos over serial port so that they can communicate with each other. Initially, I put all necessary code onto one device and now connected another via serial port. As soon as I connected the second one I lost the ability to upload new code onto the first one. I’m certain they are conflicting over serial pins. I tried to hold reset on the second Arduino, but it didn’t help. The only way to flash it back again with avrdude is to disconnect the second one.

Is there a way to get this setup working with serial bootloader without disconnecting pins? Thanks for your ideas.

I do not use the Arduino IDE. I believe that if someone has a solution for Arduino it will work for me. I use Atmel Studio 7 with avr gcc. The boards are Chinese clones with ATMega328P on them flashed with the optiboot bootloader. Pins connected are TxD and RxD to opposites on the second board. They are powered from the same power supply. This question is not how to communicate with another Arduino. This question is how to still be able to flash one Arduino while something else is connected to its serial port. I know that the USB to serial bridge IC is connected, but this is a standard setup on all Arduinos that have no embedded USB controller.

Board is Arduino Nano v3 clone with CH340 USB<->UART chip. Both boards work OK by themselves, once connected together they stop responding to avrdude. The connection is as following. Length of connection is only 15cm.

    Nano v3 (1)        |          Nano v3 (2)
        |              |              |
    RX0 o-----+------~ ~ ~------+-----o TX1
        |     |        |        |     |
    TX1 o---+-|------~ ~ ~------|-+---o RX0
        |   | |        |        | |   |
          --o-o--      |      --o-o--
           CH340       |       CH340
             ^         |         ^
             |         |         |
            USB        |        USB

title: Bootloader fails when two Arduinos are connected over serial port

Answers: 0


body:
I am wondering if it's possible to transmit on all frequencies at once using [this module][1].

I know it's illegal to take over regular stations when others are trying to listen but I'm only planning to use it for short range (less than the length of my house).

  [1]: https://www.amazon.com/dp/B01MS9RO2Y/ref=asc_df_B01MS9RO2Y5288056/?tag=hyprod-20&creative=395033&creativeASIN=B01MS9RO2Y&linkCode=df0&hvadid=226131567976&hvpos=1o1&hvnetw=g&hvrand=12369799530943192231&hvpone=&hvptwo=&hvqmt=&hvdev=m&hvdvcmdl=&hvlocint=&hvlocphy=9022821&hvtargid=pla-348168842533

title: Arduino FM transmitter

Answers: 2

body: No, this is a receiver only, not a transmitter.

body:
> I am wondering if it's possible to transmit on all frequencies at once using this module.

it is definitely possible to transmit on all frequencies at once ***NOT*** using that module: square waves are a combination of all sorts of frequencies and your arduino is good at producing that.


body:
I have a seemingly simple problem but I haven't found a solution yet. I recently got a DHT22 temp/humidity sensor and I wired it according to [the guide from Adafruit][1].

I downloaded and installed the library. I loaded the "DHTtester" example sketch. I also included the Adafruit Unified Sensor library to be safe, because the guide said I might need to. But when I upload the sketch and check the serial monitor the humidity value is always "1.00%". The temperature also seems to be off by about 4 degrees F.

I don't know what is going wrong here. I've removed the 10K resistor but nothing changed. Does anyone know why this might be happening? Any help would be appreciated. Thanks!

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

  [1]: https://learn.adafruit.com/dht
  [2]: https://i.stack.imgur.com/VjMEP.jpg
  [3]: https://i.stack.imgur.com/Z0HmT.jpg

title: Why is my DHT22 sensor reading 1.00% humidity?

Answers: 3

body: This problem mainly happens when DHT11 sensor is mistaken with DHT22 or vice versa. Try testing it for DHT11, can you send the picture of sensor and circuit connection if possible.

body:
I have 2 suggestions for you.

1. If you compare these 2 data sheets:
[This one says "adafruit learning systems" on it][1]
and [this one is from the Adafruit website][2]
  [1]: https://www.mouser.com/ds/2/737/dht-932870.pdf
  [2]: https://cdn-shop.adafruit.com/datasheets/Digital+humidity+and+temperature+sensor+AM2302.pdf
, you'll see there is a discrepancy regarding the pull-up resistor value to use. One document says 10k ohm, the other says 1k ohm. It's a bit of a long shot, but you could try adding another 10k ohm resistor in parallel with the one you already have on the data line. This gives you an equivalent resistance of 5k ohm which works when used on a DHT11 sensor (cheaper, less accurate version of the DHT22).

2. There are several versions of the DHTxx library out there, so my next suggestion is to try a different one. You may have to remove the library you currently have installed before trying a new one.

body:
When I have rigged up these sensors to test, I breathe on them. Both the temperature and humidity should rise as breath is warm and humid.

From memory, I have seen the humidity rise from ~40% to ~70%, and temperature by at least 5 degrees.

If you see temperature rise but not humidity, then the humidity part may not be working (perhaps as smajli suggests).

There is also a checksum in the data, so I imagine that if there was a problem with communications, the result would be -1 or nothing at at all.


body:
I am working on a project where I would like values received from an Xbox Kinect will activate components on my Arduino. Currently, I am trying to get a servo motor to turn on and rotate when the value is "1" and to remain in one position (currently written as 120degrees) when the value is "0". However, I can turn on the motor and initiate rotation just fine, but when I let go of the mouse (and it shows that the value "0" is being sent in Processing and on the Serial Monitor), the motor just keeps spinning. This is my current code:

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

    char val; // Data received from the serial port
    #include <Servo.h>
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

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

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

    void loop() {
      if (Serial.available())
      { // If data is available to read,
        val = Serial.read(); // read it and store it in val
      }
      if (val == '1') { // If 1 was received
        Serial.print ("1");// turn the LED on
        for (pos = 0; pos <= 120; pos += 1) { // goes from 0 degrees to 180 degrees
          // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(15);                       // waits 15ms for the servo to reach the position
        }
        for (pos = 120; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(15);                       // waits 15ms for the servo to reach the position
        }
      }
      if (val == '0') {
        Serial.print ("0");
        pos = 120;
        myservo.write(pos);
      }
    }

title: How do I stop a servo motor at the current position when using a serial port? I want it to remain in one position when receiving "0"

Answers: 2

body: Are you sure the mouse is not sending a continuous stream of 1s? If that were the case then, because of buffering, all the 1s will serviced before the servo stops. For example, a sequence of 11111 followed by a 0 will cycle the movement 5 times before it stops and prints the 0.

body:
fairly simple:

    switch (serial_received()) {
      case -1: break; //-1=nothing received
      case  0: break; //0 received
      case  1: servo_pos = ...; servo_move2(servo_pos); break; //update servo position
      case  .... //other commands
      default: ...
    }

you can fill in the functions with whatever appropriate for your environment.


body:
I have several Pro Micro clones.

This morning I uploaded a sketch into one of them (that was previously unprogrammed, so it stayed in bootloader mode) and when I wanted to upload the sketch a second time, the problem began:

When I now run the reset procedure for Arduinos with integrated USB (open the COM port of the Pro Micro for example in [PuTTY][1] at 1200 bit/s and close it again), **the LEDs start flashing rapidly and the Arduino disappears from the Windows Device Manager**.

Hover for a (slightly annoying) image:
>! [![LEDs flashing][2]][2]

So then I grabbed a second, identical Pro Micro and uploaded the Blink sketch into it. It was also previously unprogrammed. The sketch executed, but when I now do the reset procedure, it exhibits the same behavior now (flashing LEDs).

I can still upload sketches just fine, by setting the COM port to a different (arbitrary) COM port to prevent the reset procedure from reaching the Pro Micro and resetting the Pro Micro manually after starting the upload procedure.

This only happens with the 3.3 V/8 MHz variant, not with the 5 V/16 MHz variant. I have selected the appropriate variant in the IDE.

How can I repair the automatic reset function?

  [1]: http://en.wikipedia.org/wiki/PuTTY
  [2]: https://i.stack.imgur.com/OtBD5.gif

title: 3.3 V Pro Micro clones flashing LEDs after 1200 bit/s touch

Answers: 2

body: Arduino Pro micro will enter bootloader if you connect it with 1200 baudrate. See this pos https://arduino.stackexchange.com/questions/25346/upload-code-on-arduino-leonardo-using-command-line/31785#31785

body:
I was finally able to solve this by using one of the Pro Micros to re-burn the bootloader of the other one.

For reference, the process is like this:

1. Flash the example sketch "ArduinoISP" into the first Pro Micro
1. Connect the two Pro Micros like this:

        Programmer (on USB)   Target
        GND ----------------- GND
        VCC ----------------- VCC
        15 ------------------ 15
        14 ------------------ 14
        16 ------------------ 16
        10 ------------------ RST

1. Choose "Arduino as ISP" as Programmer
1. Because both are Pro Micros, selecting a different board is not necessary.
1. Click "Burn Bootloader"


body:
I am trying to connect a Bluetooth module and a gas sensor to Arduino.

- Bluetooth module: [HM-10][1]
- Gas sensor: [MQ-2][2]

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example.

I would like you to give me a link to an example that uses the 5v pin for multiple modules. It would be nice if the circuit configuration was included.

  [1]: http://www.eduino.kr/product/detail.html?board_no=4&product_no=317&cate_no=58&display_group=1&keyword=
  [2]: http://www.eduino.kr/product/detail.html?product_no=120&cate_no=34&display_group=1

title: How to connect Arduino 5v pin with multiple things?

Answers: 2

body:
The simplest way is to just use a breadboard to connect your devices to your Arduino:

![breadboard][1]

I can't read Chinese, so I can't check the specifications of these particular devices, but you need to be aware of the power limitations on your Arduino.

The maximum total current you can draw when the device is powered via external power supply is 1A for the [Arduino Uno][2], 800mA for the [Due][3] and 500mA for the [Nano][4]. Check the specs for your board on the [Arduino site][5].

Arduino-compatible devices may vary - check the specs for the device you're usiing.

Note: If you're not powering your board via USB, the total 5V current limit coming out of the Arduino is limited by the voltage regulator on your particular board, and/or your input power supply (whichever provides less power).

  [1]: https://i.stack.imgur.com/y9q7E.jpg
  [2]: https://store.arduino.cc/arduino-uno-rev3
  [3]: https://store.arduino.cc/arduino-due
  [4]: https://store.arduino.cc/arduino-nano
  [5]: https://www.arduino.cc/

body:
5V is just 5V. It's not a signal, it's just a voltage level. If you need to connect multiple things to it then just connect multiple things to it. If that means connecting wires together then so be it.

Yes, you can use breadboards for it, but that's pretty wasteful if all you want to do is connect a few 5V wires together. It's simpler just to strip the ends and twist them together. Maybe add some tape to insulate them so you don't get accidental short circuits.


body:
I have Arduino UNO board. Can I upload programs written in Lua?
I wrote a code for simple home automation using relays to control lights and tried to upload it to my Arduino board, I get error code of "Error compiling for board Arduino/Genuino Uno"? What does this mean?

This is the code I used:

<!-- language: lang-lua -->

    var("Switch", "ME.BI21")
    var("Relay", "ME.BO21")
    var("RelayState", "ME.BO41")

    RelayState = 1

    Relay = Switch

    if (Relay == 1 then){
      print("The Relay is ON")
    }
    else{
      print("The Relay is OFF")
    }
    end

title: Uploading Lua code to Arduino

Answers: 1

body: The Uno can’t run Lua code. The ESP8266 modules like the Wemos D1 or NodeMCU can, with the right firmware.


body:
**Problem**

I have an Arduino Duemilanove which needs to communicate with an Ardiuno Mega.  The only pin available on the Duemilanove is D13.  The Duemilanove is in charge of driving state on my robot, and the Mega is in charge of sensor readings and navigation.  The Mega needs to send drive state updates to the Duemilanove.  I2C, PWM, Serial, anything requiring different pins on the Duemilanove is out of the question at this point.

**Idea**
I plan to have the Duemilanove send the "pipe" pin high, triggering an interrupt on the Mega.  The ISR will send the current drive state to the Duemilanove which will change pinmode and read a digital pulse.  The length of the pulse is the drive state.

**Roadblock**
I am having trouble finding an example of how to set this up.  I can't get the ISR to fire, and I'm not sure why.

**Mega Code**

    int pipe = 18;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(pipe, INPUT);
      attachInterrupt(digitalPinToInterrupt(pipe), driveStateISR, CHANGE);
    }

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

    }

    void driveStateISR(){

      Serial.println("ISR fired");
      pinMode(pipe, OUTPUT);

      digitalWrite(pipe, HIGH);
      delay(50);
      digitalWrite(pipe, LOW);

      Serial.println("Pulse sent!");

      pinMode(pipe, INPUT);

    }

**Duemilanove Code**

    int pipe = 13;

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

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(pipe, HIGH);
      delay(30);
      pinMode(pipe, INPUT);

      unsigned long duration = pulseIn(pipe, HIGH);

      Serial.println(duration);

      delay(3000);
    }

Nothing happens at all.  I'm thinking the main framework is here, but since there aren't many examples of this out there I'd love to get some other eyes on the issue.  Thanks!

title: Make one Arduino fire interrupt on another

Answers: 2

body:
since it is one-way communication, it should be fairly simple, as long as you decide what the protocol you intend to use.

it could be pwm for example -> the duty cycle is the encoded data; or analog output; or uart tx; ...

after that, pick who the master is and who the slave is. generally it is (much) harder to code a slave so pick the slave that has the necessary hardware on the pin you have and go from there.

body: You should not do `delay()` or `Serial.print()` inside an ISR. That would cause it to hang. For more information see [my page about interrupts](http://www.gammon.com.au/interrupts) and also https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969


body:
I'm trying to use Timer1 to get fired once a certain event occurs (about 1ms after the event). Using the timer to get a periodic interrupt works fine, but the very first interrupt fires immediately, rather than after the time I want it.

    #include <Arduino.h>

    void setup() {
      Serial.begin(115200);
      Serial.println("start");
    }

    #define ENTRIES 5
    long stack[ENTRIES+1];
    int ctr = 0;

    ISR(TIMER1_OVF_vect) {
      cli();
      TCNT1 = 50000;

      // if (micros() - stack[0] < 500) return; // work around guard would skip stray 1st interrupt

      stack[ctr++] = micros();

      if (ctr > ENTRIES)
        TIMSK1 &= ~(1 << TOIE1);

      sei();
    }

    void loop() {
      if (ctr > ENTRIES) {
        for (int i = 0; i < ENTRIES-1; i++) {
          Serial.print(i);
          Serial.print(": ");
          Serial.println(stack[i+1] - stack[i]);
        }
        ctr = 0;
      }

      if (!Serial.available()) return;
      char c = Serial.read();
      if (c == 't') {
        Serial.println("testing");

        stack[0] = micros();
        ctr = 1;
        cli();

        TCNT1 = 64000; // tick in around 1ms
        TCCR1A = 0;
        TCCR1B = (1 << CS10); // no prescaler
        TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt

        sei();
      }
    }

When you enter `t` on the console it enables the interrupt and - unexpectedly - the timer fires at once. The next one comes after 1ms. A sample output looks like

    start
    testing
    0: 8
    1: 980
    2: 980
    3: 980
    testing
    0: 8
    1: 980
    2: 980
    3: 980

Uncommenting the guard yields

    start
    testing
    0: 988
    1: 972
    2: 976
    3: 976

How can I modify my code (except setting a guard in the beginning of the ISR) so it is triggered once AFTER 1ms.

title: Timer1 firing immediately

Answers: 1

body:
Interrupt flags are set even without interrupt enable flags, so there is pending overflow that you didin't cleared. And guess what happens after enabling `TOIE1` flag. It gets handled by `ISR`. That's on behalf of Arduino's `analogWrite()` PWM outputs (all timers are up and running in 8bit mode and 1.024ms period).

Btw global interrupts are disabled and reenabled inside of `ISR` handler by hardware so you shouldn't have `cli()` and `sei()` in it.

Also there is another issue - counter mode is preset to 8bits and much bigger prescaler, so the first round is way off.

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

    void setup() {
      Serial.begin(115200);
      Serial.println("start");
    }

    #define ENTRIES 5
    long stack[ENTRIES+1];
    int ctr = 0;

    ISR(TIMER1_OVF_vect) {
      TCNT1 = 50000U;
      stack[ctr++] = micros();
      if (ctr > ENTRIES)  TIMSK1 &= ~(1 << TOIE1);
    }

    void loop() {
      if (ctr > ENTRIES) {
        for (int i = 0; i < ENTRIES-1; i++) {
          Serial.print(i);
          Serial.print(": ");
          Serial.println(stack[i+1] - stack[i]);
        }
        ctr = 0;
      }

      if (!Serial.available()) return;
      char c = Serial.read();
      if (c == 't') {
        Serial.println("testing");

        stack[0] = micros();
        ctr = 1;

        TCCR1A = 0;           // you have to change the timer mode before changes
        TCCR1B = 0;           // stop the timer
        TIFR1 |= _BV(TOV1);   // clear the overflow interrupt flag by writing 1 to it
        TCNT1  = 50000U;      // tick in around 1ms / this makes more sense if it's set correctly
        TCCR1B = _BV(CS10);   // no prescaler ?????  REALLY???? this one is prescale by 8
        TIMSK1 |= _BV(TOIE1); // enable timer overflow interrupt
      }
    }


body:
I was trying some AT commands using the monitor of the Arduino Web Editor with an Arduino Uno and a ESP8266 module. It was working at 115200 bauds but then I changed it with `AT+CIOBAUD=19200` and now it can't communicate.

How can I change the baudrate to 115200?

Now I see this:

[![Monitor with weird characters.][1]][1]

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

title: I change ESP8266 baudrate and now it doesn't work

Answers: 1

body:
Have you tried setting the web editor's baud rate to both the old and the new values? I ask because the CIOBAUD command has been obsolete for a while now so, depending on the age of your device, it may have done nothing. The command was replaced by "AT+UART_CUR" and "AT+UART_DEF" which have a different syntax.

See [this answer][1] to a similar question.

Update:

Yes, here's an example:

    // Declare a serial object to talk to ESP8266
    SoftwareSerial EspSerial(WIFITX_PIN, WIFIRX_PIN);  // RX, TX

    void setup(void){
       // Init WiFi serial
       EspSerial.begin(9600);
       delay(10);
    }

I've used 9600 baud in my example since SoftwareSerial may not work well at faster speeds.

Update 2:

> Is it possible to send AT commands from the code instead of the
> monitor?

Yes, easily. Once the above code has run (and note that I've deleted an unnecessary line since update 1), you can send strings to the ESP with EspSerial.print() and EspSerial.println(). Here's an AT command example:

    // Set 9600 baud, standard 8-bit frame, and save as power-on default:
    EspSerial.println("AT+UART_DEF=9600,8,1,0,0");

  [1]: https://arduino.stackexchange.com/questions/24156/how-to-change-baudrate-of-esp8266-12e-permanently/24191#24191


body:
I am trying to read a file from sd card and parse them to polymorphic objects, then have an array of pointers to them so i can access them later.

I was wondering what the best format would be to save these objects in, i was looking at https://github.com/bblanchon/ArduinoJson but i don't know if it's possible to deserialize them to the right object.

Is this even possible?

title: Parsing sd card file to polymorphic objects

Answers: 1

body:
There is no such thing as serialization/deserialization in C++. You can read the data values from an object, and you can write data values to an object, as long as you either expose the properties as `public`, or create "getter" and "setter" member functions.

It is then up to you to store and retrieve that data in whatever form you like.

You could store the raw RAM data that corresponds to an object, however if there are any pointers in that object they will be stored as just that - a pointer - which will be meaningless when reloaded. So it's better to store the data values manually.

How you store the data depends on what the data is. Yes, you can use JSON format if you so choose - it has good abstraction for storing strings, escaping special characters, etc. So it would be quite convenient - however, it's quite a heavyweight arrangement. A lighter method would be to store binary data directly, but that is inflexible and can't easily store different types of data in different ways for different objects.

CSV format is quick and easy to parse, but you have to manually deal with things like commas in data strings, etc.


body:
I set up a serial connection and sending integers from a Raspberry Pi to an Arduino.

This is the Python code in my Raspberry Pi:

    import serial
    ser = serial.Serial('/dev/ttyACM2', 9600)
    ser.write(str(x_value));

And this is the command line output for `x_value`:

> -38 -38 -38 -40 - 38 - 39 - 40 - 12 18 26 25 49...

They are x coordinate values I generated and they range from -100 to 100. And here's the Arduino code for receiving serial data:

    int ByteReceived;

    void loop() {
      while(1) {
        if (Serial.available() > 0) {
          ByteReceived = (Serial.read());
          Serial.print(ByteReceived);
          Serial.print("\n");
        }
      }

On the serial monitor I'm receiving these numbers:

> 46 45 51 48 45 53 52 45 49 52 45 52 55 55....

They are numbers between 40-60 and no way proportional to the values I sent from `serial.write`.

I'm really confused right now. Can someone help me to figure out what caused this problem?

Thank you so much.

title: Getting wrong values from serial.read() connected to a Raspberry Pi

Answers: 1

body:
    ser.write(str(x_value));

Writes the string representation of the integer `x_value`, which is a sequence of ASCII characters.

    ByteReceived = (Serial.read());
    Serial.print(ByteReceived);

Reads a character (byte) and prints to the value (again as a sequence of characters).

    45 51 48 45 53 52 45 49 52 45 52 55 55....

`45` is ASCII character value for the character '-', `51` is the character '3', `48` is '0' and so on.

Cheers!


body:
I am new to working with Arduino and I have a basic question.

I have an entire circuit set up and functioning, but I would like to add an arcade style button (Larger concave style) like [this](https://www.sparkfun.com/products/9337).

So my question is, how would I go about wiring this button to the Arduino? I don't need this button to control any lights or any other functions. The basic function of this button is for my code to register if the button is pressed or not. I also have the code done. I just want to know how to wire this.

Also I don't know if this helps, but I already have two normal tactile buttons (with 4 pins) in the circuit connected with a pull-up resistor and I know how to connect them. I just have no idea how to go about with only 2 pins.

Any help would be greatly appreciated. Thanks.

title: Concave button wiring with Arduino

Answers: 1

body:
A simple switch, frequently called single pole single throw, will have only two pins. A switch works by breaking the circuit. This is shown in a wiring diagram in this manner:

[![spst switch][1]][1]

It matters not that the switch in this image is not the same switch as in the image you linked, the operation is identical. You may find momentary switches with similar appearance and identical diagrams. The difference is that one has to hold the button to make (or break) a circuit, which reverts once released.

You mention four pins. Those switches are electrically identical to the SPST switch, except that you may find you can control two independent circuits that both activate when the button is pressed. That would be a double pole single throw. There is also the possibility that the four-pin switch has common connections on each side. That is to say that if you connect your circuit to one pin, it is conductive to the other on on the same side, while the closure of the switch will also equally effect the two pins on the opposite side. I've found some tiny switches that have this arrangement, ostensibly to provide for four points to solder to the circuit board, making for a more sturdy attachment.

One can find some useful switch information on [Electronics Hub][2], which is too exhaustive to cover here.

There are many other types of switches

  [1]: https://i.stack.imgur.com/3vtyd.png
  [2]: https://www.electronicshub.org/switches/


body:
I am creating a project in which an Arduino reads (gets) a value from
a DHT sensor. The DHT sensor returns two values:

1. Temperature
2. Humidity

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

My assembly code:

    sbi ddrd,5
    cbi ddrd,2
    sbi portd,5

    start:

    in r16,Pind2
    cpi r16,80
    brne On

    jmp start

    On:
    cbi portd ,5
    jmp start

After the code, the light remains turned on, but if the sensor sends '80'
and I get it correctly it should be turned off.

Question: Am I Using the write way to read a pin?

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

title: Reading from a pin Arduino Uno (assembly)

Answers: 2

body:
You are simply reading the state of the input pin - this won't work.

Study the datasheet for the DHT22, available from Sparkfun or eslewhere.

To get data from the DTH22, you must first send a start signal, wait a specified time, then watch the level of the data line, measuring the time of each bit to determine whether it is a 1 or 0, and store the bits in five 8-bit variables.  You can then examine those variables to determine the temperature and humidity.

body:
 Instructions for **writing** to an individual output bit:-

     sbi portd,5 ; make Port D output bit 5 high (set)

     cbi portd,5 ; make Port D output bit 5 low (clear)

     sbi pind,5  ; toggle Port D output bit 5 (low -> high, high -> low)

Instructions for **reading** an individual I/O pin:-

     sbis pind,2 ; skip next instruction if Port D pin 2 is high

     sbic pind,2 ; skip next instruction if Port D pin 2 is low


body:
How to reduce sketch size?

I got an error that “Sketch uses 30,044 bytes (104%) of program storage space. Maximum is 28,672 bytes.”

I can't reduce function in sketch.I can't change ATmega32u4,now.
The sketch has function of measuring sensor,logging on SD,connection with BLE module.

So please tell me hack.

Or,how to increase flash memory size?

I tried to change type of String to Char.

title: How to reduce sketch size?

Answers: 4

body: There's no magic bullet. You have to work through your code and see what you can remove safely. If you have duplicate code, put it in a function and call this. If you `Serial.print` a lot of text, considering saving up on that. etc etc etc

body:
> How to reduce sketch size?

without your code, tough to be specific. but generally:

1) try not to use floating pointmath;

2) try not to use printf() or its derivative;

3) try to minimize large arrays;

4) use functions instead of macros;

5) use modular programming;

...

> Or,how to increase flash memory size?

1) use a bigger chip;

2) use onboard eeprom;

3) use outboard eeprom / flash / fram / ....

4) divide up the tasks among multiple chips;

...

body:
Some generic techniques you can try:

- Remove duplicate code and put it in a function.
- If you have duplicate code that is ALMOST duplicate, parameterize it (i.e. add a function, make the difference a parameter(s) of the function and call from various locations with different argument(s).
- Use a micro controller with more Flash memory.
- Minimize the data storage, limiting array sizes for example (if these are in flash RAM).
- If you use precalculated arrays, remove them and create a function calculating them real time (this will be a performance cost of course).
- Check for dead code inside functions. A smart compiler will already remove uncalled functions, but do not check inside functions.
- Remove or minimize debug/print statements. Each character cost a byte, which adds up quickly with many strings.
- Try to remove complete libraries, like removing the Serial for print statements used only for debugging.

body:
If you're using donated libraries to run your hardware (such as the Dallas Temperature library) or provide software features (like SimpleTimer), the authors often provide a full complement of features, some of which you may not need. I often make my own versions of these libraries that provide the functionalities I must have, and cut out the others. I can always add one or two of them back into whichever sketch needs them, without burdening other sketches with their overhead.

In SimpleTimer, for instance, I seldom have need for enable/disable timer or for a timer that runs N-times and then stops, so I have a version of the library with those functions removed.

If you've declared some text strings or other data to live in Flash, and you have more spare RAM than spare Flash, let some of those objects live in RAM instead. Or reduce the length of output strings that are stored in Flash by writing more tersely, even at the cost of clarity in the output, or eliminating that outpu altogether (which eliminates not only the string data but the code to print it, as well).

Can you reduce any code segments or algorithms with more space-efficient code? Can you eliminate some functionality to save code space?

Note that trimming buffers and arrays won't help because those are in RAM, and data packing, such as storing a number of booleans as distinct bits within a word, will actually increase your code size (this is a common way to reduce RAM requirements when you can afford the code to do the packing/unpacking, but you have the opposite problem!).


body:
I'm trying to send the byte `0x5A` (`0b01011010`) on the serial output of an Arduino Due. My program is based on [this example project](https://github.com/klangner/arduino-due-rust), but I've stripped out all the unrelated parts:

    #![feature(lang_items)]
    #![no_std]
    #![no_main]

    extern crate sam3x;

    pub mod rust_base;
    use sam3x::*;
    use sam3x::hal::peripherals::{Peripheral};
    use sam3x::drivers::led::{Led};
    use sam3x::hal::rtt::{init_timer, wait_ms};
    use sam3x::hal::pmc;
    use sam3x::hal::uart;

    #[link_section=".vectors"]
    pub static VECTOR_TABLE: VectorTable =
        VectorTable {
            reset_handler : start,
            exceptions    : [0; 14],
        };

    fn start() -> ! {
        init_timer();
        pmc::enable_peripheral_clock_0(Peripheral::PioC);

        let led = Led::connect(Peripheral::PioB, 27).expect("Wrong pin for led.");
        let tx = uart::Tx::init(uart::BR_9600);

        let mut led_on = true;
        led.on();
        loop {
            tx.write_byte(0b01011010);

            wait_ms(250);
            if led_on {
                led.off()
            } else {
                led.on()
            }
            led_on = !led_on;
        }
    }

As you can see, all I do is send out the byte `0x5A` four times a second, with some LED blinking just to show the program is running.

My problem is that if I connect a serial terminal program with 9600-8N1 settings, I am not getting `0x5A`; instead, I am getting mostly `0xBA`, and sometimes a `0x9A` slips through.

Writing out the bits:

    0101 1010    5A
    1011 1010    BA
    1001 1010    9A

Note that the lower nybble is always correct, which is why I don't think it's a serial communication setting issue; also, it's pretty clear from [`uart::Tx::init`'s implementation](https://github.com/klangner/sam3x/blob/a34e0e2241951f49e1a990e05fe45175fafb95c5/src/hal/uart.rs#L84) that it defaults to no parity bits.

title: Garbled high bits on serial output

Answers: 1

body:
It seems this error is specific to the Rust ARM library I am using; quoting from https://github.com/klangner/sam3x/issues/9:

> It looks that at bound rate=9600 the timer sends data with the speed of ~888. And then computer can't understand the output.

Based on this, I started playing around with the baud rate I pass to the library when initializing it, and using 11000 instead of 9600 empirically seems to work (i.e. I am seeing a steady stream of `0x5A` on my PC receiving at 9600).


body:
I have an Arduino project that needs to receive data from ThingSpeak. [This][1] is the data that I'm supposed to get.

When the data is "true" it must turn the LED on. I tried this code in hope of getting "true".

    void loop() {
      Serial.println();
      Serial.println("Receiving Trigger Data...");
      if (client.connect(server, 80)) {
        Serial.println("Connected to server");
        client.println("GET /channels/344468/fields/3/last?key=XXXXXXX HTTP/1.1");
        client.println("Host: api.thingspeak.com");
        client.println("Connection: close");
        client.println();
    }
    while (client.available()) {
      reply = client.read();
      content.concat(reply);
    }
    delay(3000);
    Serial.println(content);
    if(content.indexOf("Content-Length: 4") > 0) {
      digitalWrite(ledPin, HIGH);
    }

The Serial Monitor gives this reply. I don't see the word "true" being returned at all and I don't also see the content length. I tried putting delays but still I don't receive the "true" or even just the content length. Please help.

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

  [1]: https://thingspeak.com/channels/344468/fields/3/last
  [2]: https://i.stack.imgur.com/60VSr.jpg

title: Receiving incomplete HTTP request

Answers: 0


body:
I'm including this library "ESP8266WiFi.h" at the top of my sketch.
I can find documentation on `WiFiServer.available()`, but didn't find for `WiFi.connected()`, which is called in a server sketch after getting the client.

Clearly it's a test whether (once? I believe) the client is connected or not (and hasn't been explicitly closed in the server's side). It may seem obvious but some documented info would be helpful though.

title: Arduino IDE documentation for WiFi.connected()

Answers: 1

body:
You'll find it defined in `WifiClient.h`. The version I am using is, in `WifiClient.cpp`:

    uint8_t WiFiClient::connected() {
      if (!_client)
        return 0;
      return _client->state() == ESTABLISHED || available();
    }


body:
I have made a home automation project where am using an Arduino Uno and HC-05 Bluetooth module and an Android app. I did everything properly but when I send commands from my Android app it works sometimes and sometimes it doesn't work.

I checked these commands on the serial monitor and found that data command I recieve at serial monitor did not match the commands which I send from my Android app. For example my Android app send command "ON1" but on serial monitor it shows "OL1?". I thought it might be a problem with the HC-05 so I changed it and used a new HC-05 module, but the problem is still there.

This time I checked the commands from another Android app (Bluetooth Terminal HC-05) and there was the same problem. Sometimes it read the command correctly app and sometimes it read something else.

I am so confused weather the problem is in my hardware side or software side.I tried a lot but didn't get any solution about my problem anywhere. Can anybody help me please?

This is the Arduino code of my project:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial Genotronex(2, 3); //TX, RX  pins of arduino respetively
    String command;
    void setup() {
      Genotronex.begin(9600);
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
    }

    void loop() {
      while (Genotronex.available()) {
      //Check if there is an available byte
        to read
        delay(10); //Delay added to make thing stable
        char c = Genotronex.read(); //Conduct a serial read
        command += c; //build the string.
      }
      if (command.length() > 0) {
        Serial.print(command);
        if (command == "ON1") {}
        //this command will be given as an input to switch on light1
        digitalWrite(9, HIGH);
      } else if (command == "OFF1") {
        //this command will be given as an input to switch off light1 simillarly other commands work
        digitalWrite(9, LOW);
      } else if (command == "ON2") {
        digitalWrite (10, HIGH);
      } else if ( command == "OFF2") {
        digitalWrite (10, LOW);
      } else if (command == "ON3") {
        digitalWrite (11, HIGH);
      } else if (command == "OFF3") {
        digitalWrite (11, LOW);
      } else if (command == "ON4") {
        digitalWrite (12, HIGH);
      } else if (command == "OFF4") {
        digitalWrite (12, LOW);
      } else if (command == "ON5") {
        digitalWrite (13, HIGH);
      } else if (command == "OFF5") {
        digitalWrite (13, LOW);
      } else if (command == "all on") {
        //using this command you can switch on all devices
        digitalWrite (9, HIGH);
        digitalWrite (10, HIGH);
        digitalWrite (11, HIGH);
        digitalWrite (12, HIGH);
        digitalWrite (13, HIGH);
      } else if (command == "off") {
        //using this command you can switch off all devices
        digitalWrite (9, LOW);
        digitalWrite (10, LOW);
        digitalWrite (11, LOW);
        digitalWrite (12, LOW);
        digitalWrite (13, LOW);
      }
      command = "";
    } //Reset the variable

title: HC-05 Bluetooth module doesn't read data correctly from my Android phone

Answers: 1

body:
I suggest to have a look at this answer:
https://arduino.stackexchange.com/questions/47017/change-the-baud-rate-of-hc-05/47022#47022

In many case and especially when you send data from Android and receive bad data on Arduino, it's because the speed is not set correctly.
On the other side (getting data from the Arduino), it's a bit more complicated. You have to build your own "time out" system on Android as the Bluetooth library don't have such a feature.


body:
I got this display on ebay and I have no instructions on how to use it. I can guess what most of them do but I'd rather be sure I know what they all are instead of messing around trying to guess. The ebay page said the screen is a KS0107+KS0108 128x64 display.

[![photo of screen][1]][1]

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

Is there any documentation on what these pins do and which ones I need to connect to my arduino uno to get it working?

title: What do the pins on this KS0107+KS0108 display do?

Answers: 1

body:
[glcd-arduino][1] (GLCDv3) is an unofficial Arduino library that supports Graphic LCDs (GLCD) that use the KS0108 (or equivalent) chip.

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

  [1]: https://playground.arduino.cc/Code/GLCDks0108
  [2]: https://i.stack.imgur.com/Oy855.jpg


body:
I am having issues with the ArduinoYun. It's not showing any data in the serial monitor. The sensor lights up when I plug it in but that's about it and the code seems to compile but nothing is coming through. I am using the Adafruit color sensor. I have SDA/SCL connected to pins 4 and 5. The servo is connected to pin 3. The rest is just on Vin and GND.

    #include "Servo.h"
    #include "Wire.h"
    #include "Adafruit_TCS34725.h"

    const int redPos = 160;
    const int orangePos = 130;
    const int yellowPos = 100;
    const int greenPos = 70;
    const int bluePos = 30;
    const int nonePos = 0; // Kein Objekt erkannt

    Servo myservo;

    Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X);

    void setup() {
      Serial.begin(9600);
      Serial.println("Makerblog.at - MuMs Color Sensor");
      if (tcs.begin()) {
        Serial.println("Sensor gefunden");
      } else {
        Serial.println("TCS34725 nicht gefunden ... Ablauf gestoppt!");
      while (1);
      }
      // Der Servo hängt am PWM-Pin 3
      myservo.attach(3);
      // Servo in Grundstellung fahren
      myservo.write(0);
      delay(1000);
    }

    void loop() {
      uint16_t clearcol, red, green, blue;
      float average, r, g, b;
      delay(100); // Farbmessung dauert c. 50ms
      tcs.getRawData(&red, &green, &blue, &clearcol);
      average = (red+green+blue)/3;
      r = red/average;
      g = green/average;
      b = blue/average;

      // Clear-Wert und r,g,b seriell ausgeben zur Kontrolle
      // r,g und b sollten sich ca. zwischen 0,5 und 1,5
      // bewegen. Sieht der Sensor rot, dann sollte r deutlich über 1.0
      // liegen, g und b zwischen 0.5 und 1.0 usw.
      Serial.print("\tClear:"); Serial.print(clearcol);
      Serial.print("\tRed:"); Serial.print(r);
      Serial.print("\tGreen:"); Serial.print(g);
      Serial.print("\tBlue:"); Serial.print(b);

      if ((r > 1.4) && (g < 0.9) && (b < 0.9)) {
        Serial.print("\tROT");
        myservo.write(redPos);
      } else if ((r < 0.95) && (g > 1.4) && (b < 0.9)) {
        Serial.print("\tGRUEN");
        myservo.write(greenPos);
      } else if ((r < 0.8) && (g < 1.2) && (b > 1.2)) {
        Serial.print("\tBLAU");
        myservo.write(bluePos);
      } else if ((r > 1.15) && (g > 1.15) && (b < 0.7)) {
        Serial.print("\tGELB");
        myservo.write(yellowPos);
      } else if ((r > 1.4) && (g < 1.0) && (b < 0.7)) {
        Serial.print("\tORANGE");
        myservo.write(orangePos);
      } else {
        Serial.print("\tNICHT ERKANNT");
        myservo.write(nonePos);
      }
      Serial.println("");
      delay(100);

title: Arduino Yun not showing anything on the serial monitor

Answers: 1

body:
Assuming the code works, you should be able to change the position of the servo by altering the initialized color values.  Currently they are:

     const int redPos = 160;
     const int orangePos = 130;
     const int yellowPos = 100;
     const int greenPos = 70;
     const int bluePos = 30;
     const int nonePos = 0;

If, for example, the positions of Red and green are to be swapped all that is needed is to alter the code like this:

     const int greenPos = 160;
     const int orangePos = 130;
     const int yellowPos = 100;
     const int redPos = 70;
     const int bluePos = 30;
     const int nonePos = 0;

The numbers, according to the [Arduino's servo driver web page][1], are the angle in degrees the servo will be moved to after executing the [call to the Arduino servo driver][2].

Given the above, if a new color violet were to be added to the original set of colors the first change would be to move the servo positions slightly higher to make room for the new color.

     const int redPos = 160;
     const int orangePos = 135;
     const int yellowPos = 110;
     const int greenPos = 85;
     const int bluePos = 60;
     const int violetPos = 35;
     const int nonePos = 0;

The next change would be to alter the ranges of the color test code.  As you did not specify what hardware you are using to detect colors, you will have to experiment to find the combination of red, green & blue which matches the new color violet.  The code used for detecting blue is:

     else if ((r < 0.8) && (g < 1.2) && (b > 1.2))

Likely violet contains more red and may be detectable with a line of code like this:

     else if ((r > 1.0) && (g < 1.2) && (b > 1.2))

The position of this test may be important depending on how the detector works.  It may be best to place it after testing for orange.  Remember to use the new initialized variable such that you code may look like this:

    else if ((r > 1.0) && (g < 1.2) && (b > 1.2)){
      Serial.print("\tVIOLET");
      myservo.write(violetPos);
    }

  [1]: https://www.arduino.cc/en/Reference/Servo
  [2]: https://www.arduino.cc/en/Reference/ServoWrite


body:
I am going to update the firmware of an ESP8266 module, but first I would like to know the current version or name.

How can I get it? Maybe with an AT command?

This is my ESP8266 module:

[![My ESP8266 module.][1]][1]

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

title: How to get ESP8266 firmware version?

Answers: 1

body:
ESP8266 and the AT firmware are products of Espressif. They have everything documented on the [web site][1].

The AT command for version is `AT+GMR`.

  [1]: http://espressif.com/en/support/download/overview?keys=&field_type_tid[]=14


body:
The following code

      int i;
      char msg[16]; // Serial data.

      Serial.println();
      Serial.println("===============");

      sprintf(msg, "Sequence:  M", runNum);
      Serial.println(msg);

      Serial.print("LED colour: ");
      Serial.println(colours[colour]);

      Serial.print("Max mA:      ");
      Serial.println(mAmax);

      Serial.println("  mA    mV");
      for (i = 1; i <= mAmax; i++) {
        sprintf(msg, "M", i);          // <--- Line 1.
        Serial.print(msg);               // <--- Line 2.
        sprintf(msg, "m", i * 3);
        Serial.println(msg);
        delay(50);
      }

crashes after the first pass as shown below:

    ===============
    Sequence:     1
    LED colour: red
    Max mA:      30
      mA    mV
       1     3

If I comment out "Line 1" and "Line 2" the loop runs correctly.

I suspect that something odd happens with either the two `sprintf` calls or the `Serial.print` / `Serial.println` calls in quick succession.

Can anyone spot an error or know of an issue that I've missed?

Development environment: create.arduino.cc

title: Serial.print / sprintf causes program crash

Answers: 0


body:
I have this sample code:

    #include <MD_Parola.h>
    #include <MD_MAX72xx.h>
    #include <SPI.h>

    #define MAX_DEVICES 4
    #define CLK_PIN   11
    #define DATA_PIN  12
    #define CS_PIN    10

    MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

    void setup(void) {
      P.begin();
      P.print("PPPPPPPP");
    }

    void loop(void) {
    }

And this is how it lights up the display:

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

I presume that the code displays text incorrectly, because the display manufacturer has connected individual 8x8 displays "differently than any library expects" (i.e. in red I have annotated the column addresses for my display, while with green I have annotated what they would have to be for this library to show text correctly).

I have two questions:

1. Is there any good Arduino graphics library that would allow me to fix from software the addressing issue specific to my display?
2. Since in the future I plan to make a 16x64 display out of 4 of these, then is there a library capable of doing that as well (i.e. have vertical font size of 12-16 pixels)?

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

title: MAX7219 library that can compensate for poorly designed/miswired 8x32 panel?

Answers: 1

body:
The issue is minor. It looks like the library was designed for a slightly different matrix display / wiring.

Take a look at the library and it likely maps the input buffer to segment / dot-matrix information. Play with that.

The author did 99% of the work for you. You just need to finish the last 1%.


body:
I made a counter to count pulses:

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

    int count  = 0 ;
    .
    .
    .
    setup()
    {
    }

    while (count <= 35000)
    {
      digitalWrite(9, HIGH);
      delayMicroseconds(500);
      digitalWrite(9, LOW);

      count = count + 1;
    }

But when I try `while(count <= 40000)`, it does not stop counting.

title: Arduino int problem

Answers: 3

body: `int` in AVR GCC is 16 bits. ***All*** possible `int` values are less than 32767.

body:
> But when I try while(count <= 40000), it does not stop counting.

"int" has a range from -32k to +32k-1. so "count <= 40000" will always be true as count is "int".

body:
You have reached the maximum number that an `int` can represent. That is **32767**.

`int` is a variable type that is made up of **16 bits**. It is **signed**, meaning that it can represent positive and negative numbers.

Out of the **65536** (ie. **2^16**) possible numbers from the 16 bits, half of them represent negative numbers and the remaining half represents positive numbers (including zero). Or in other words, **-32768 to 32767**.

If you don't need negative numbers, then you can change your variable type to `unsigned int` which  will use numbers up to a maximum of **65535**. So it becomes:

    unsigned int count = 0;


body:
I need to update my global variable once I get a 'overdtrue' response and light up my LED but only my LED is lighting up but my global variable is not updated.

Here is my code

    int x = 0;

    void loop() {
    if (content.indexOf("ovrdtrue") > 0)
     {
      x++;
      digitalWrite(ledPin, HIGH);

     }
    fsrReading = analogRead(fsrAnalogPin);
    Serial.print("Analog reading = ");
    Serial.println(fsrReading);
    Serial.print("X: ");
    Serial.println(x);
    }

The x value should be 1 but only the LED has light up. Please help.

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

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

title: Global variable won't update inside void loop arduino

Answers: 4

body: You never set the LED pin to LOW, so it will stay lit up regardless of the global variable.

body:
Are you sure the LED is not lighted from the start?
It's unclear if in the Setup you set the light on or off (or it is default on or off).

Print a Serial print inside the if statement to be sure that the if block is entered, also print before the if the value of content to be sure if 'ovrdtrue' is found in the string.

Also, since you want the LED on in this situation, explicitly set it off in the setup.

body:
> Here is my code

your code ran without setup()?

you are conditionally incrementing "x", and if your condition doesn't hold true, the increment doesn't take place.

body:
It seems like I forgot to include an if else condition above the ovrdtrue.

    if(content.indexOf("true") > 0)
    {
      digitalWrite(ledPin, HIGH);

    }

Arduino is reading this condition even though the data received "ovrdtrue" but this contains some word "true" so this is the one getting read and not the ovrdtrue condition. I just changed the condition variable not close to the word true and it worked fine. I'm sorry for this.


body:
I have an android device and stm32f103 + HC-05 bt dongle. I'm sending 10 bytes "0123456789" string from android to stm32, but I'm receiving only random 1-5 bytes. code on stm32 side:

    long received = 0;
    const unsigned long buffer_size = 128;
    uint8_t buffer[buffer_size];

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

    [...]
    void loop() {
        [...]
        if(Serial1.available()){
            received += Serial1.readBytes(buffer + received, bufferSize-received);
        }
    }

So, if will send "0123456789" from android, let say, 3 times every 1 second, on stm32 i will receive 3 portions like this:

"0", "0567", "047"

or something like this, i.e. I always receive first byte and it's always correct, but it looks like the rest bytes could be randomly lost.

any idea what am I doing wrong?

P.S.> On stm32 side I'm using [Arduino STM32 library][1]. Serial1 is a UART interface, which is located on stm32f103's PA9 and PA10 pins.

I tried to use other bod rate (19200, 38400), but in this case the data is completely corrupted, i.e. just random bytes.

When I'm sending data from stm32 to Android everything works just fine, i.e. I'm receiving all the data on android side.

I'm using standard BluetoothSocket on android side. So, code looks like this:

    BluetoothSocket socket;
    OutputStream outStream;
    [...]

    void init(...) {
        socket = ConnectToSTM32(...);
        [...]
        outStream = socket.getOutputStream();
    }

    void send(byte[] bytes) {
        outStream.write(bytes);
    }

    [...]
    String strToSend = "0123456789";
    send(strToSend.getBytes());

  [1]: https://github.com/rogerclarkmelbourne/Arduino_STM32

title: HC-05 receives only first few bytes

Answers: 0


body: I am using figaro tgs gas sensor (2600, 2602 and 2620) to sense breath from human. What I obtained is the output voltage. However, I would like to convert the voltage to concentration in ppm? Since these gas sensors can sense more than one gas. Is there any way?? Thanks.

title: Gas Sensor output voltage to concentration

Answers: 3

body:
> I would like to convert the voltage to concentration in ppm?
>
> Is there any way??

the datasheet for those devices would have the answers for you. Generally, you read the datasheet BEFORE deciding on using them or not. not that otherway around.

body:
[This][1] is one of the datasheet. I have calibrated it using the clean air factor in datasheet and got the Rs/R0 ratio. However, from there, I not sure how to find the concentration for each gas.

  [1]: http://www.figaro.co.jp/en/product/docs/tgs2600_product_information_rev02.pdf

body:
If you want to measure concentrations of individual gases you would have to separate them and detect them separately using a chromatography column. In the case of gases this is known as gas chromatography (GC) and for liquids it's LC, with the most popular one being HPLC (high performance liquid chromatography, or sometimes called high pressure liquid chromatography). This is actually a really fun thing to do as a project and I stumbled on this question because I want to make my own GC using the sensor you mentioned.

The principle is fairly simple. Most modern GCs have a carrier gas, usually an inert gas like nitrogen or helium, at a steady flow rate and it passes through a column. You inject your sample into this carrier gas flow and then your sample also passes through that column.
Most columns are packed with a material like silica gel or long alkanes (usually around 18 carbon atoms). Silica has more affinity for polar compounds (like alcohols) while alkanes have more affinity for non-polar compounds like butane, hexane, etc.
If you have a mixture of compounds, like in human breath or lighter fuel, they pass through that column at different rates depending on affinity for your stationary phase (the column) and also size of the molecules (heavier molecules like hexane pass through it more slowly than the lighter propane just due to size).
At the end of the column you get the gases coming out separately, depending on the quality of your separation with the ones being less retained by the column coming out first.

A small problem with this is that the separation takes time and can take up a lot of time depending on conditions. Most GCs operate at about 200 degrees Celcius to increase the speed but also to make sure that everything actually is in the gas phase.

For a hobby project I just want to do it at ambient temperature first using lighter gas (which I know is a gas at room temperature) and for a column I will use bentonite clay, which they used back in the old days before silica and it's cheap. Kitty litter is made from bentonite clay as well so it's easily available. As a carrier gas just normal air using for example an aquarium pump or other small membrane pump.


body:
I am working on a project to have a open/close a solenoid at certain ranges (using HC-SR04 ultrasonic sensor).

    #include <NewPing.h>2

    #define Relay1 7
    #define Relay2 8

    NewPing SonarRight(12, 11, 400);

    void setup() {
      pinMode(Relay1, OUTPUT);
      pinMode(Relay2, OUTPUT);
    }

    void loop() {

      unsigned int uS1 = SonarRight.ping();
      delay(50);

      if (uS1 / US_ROUNDTRIP_CM > 15)
        digitalWrite(Relay1, HIGH);
        delay(100);
        digitalWrite(Relay1, LOW);
        delay(1000);

      if (uS1 / US_ROUNDTRIP_CM < 5)
        digitalWrite(Relay2, HIGH);
        delay(100);
        digitalWrite(Relay2, LOW);
        delay(1000);
    }

I got the sensor to ping correct and the distances are reading accurately.  I have it to where once sensor reads that the object is more than 15cm away, the solenoid opens but it keeps clicking open until the object goes back to the dead zone (5-15cm).  Same thing when less than 5cm.  Essentially what i am trying to accomplish is to have the solenoid fill up a tank when the water level get low.  So when the water drops 10cm (x>15) the solenoid opens and then once the water is replenished (x<5), the solenoid closes.

How do i go about doing this without sending a constant OPEN/CLOSE to the solenoid?  Is there a way to make a loop to have it send a the signal only once until it exits that defined range?

Please note that i have not actually used it for its intended purpose im supply moving an object back and forth to simulate water distance.

Thanks

title: How to send signal ONCE when within constant range of sensor?

Answers: 1

body:
You have to add a (global) variable that stores the last send command (to open/close).

When you send a command, you save it in the global variable.

And you only send a command when it is different than the command send the last time, so only CHANGES are sent.

The best way to do this is to make a specific function, e.g. SetSolenoid(bool open);

    #define SOLENOID_OPEN  TRUE
    #define SOLENOID_CLOSE FALSE

    bool _currentSolenoidStatus = false; // Assume closed

In your loop:

    ...
    if  ... condition when solenoid should be be opened
    {
        SetSolenoid(SOLENOID_OPEN);
    }
    ...
    if  ... condition when solenoid should be be closed
    {
       SetSolenoid(SOLENOID_CLOSE);
    }

Function to open/close solenoid open (only when changed):

    bool SetSolenoid(bool status)
    {
        if (_currentSolenoidStatus != status)
        {
            // Send status to solenoid
            _solenoidStatus = status;
        }
    }


body:
I spent on this question more than 2 weeks of googling with no success.
I do not get a response from ESP8266 version 01 on AT commands.
I need to access Wi-Fi from Arduino via ESP8266-01. I know that ESP8266 can be programmed to work without Arduino and so on, but I need it to be a Wi-Fi module for Arduino. On most of the websites Arduino is used as UART for direct programming of ESP8266-01, but I am making this setup to make it work as a Wi-Fi support for Arduino:

      esp       Arduino
      ---       -------
       RX <---> pin 6 (TX) via voltage divider (5V-3.3V)
       TX <---> pin 5 (RX) (3.3V)
      Vcc <---> 3.3v
      GND <---> GND
    CH_PD <---> 3.3V via 10k resistor
    GPIO0 <---> 3.3V via 10k resistor
    GPIO2 <---> 3.3V via 10k resistor

Then I upload this code on Arduino:
<!-- language-all: lang-c -->

    SoftwareSerial espSerial(5, 6);

    const int COM_BAUD = 9600;

    void setup() {
      espSerial.begin(COM_BAUD);
      Serial.begin(COM_BAUD);
      Serial.println("Setup done");
    }

    void loop() {
      if ( espSerial.available() )
        Serial.write( espSerial.read() );
      if ( Serial.available() )
        espSerial.write( Serial.read() );
    }

It prints on AT monitor:
Setup done

But when I send AT command it is not even printed on AT monitor.

One more point -> New wifi called "AITHINKER..." is being created and I even connect to it, of course, this does not grant me access to the web. But this is a good sign telling that ESP8266-01 is working, both current and voltage are enough for operation.

So it does not respond or receives AT commands.
There is no documentation for correct connection of esp01 as wifi of Arduino Uno and I will be very happy if you could share some websites using ESP8266-01 as Wi-Fi of Arduino Uno correctly.

There are some points which are usually resolved other problems of such kind, but did not resolve mine:
- External power supply with common to Arduino ground -> done
- Change RX, TX pins -> done
- Replace ESP8266-01 -> having 5 of them, protecting from over voltage

Please, help me... Losing any hope on this...

P.S. It responds to AT commands when I connect it directly to the computer via USB UART cable.
The problem comes when I connect it to Arduino as the module...

title: ESP01 + Arduino UNO

Answers: 2

body:
The AT command firmware for the ESP8266 modules have not always been set to 9600 bps. You might try 115200 and 57600 bps settings and see if that shows the result.

Also, connect the ESP8266 module directly to an FTDI or similar UART-USB bridge, temporarily eliminating the Arduino, so you can do more experimentation with the baud rates, etc. Then you would be able to easily see if the startup output from the ESP8266 looks garbled (which might indicate a serial speed mismatch), or if there is no output at all.

Another possibility is that the AIThinker module doesn't have the AT command firmware on it. From what source did you obtain the module -- what documentation is provided by that vendor?

body:
I have previously written an Instructables article about how to set up an ESP8266 ESP-01 Wi-Fi module available here: [Definitive Guide to Setting Up Your New ESP01 Module][1], which includes more or less everything you need to know to set up and interface your ESP8266 chip with either your computer or your Arduino Uno (on step 4, which mentions that you should reduce the baud rate).

The main problems you might be facing right now are:

 - The Arduino Software Serial ports only support speeds up to 57600 baud if I'm not wrong, but the ESP-01 module typically comes out of the box with 115200 baud.
 - The Arduino 3.3V regulator may not have enough current to supply the ESP8266. It's a very power hungry chip relative to an Arduino. If you don't mind, do post a picture of your Arduino Uno (or compatible) so I know if it's a power supply issue.
 - The Arduino 3.3V pin does not provide adequate power supply decoupling, which may cause the ESP8266 to malfunction with cheap power supplies.

I designed a PCB called the [ESPBlaster][2] which you may be interested in. It takes a USB-TTL module on one side and has a socket for an ESP8266 module on the other to facilitate direct communications from your computer to the ESP8266 so you can set it to the correct baud rate so that you can interface it with an Arduino Uno, and contains a specially designed voltage regulator which does provides adequate current and decoupling.

[![ESPBlaster PCB][3]][3]

  [1]: https://www.instructables.com/id/Definitive-Guide-to-Setting-Up-Your-New-ESP01-Modu/
  [2]: https://github.com/sammy0025/ESPblaster
  [3]: https://i.stack.imgur.com/A49v3.png


body:
Going through an old project, I had code on two Arduino Due that looked like this

    void loop()
    {
      foo();
      delay(time);
    }

taking to heart [the majority][1] of [literature][2] on using `delay();` I recoded this as

    void loop()
    {
      static unsigned long PrevTime;
      if(millis()-PrevTime>time)
      {
        foo();
        PrevTime=millis();
      }
    }

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously

My question is twofold:

 1. Why would `if(millis()-PrevTime>time)` cause more drift than
        `delay(time)`?
 2.  Is there a way to prevent this drift without going back to `delay(time)`?

  [1]: https://playground.arduino.cc/Code/AvoidDelay
  [2]: http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/

title: delay(time); vs if(millis()-previous>time); and drift

Answers: 3

body:
Because you reset the timer after the operation.

    static unsigned long PrevTime=millis();

 unsigned long t = millis();

 if (t - PrevTime > time) {
  foo();
  PrevTime = t;
 }

body:
There's one important thing that you need to remember when working with time on an Arudino of any form:

* Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.

The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.

For instance, take the following:

    if (millis() - last > interval) {
        doSomething();
        last = millis();
    }

The variable `last` will be the time the routine triggered *plus the time `doSomething` took to run. So say `interval` is 100, and `doSomething` takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.

So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):

    uint32_t time = millis();

    if (time - last > interval) {
        doSomething();
        last = time;
    }

Now the time that `doSomething()` takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for *more* that 100ms having passed - and that means 101ms or more.  Instead you should use `>=`:

    uint32_t time = millis();

    if (time - last >= interval) {
        doSomething();
        last = time;
    }

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc.  But note that bit: *"as long as nothing else happens in your loop"*...

What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.

    if (millis() - last >= interval) {
        doSomething();
        last += interval;
    }

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc.  It always tries to run it as close to the interval as possible regardless of delays.  And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.

Before you had *drift*. Now you have *jitter*.

body:
For what you are trying to do, delay() is the appropriate way to implement the code. The reason you would want to use the if(millis()) is if you want to allow the main loop to continue to loop so your code or some other code outside of that loop can do other processing.

For example:

    long next_trigger_time = 0L;
    long interval = DESIRED_INTERVAL;

    void loop() {
       do_something(); // check a sensor or value set by an interrupt
       long m = millis();
       if (m >= next_trigger_time) {
           next_trigger_time = m + interval;
           foo();
       }
    }

This would run foo() on the specified interval while allowing the loop to continue to run in between. I put the calculation of next_trigger_time before the call to foo() to help minimize the drift, but it is inevitable. If drift is a significant concern, use an interrupt timer or some sort of clock/timer synchronization. Also remember that millis() will wrap around after some period of time and I didn't account for that to keep the code example simple.