body:
For a school project I have been working on a system that will automatically brake when there is danger. Only the requirements are more strict (safety) than just using a ping sensor and detecting a fixed distance. I am going to implement the speed of an incoming object a swell.

On the internet I found this awesome 100Hz sample Lidar module that's very cheap. It uses UART with 2 header frames (0x59), after that a data Lowbyte and a data Highbyte.

So I've started inputting coffee and outputting code (in C) on the atmega328P (Arduino). Only I'm stuck for a few days now.

As you can see here I've set up the code to read the sensor and process the data. The problem is that it gives back weird readings, like a distance difference when I'm moving further away AND when moving closer even though I stated it not to.

Does anyone have experience using this module? Or maybe I misread something of the datasheet.

    //Includes
    //============================================================================================//
    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <math.h>
    //============================================================================================//

    //Defines
    //============================================================================================//
    #define F_CPU 16000000                                          //CPU frequency
    #define Baudrate 115200                                         //UART Baudrate
    #define UBRR_VALUE (((F_CPU / (Baudrate * 8))) - 1)             //UART Baudrate set in Arduino
    // #define SafetyRating 8
    // #define sampleTime 0x65                                          //Time between 2 samples in 10^-4. This value comes from testing (its 1,01ms)
    //============================================================================================//

    //Enums
    //============================================================================================//
    enum {Safe, Warning, Danger}State;                              //Possible States
    //============================================================================================//

    //Global variables
    //============================================================================================//
    uint8_t distanceL;                                              //Distance (low value) data taken from the UART buffer coming from Lidar
    uint8_t distanceH;                                              //Distance (high value) data taken from the UART buffer coming from Lidar
    uint16_t Distance;                                              //Distance combined
    uint8_t frameByteCount = 0;                                     //To count which byte in the frame is current
    uint16_t Speed;                                                 //Speed variable
    //volatile uint8_t DangerLevel;                                 //Danger indicator

    //Function prototypes
    //============================================================================================//
    void calcSpeed(uint16_t Measurement);                       //Function to calculate the speed out of distance readings
    void UART_Transmit(uint8_t data);                               //Funtion to send data via uart
    //============================================================================================//

    //Interrupts
    //============================================================================================//
    /*UART receive complete interrupt*/
    ISR(USART_RX_vect)                                              //Data taken from the UART buffer
    {
        uint8_t sample;

        sample = UDR0;                                              //Read a sample from the receiver buffer

        if(frameByteCount == 3)                                     //If its the 4th byte of the frame
        {
            frameByteCount = 0;                                     //Reset the counter
            distanceH = sample;                                     //Read the distance data high byte
            Distance = (8 << distanceH);                            //Combine the data low and data high
            Distance |= distanceL;

            calcSpeed(Distance);                                //Send the data to laptop for debugging purposes

        }

        if(frameByteCount == 2)                                     //If its the 3rd byte in the frame read the distance data low byte
        {
            distanceL = sample;
            frameByteCount++;                                       //Increment the counter
        }

        if (sample == 0x59)                                         //If a sample is a header increment a counter
        {
            frameByteCount++;
        }
        else if (frameByteCount != 2 && frameByteCount != 3)        //If its not a header or distance data byte reset counter
        {
            frameByteCount = 0;
        }
    }
    //============================================================================================//

    //Timers and Counters
    //============================================================================================//
    /*Timer0 Counter, this decreases the danger level periodically so a really slow approach will not keep incrementing the danger level*/
    ISR(TIMER0_OVF_vect)
    {
    //  if (DangerLevel > 0)
    //  {
    //      DangerLevel--;
    //  }
    }
    //============================================================================================//

    //Main
    //============================================================================================//
    int main(void)
    {
        DDRB    |=      0x02;                                       //For debugging purposes LED pin PB1 (pin 9) as output

        UBRR0H = (UBRR_VALUE >> 8);                                 //Setting the Baudrate register high value
        UBRR0L =  UBRR_VALUE;                                       //Setting the Baudrate register low value
        UCSR0A |= (1<<U2X0);                                        //Setting the data sample to double speed to make Baudrate error less
        UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00);                        //Initializing UART, setting frame to 8 data bits
        UCSR0B |= (1<<RXCIE0) | (1<<TXEN0) | (1<<RXEN0);            //Setting receiver interrupt enable, transmitter enable and receiver enable... Transmitter for debugging purposes

        TCCR0A = 0x00;                                              //Timer0 Setup
        TCCR0B |= 0x05;                                             //Timer0 clock prescaler to 1024
        TIMSK0 |= 0x01;                                             //Timer0 overflow interrupt enable

        sei();                                                      //Set interrupts

        State = Safe;                                               //Set state to safe

        while (1)
        {
            //checkState(DangerLevel);
        }
    }
    //============================================================================================//

    //Functions
    //============================================================================================//
    /*Calculate the danger level out of distance readings*/
    void calcSpeed(uint16_t Measurement)
    {
        static uint8_t samplenumber = 0;                                //Sample tracker
        static uint16_t value0 = 0;                                         //First sample
        static uint16_t value1 = 0;                                         //Second sample

        switch(samplenumber)                                            //To store the measurements alternately
        {
            case 0:
                value0 = Measurement;                                   //Store first measurement
                samplenumber = 1;                                       //So next measurement goes to a different variable
            break;
            case 1:
                value1 = Measurement;                                   //Store 2nd measurement
                samplenumber = 0;                                       //So next measurement goes to a different variable
            break;
            default:
            break;
        }

        if (samplenumber == 0 && value1 < value0)                       //When value0 is first and value1 is second and the object is closing in
        {
            Speed = value0 - value1;
        }
        else if (samplenumber == 1 && value0 < value1)                  //When value1 is first and value0 is second and the object is closing in
        {
            Speed = value1 - value0;
        }
        else
        {
            Speed = 0;
        }
        UART_Transmit(Speed);       //I think sending an uint16_t over uint8_t uart is possible because 'Speed' is never greater than 255 when i'm testing it
    }

    /*Send data over UART when buffer is empty*/
    void UART_Transmit(uint8_t data)
    {
        /* Wait for empty transmit buffer */
        while ( !( UCSR0A & (1<<UDRE0)) )
        ;
        /* Put data into buffer, sends the data */
        UDR0 = data;
    }
    //============================================================================================//

The datasheet for the module: [Datasheet Lidar module][1]

  [1]: http://www.robotshop.com/media/files/pdf/benewake-tfmini-micro-lidar-module-ip65-12-m-datasheet.pdf

title: Speed measurement from lidar sensor for automatic braking system

Answers: 2

body:
I think you are either getting interference that is corrupting the serial data or reflections from the scattering of the light off the object.

If you are certain that your code is right, which it seems to be, then I think you need to ascertain if the unit is giving you constant readings or not.  Can you set up a test that puts the unit at a fixed distance from a reflector and get readings for a minute.  The raw readings should all be identical, absolutely no variation.  They won't be they will waver around a tiny amount so work out what the percentage variation is for this distance.

Now repeat the test but at double the distance, you should get the same accuracy. Now again at double the distance again and you should have the same level of accuracy.

If the accuracy is varying "significantly" then you will need to generate a calibration table.  'At distance x the accuracy is y', etc.

Reflections will give you intermittent wildly inaccurate results. To combat this you might want to filter the data to remove any data that is more than n times the accuracy away from the previous reading.  n has to be a value large enough to cover the maximum distance the reflector (car) can cover in the time between samples.  I would guess assuming a maximum speed of 300MPH would be enough for most cases.

body:
I found it!
Can't believe I was stuck for two days on this.

    Distance = (8 << distanceH);                            //Combine the data low and data high
    Distance |= distanceL;

Should be:

    Distance = (distanceH << 8);                            //Combine the data low and data high
    Distance |= distanceL;

Thanks all for taking the effort, and i'm definately going to do the experiment above to test the accuracy.


body:
I am making a 2-wheeled Arduino car controlled by T.V. remote for a science fair tomorrow. I have found a tutorial for the IR part. I brought this  [L293D motor driver] [1] to control a 2-wheeled car. I am facing a problem. I know where to connect the motors (because there are indications stating M1 and M2) but I don't know where to connect the motor driver to the Arduino and to the batteries.

I checked over the net but couldn't find any tutorial for this kind of board. Also I have no experience in all this so I don't want to risk it. I don't want any code or anything, just where to connect what.

Any help is appreciated.

  [1]: https://www.amazon.in/Maker-Hacker-MBRIDGEV-H-Bridge-Raspberry/dp/B01CBD52QA

title: Use an L293D with Arduino

Answers: 1

body:
All the inputs are clearly marked.

The battery connects to +12V and GND
The Arduino's 5V and GND connect to 5V and GND.

The control signals connect to the header of control signals. ENx is the PWM signal for the speed for motor X. IN1/IN2 are the direction/brake controls for motor 1, and IN3/IN4 are the direction/brake controls for motor 2.

The signal labels are exactly the same as the pin names for the chip and match up precisely with every single tutorial on the net for using the L293D with the Arduino.


body:
In my code I have that string:`String code = rs1 + rs2 + rs3; //rs1=034, rs2=000, rs3=017` It means that `code = "034000017"`. But if I run `if (code.equals("034000017")) Serial.println("OK");` There is nothing in serial monitor. Here is full code:

    String code, rs1, rs2, rs3, readString;
    void setup() {
        Serial.begin(9600);
        Serial.println("Serial ready!");
    }

    void loop() {
        if (Serial.available()) {
            while (Serial.available()) {
              delay(10);
              if (Serial.available() >0) {
                char c = Serial.read();
                readString += c;
                rs1 = readString.substring(0, 3); //034
                rs2 = readString.substring(3, 6); //000
                rs3 = readString.substring(6, 9); //017
                code = rs1 + rs2 + rs3;
                Serial.println(code);
                if (code.equals("034000017")) Serial.println("OK");
              }
            }
        }
    }

title: Strings from serial are not equal

Answers: 2

body:
In your code there is a trivial error and a conceptual error.

The trivial error is in line 16, you wrote

    rs2 = readString.substring(6, 9); //017

but it should have been

    rs3 = readString.substring(6, 9); //017

(3 instead of 2)

The conceptual one is that you do not have to check the string every time; if you know that the string must be 9 chars long, check for it:

    void loop() {
     while (Serial.available()) {
      readString += (char)Serial.read();
      if (readString.length() >= 9) {
       rs1 = readString.substring(0, 3); //034
       rs2 = readString.substring(3, 6); //000
       rs3 = readString.substring(6, 9); //017
       code = rs1 + rs2 + rs3;
       Serial.println(code);
       if (code.equals("034000017")) Serial.println("OK");
       readString = "";
      }
     }
    }

Note that in this code I cleaned up a bit your code, and MOST IMPORTANT I reset the readstring to nothing after the check (otherwise only the first string is accepted)

I left a lot of things as they were (for instance in my opinion using a string in this case is pointless - better use a byte array; or splitting the string in three for joining it again later), since I think this is part of a larger program

body:
Lots of errors in your code. Mine is basically the same that @frarugi87's answer.

I only have to add: when reading serial, wait for the end of line ('\r' and/or '\n') to know when you have all your data, so you don't depend on length (which can be corrupted).

**Edit (on Majeko's comment)**

    String code, rs1, rs2, rs3, readString;
    void setup()
    {
      Serial.begin(9600);
      Serial.println("Serial ready!");
    }

    void loop()
    {
      static bool inData = true;

      while (Serial.available()) {
        char c = (char) Serial.read();

        if (c != '\r' && c != '\n') {
          readString += c;
          inData = true;
        }
        else {
          if (inData) {
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);

            if (code.equals("034000017")) {
              Serial.println("OK");
            }
            readString = "";
            inData = false;
          }
        }
      }
    }

This code works for any configuration of line ending ('\r', '\n' or '\r\n').

It doesn't test for length (or validity or timeout); it's left as an exercise to the reader :-)

I hope it shows how code grows when making it robust in all scenarios.


body:
I am trying to open load a webpage from ESP8266 that displays temperature and humidity of my room if I only type root URL:**`192.168.1.89`**

    GET / HTTP/1.1
    Host: 192.168.1.89
    Connection: keep-alive
    Upgrade-Insecure-Requests: 1
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50
    Accept-Language: en-us
    DNT: 1
    Accept-Encoding: gzip, deflate

to do that in my esp8266 sketch I am trying this logic:

    bool readRequest(WiFiClient& client) {
      bool currentLineIsBlank = true;
      while (client.connected()) {
        if (client.available()) {
          char c = client.read();
          if (c == "GET / HTTP/1.1"){
            Serial.println("Got root");
            client.println(handleRoot()); // where handle root contains web page
          }
          else{
            Serial.println("Did not got root.");
          }
          if (c == '\n' && currentLineIsBlank) {

            return true;
          } else if (c == '\n') {
            currentLineIsBlank = true;
          } else if (c != '\r') {
            currentLineIsBlank = false;
          }
        }
      }
      return false;
    }

but the condition to check if it met `GET / HTTP/1.1` never validates.

title: checking if user is opening root entry point of the IP address on esp8266 webserver

Answers: 0


body:
I want to check the water level and have an SMS sent via a GSM module. Reed switches are connected to four Arduino analog inputs.

I am unable to add a string and tank level (TKLVL) in program.
The program is sending some garbage value via SMS. But TKLVL variable prints the right value.

What is wrong with my code?

        #include <SoftwareSerial.h>
        SoftwareSerial SIM900(10, 11);
        String textMessage;
        #define LED1 2
        #define IRLED 3
        //#define rf433DATA 4
        //D4 IS CONNECTED TO RF433MHZ RECEIVER CHANGE ACC TO LIBRARY
        #define PIRpower 5
        int receiver = 6;
        #define VALVE1 7
        #define GSMRESET 8
        #define pumpONdetect 9
        #define VALVE2 12
        //#define TANK_SENSPOWER 13 //
        #define TANK_SENS4 A0  //full tank wigh buzzer
        #define TANK_SENS3 A1
        #define TANK_SENS2 A2
        #define TANK_SENS1 A3  //low tank
        int TKLVL= 0;
        int LEVEL;

        void setup()
        { pinMode(LED1, OUTPUT);
          pinMode(IRLED, OUTPUT);
          pinMode(PIRpower, OUTPUT);
          //CHECK RECEIVER PIN
          pinMode(GSMRESET, OUTPUT);
          pinMode(VALVE2, OUTPUT);
          // pinMode(TANK_SENSPOWER, OUTPUT); //DRIVE THIS PIN LOW TO ON TANK POWER(PNP TRANSISTOR)
          pinMode(TANK_SENS4, INPUT); //FULL TANK WITH BEEP BUZZER
          pinMode(TANK_SENS3, INPUT);
          pinMode(TANK_SENS2, INPUT);
          pinMode(TANK_SENS1, INPUT); //LOW TANK WATER
          // digitalWrite(TANK_SENSPOWER, HIGH); //turns OFF tanksenspower OFFvia PNP transistor..
          Serial.begin(9600);
          SIM900.begin(9600);
          Serial.print("SIM900 ready...");
          SIM900.println("AT+CMGD=1,4\r");
          delay(1000);
          // AT command to set SIM900 to SMS mode
          SIM900.println("AT+CMGF=1\r");
          delay(400);
          // Set module to send SMS data to serial out upon receipt
          SIM900.println("AT+CNMI=2,2,0,0,0\r");
          delay(400);
          digitalWrite(VALVE1, LOW);

        }

        void loop()
        {
          if (SIM900.available() > 0) {
            textMessage = SIM900.readString();
            Serial.print(textMessage);
            delay(10);
          }
          if (textMessage.indexOf("Von") >= 0)
          {
            G_valve1On();
            Serial.println("on loop");
            textMessage = "";
          }
          if (textMessage.indexOf("Voff") >= 0)
          {
            G_valve1Off();
            Serial.println("off loop");
            textMessage = "";
          }

          if (textMessage.indexOf("Tanklvl") >= 0)
          {
            Tanklvl_calc();
             Serial.print("TKLVL is=");
             Serial.println(TKLVL);
            //  TKLVL=LEVEL;
            // Serial.print("level is=");
            //Serial.println(LEVEL);
            String msg ="TANK IS " + TKLVL;
            Serial.println(msg);
            sendSMS(msg);
            textMessage = "";
          }

        }
        //SEND SMS function
        void sendSMS(String lvlmsg)
        {
          SIM900.print("AT+CMGF=1\r");
          delay(1000);
          SIM900.println("AT+CMGS=\"+9182375*****\"\r");
          delay(100);
          SIM900.println(lvlmsg);
          delay(100);
          SIM900.println((char)26);
          delay(1000);
          SIM900.println();
          delay(5000);
        }

        void G_valve1On()
        {
          digitalWrite(VALVE1, HIGH);
          Serial.println("...turning valve1 on...");
        }
        void G_valve1Off()
        {
          digitalWrite(VALVE1, LOW);
          Serial.println("...turningvalve1 off...");
        }

        int Tanklvl_calc()
        {
          if (digitalRead(TANK_SENS4) == HIGH)
          {
            TKLVL = 100;
            Serial.println("TANK LEVEL 100%");
          }
          else if (digitalRead(TANK_SENS3) == HIGH)
          {
            TKLVL = 75;
            Serial.println("TANL LEVEL 75%");
          }
          else if (digitalRead(TANK_SENS2) == HIGH)
          {
            TKLVL = 50;
            Serial.println("TANK LEVEL 50%");
          }
          else if (digitalRead(TANK_SENS1) == HIGH)
          {
            TKLVL = 25;
            Serial.println("TANK LEVEL 25%");
          }
          else
          {
            TKLVL = 0;
            Serial.println("TANK LEVEL IS LESS THAN 25%");
          }
          return(TKLVL);
        }

title: Arduino GSM module + SMS string sending garbage value

Answers: 2

body:
TKLVL is integer type. Convert it to String object and add :-

String msg = "TANK IS " + String(TKLVL)

body:
Using Strings in a microcontroller is a no-no.
First, try to send a test SMS, to see if everything works OK on SIM800-Arduino etc.

If you receive it correctly, then try to play with char arrays.
First, declare a char array big enough for your data to fit in. Let's use a demo array, but keep in mind that it's your responsibility to keep things tidy.

    byte sizeOfBuffer = 10;
    char smsString[sizeOfBuffer] = {'\0'};

What we did is create an smsString array of 10 bytes, 9 bytes for data and 1 byte for our special end of sting character. Since we don't want Arduino to handle things with Strings, we have to tell our microcontroller where does that String end. That's what '\0' does.

Then, modify the send function to accept that data type.

    //SEND SMS function with char array
    void send_SMS_charArray(char *lvlmsg, byte sizeOfsms)
    {
      SIM900.print("AT+CMGF=1\r");
      delay(1000);
      SIM900.println("AT+CMGS=\"+918237504767\"\r");
      delay(100);
      for (byte i=0; i<sizeof(sizeOfsms); i++){
        SIM900.print(lvlmsg[i]);
      }
      Serial.println();
      delay(100);
      SIM900.println((char)26);
      delay(1000);
      SIM900.println();
      delay(5000);
    }

Finally, to call the new function you would do something like

    sprintf_P(smsString, PSTR("TANK IS: %i"), TKLVL);
    send_SMS_charArray(smsString, sizeOfBuffer);

Notice sprintf_P when using static messages such as "TANK IS". It will save your life in a few months.


body:
I am learning the `ArduinoJson.h` library and creating jsonOject:

    JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
      JsonObject& root = jsonBuffer.createObject();
      JsonArray& tempValues = root.createNestedArray("temperature");
      tempValues.add(t);
      JsonArray& humiValues = root.createNestedArray("humidity");
      humiValues.add(h);
      JsonArray& dewpValues = root.createNestedArray("dewpoint");
      dewpValues.add(pfDew);
      JsonArray& EsPvValues = root.createNestedArray("systemv");
      EsPvValues.add(pfVcc / 1000, 3);
      return root;
    }

As per the example given [here][1]. However since I am using an `ESP8266WebServer` to create a server object from `ESP8266WebServer.h`, I cannot pass a JsonObject to `server.send(.....)`.

> no matching function for call to 'ESP8266WebServer::send(int, const
> char [10], ArduinoJson::JsonObject&)'

    void outputJson() {
      StaticJsonBuffer<500> jsonBuffer;
      JsonObject& json = prepareResponse(jsonBuffer);
      writeResponse(client, json);
      server.send ( 200, "text/json", json );
    }

    void writeResponse(WiFiClient& clnt, JsonObject& json) {
      clnt.println("HTTP/1.1 200 OK");
      clnt.println("Content-Type: application/json");
      clnt.println("Access-Control-Allow-Origin: *");
      clnt.println("Connection: close");
      clnt.println();
      json.prettyPrintTo(clnt);
    }

  [1]: http://www.esp8266.com/viewtopic.php?p=36531#p36531

title: How to pass JsonObject from ArduinoJson to ESP8266WebServer object?

Answers: 1

body:
As far as I know, the only way is to serialize the `JsonObject` to a `String`:

    String createJsonResponse() {
      StaticJsonBuffer<500> jsonBuffer;

      JsonObject &root = jsonBuffer.createObject();
      JsonArray &tempValues = root.createNestedArray("temperature");
      tempValues.add(t);
      JsonArray &humiValues = root.createNestedArray("humidity");
      humiValues.add(h);
      JsonArray &dewpValues = root.createNestedArray("dewpoint");
      dewpValues.add(pfDew);
      JsonArray &EsPvValues = root.createNestedArray("systemv");
      EsPvValues.add(pfVcc / 1000, 3);

      String json;
      root.prettyPrintTo(json);
      return json;
    }

    void outputJson() {
        server.send(200, "text/json", createJsonResponse());
    }

By the way, I recommend that you use the [ArduinoJson Assistant](https://arduinojson.org/assistant/) to compute the size of the `JsonBuffer`.


body:
how can I make the repetitions stop at 10 ? Also how can I get the lcd to reset when its off/low ?

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12,11,5,4,3,2);
    const int tiltSensor = 8;
    int reps = 0;
    int switchState = HIGH;
    int prevSwitchState = LOW;

    void setup() {
      lcd.begin(16,2); // type of lcd(16 columns and 2 rows)
      pinMode(tiltSensor,INPUT);
      lcd.clear();
      lcd.setCursor(0,0); // the cursor is where on the
      lcd the characters will be placed
      lcd.print("Workout Time"); // print is the characters on the screen
      lcd.setCursor(0,1);
      lcd.print("Lets GO ! ");
    }

    void loop() {
      switchState = digitalRead(tiltSensor);
      if (switchState != prevSwitchState) {
        if (switchState == LOW) {
          reps = reps + 1;
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Reps:");
          lcd.setCursor(0,1);
          lcd.print(reps/10);
        }
      }
      prevSwitchState = switchState;
    }

title: Arduino : LCD / POT

Answers: 1

body:
> how can I make the repetitions stop at 10 ?

use a loop counter:

      if (loop_cnt++ < 10) do_mything();


body:
I'm working on a project based on the two sensor above but I keep getting this error:

'liquid_level does not name a type'

This is my sketch:

    /*
    YF‐ S201 Water Flow Sensor
    Water Flow Sensor output processed to read in litres/hour
    Adaptation Courtesy: www.hobbytronics.co.uk
    */
    const int sensorPin= 0; //sensor pin connected to analog pin A0
    int liquid_level;
    volatile int flow_frequency; // Measures flow sensor pulses
    unsigned int l_hour; // Calculated litres/hour
    unsigned char flowsensor = 2; // Sensor Input
    unsigned long currentTime;
    unsigned long cloopTime;
    void flow () // Interrupt function
    {
       flow_frequency++;
    }
    void setup()
    {

       pinMode(flowsensor, INPUT);
       pinMode(sensorPin, INPUT);
       digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
       Serial.begin(9600);
       attachInterrupt(0, flow, RISING); // Setup Interrupt
       sei(); // Enable interrupts
       currentTime = millis();
       cloopTime = currentTime;
    }
    void loop ()
    {
       currentTime = millis();
       // Every second, calculate and print litres/hour
       if(currentTime >= (cloopTime + 1000))
       {
          cloopTime = currentTime; // Updates cloopTime
          // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
          l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
          flow_frequency = 0; // Reset Counter
          Serial.print(l_hour, DEC); // Print litres/hour
          Serial.println(" L/hour");

       }
    }

    liquid_level= analogRead(sensorPin); //arduino reads the value from the liquid level sensor
    Serial.println(liquid_level);//prints out liquid level sensor reading
    delay(100);//delays 100ms
    }

title: Hall effect sensor and water sensor

Answers: 1

body: The last 4 lines are outside any function. They aren’t in the `loop()` function. You can’t put plain statements outside of any function. Check your brackets.


body:
I would like to blink, using specific waveforms, 2 LED controlled by the 2 DAC output of the Arduino Due.

I wrote this :

        #include "Waveforms.h"

        int i = 0;
        int sample;

        void setup()
    {
          analogWriteResolution(12);
    }

        void test(float fq, int wave1, int wave2)
    {

          sample = ((1/fq)*1000000)/120;

          analogWrite(DAC0, waveformsTable[wave1][i]);
          analogWrite(DAC1, waveformsTable[wave2][i]);

          i++;

          if(i == maxSamplesNum)
              {
                i = 0;
              }

          delayMicroseconds(sample);

    }

        void loop() {
        // 10 Hz, 0 is a sine wave on DAC0, 3 is a square wave on DAC1

          test(10, 0, 3);

I would like to be able to change the frequency of each output (1Hz - 100 Hz) using differents waveforms. Changing waveforms is ok and it works, but is it possible to also change the frequency so to have two differents output frequency on each DAC output ?

The goal is to have, for example, simultaneously :

 - 1 Hz, sine wave on DAC0.
 - 10Hz, square wave on DAC1.

Thanks a lot.

title: How can I have 2 differents frequency on the 2 DAC outputs on an Arduino Due?

Answers: 1

body:
I don't have experience with this, but what you can do is:

- If the frequency of DAC1 is x times faster than DAC2 to calculate the delay time based on the fastest and for DAC1 changing in every loop, while changing DAC2 only every DAC1/DAC2 times.

- Vice versa if DAC2 is x times faster than DAC1

- However, if there is not a simple ratio between DAC1 and DAC2 than you have to use the fastest speed of the two and use for the slowest an approximation...

- Or use a higher significant fixed speed for i use a simple linear approximation between two points of the wavetable.

E.g. assume the speed is 10 times too fast for DAC1.
Suppose i = 100.. you should use the following points in the waveform: wave[100/10] and wave[100/10 + 1], so two consecutive points.
Assume the first is 10.0 and the second is 20.0... for the 10 increases of i (because i is running 10 times too fast) you can calculate for values of

     i     : 10.0 +   0% of (20.0 - 10.0)
     i + 1 : 10.0 +  10% of (20.0 - 10.0)
     ...
     i + 10: 10.0 + 100% of (20.0 - 10.0)

etc.

Note this is called linear interpolation.

You would have to check how many numbers per wave form table you need to get good values for different frequencies/speeds and what 'fixed' frequency you need to use for the delay.


body:
Data can be seen in the console but the data is not being written in the text file. The file is created but there is no data in it.

Here is my code in Processing,

    import processing.serial.*;
    Serial myPort;  // Create object from Serial class
    String val;     // Data received from the serial port
    PrintWriter output;
    void setup()
    {

       String portName = Serial.list()[0];
       myPort = new Serial(this, portName, 9600);
       output = createWriter( "my.txt" );
    }
    void draw()
    {
        if ( myPort.available() > 0)
         {  // If data is available,
             val = myPort.readStringUntil('\n');
           output.print( val );
         }
        println(val); //print it out in the console

     }

and in Arduino,

      int potPin = 0; // initialize analog pin 0 for LM35 temperature sensor
      void setup()
      {
         Serial.begin(9600);// set baud rate at”9600”
      }
      void loop()
      {
         int val;// define variable
         int dat;// define variable
         val=analogRead(0);
         dat=(125*val)>>8;// temperature calculation formula
         Serial.print("Tep:");//
         Serial.print(dat);// output and display value of dat
         Serial.println("C");// display “C” characters
         delay(500);// wait for 0.5 second
       }

Any answers are appreciated. Thank you!

title: No data in text file

Answers: 1

body:
createWriter description says:

> "For the file to be made correctly, it should be flushed and must be
> closed with its flush() and close() methods"

 Source: https://processing.org/reference/createWriter_.html
This question is not about Arduino, but Processing language.


body:
> I'm not talking about the onboard LED at the Arduino board here.  What those LED's mean, is the LED's we usually plug at the breadboard.

I plugged in a yellow LED and a green LED onto a breadboard.  I wired it up, and noticed something.  Green LED lights up at its full brightness, while yellow LED didn't emit any light.  Tried in another yellow LED, and it seems like it's smoking, which means it's burned.

I'm not using a 220 Ohm resistor or any kind of resistor that time.  I also have no idea why the green LED didn't burn itself, when you plug it directly on 5V and GND.  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

When I plugged the green LED into a 220 Ohm resistor, it did as expected.  It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

title: Yellow LED got burned, green LED didn't

Answers: 3

body:
> I'm not using a 220 Ohm resistor or any kind of resistor that time.

Well, there you go then. If you abuse an LED you can expect it to die.

> When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the LED was so much happier when you weren't abusing it.

> I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

It was probably tinged with yellow. And if you left it a while it would get yellower as it got hotter, and then started to fade out, and eventually die.

Different LEDs use different combinations of elements to make the different colours. Different types of the same colour also use different elements. Old fashioned green LEDs are more reliable, though dimmer, than newer ones. They withstand more abuse. But they will still complain after a while.

body:
Majenko already mentioned the reason. Maybe it's good to add that different colored LEDs (and even each type/model) should have its 'calculated' resistor.

Find the forward voltage of the LED (differs per type/color), and use the following formula :

    V - Vfv = I * R  <=> R = (V - Vfv) / I

E.g. if the forward voltage is 2V and you use a 5V Arduino and want 20 mA:

    R = (5 - 2) / 0.02 = 150 ohm

The maximum mA you can find also in the data sheet of the LED.

body:
>  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

LEDs get burned from excessive heat that is the result of excessive current. Green LEDs have higher forward voltage than yellow LEDs so, if everything else is equal, the "excessive" current through the green LED is smaller than the one through the yellow LED, thus causing the yellow LED to warm up faster and thus burn out faster.

Other factors may still attribute to the yellow's burn-out.


body:
I am working on Arduino code for stepper motor rotations control. I want to rotate a stepper for only 4 rotations.

The code is working fine but that will run only once as I have put that in `setup()`.

I want to know if there will be any reverse current flowing in the circuit that would damage the Arduino or stepper. What if I want to run the stepper in the `loop()`? I tried but that will force the stepper to run continuously.

How can I run stepper for only 4 rotations and then stop?

I want to run it in `loop()`.

[![arduino-stepper wiring][1]][1]

Below is the code I am using:

    #include <Stepper.h>

    const int stepsPerRevolution = 2100;
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(110);
      // initialize the serial port:
      Serial.begin(9600);
      for(int i=0;i<25;i++) {
        Serial.println("Anti-clockwise");
        myStepper.step(stepsPerRevolution);
        delay(50);
      }
    }

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

title: Arduino Uno + MSD-11-EM stepdriver + NEMA 17

Answers: 3

body:
In loop add flag to change after what you desired plus a statement to check the flag.
Code below (assuming what is in for() being enough to do 4 revolutions):

    #include <Stepper.h>

    const int stepsPerRevolution = 2100;
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
    bool flag = true;

    void setup() {
     // set the speed at 60 rpm:
     myStepper.setSpeed(110);
     // initialize the serial port:
     Serial.begin(9600);
    }

    void loop {
     if (flag) {
       for(int i=0;i<25;i++) {
         Serial.println("Anti-clockwise");
         myStepper.step(stepsPerRevolution);
         delay(50);
       }
       flag = false;
     }
    }

This solution gives you a flexibility to add a pushbutton to change flag and do another 4 revolutions.

body:
I can't validate what you are doing in the `for` statement, but if you want to execute that only 4 times, this sketch will do

    #include <Stepper.h>

    const int stepsPerRevolution = 2100;
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    void setup()
    {
     // set the speed at 60 rpm:
     myStepper.setSpeed(110);
    // initialize the serial port:
     Serial.begin(9600);
    }

    void loop() {
     static int count = 0;

     if(count < 4)
     {
      count++;

      for(int i=0; i<25; i++) {
       Serial.println("Anti-clockwise");
       myStepper.step(stepsPerRevolution);
       delay(50);
      }
     }
    }

`count` keeps the count of how many times you execute the `for` loop. It's declared `static` to keep his value between `loop()` executions; otherwise, it will be zero on each `loop`

body:
I still wonder how code which I have posted earlier worked but no worries code below is working as expected.

    int dirpin_T1 = 7;
    int dirH_T1 = 8;
    int steppin_T1 = 9;
    void setup() {
      pinMode(dirpin_T1, OUTPUT);
      pinMode(dirH_T1, OUTPUT);
      pinMode(steppin_T1, OUTPUT);
    }

    void loop() {
      static int count = 0;
      if(count < 4) {
        count++;
        digitalWrite(dirpin_T1, LOW); // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);
        for (int i = 0; i<3193; i++) {
          // Iterate for 4000 microsteps.(32767)
          digitalWrite(steppin_T1, LOW);
          // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH);
          // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(500);
        }
      }
    }


body:
I fail to use PWM in power saving mode.  The output behaves erratically.  This should be possible, I guess.  The following is a minimal working example:

    /* MWE: Cannot use PWM in any power saving mode.

       A minimal working example (MWE) demonstrating my trouble in using
       PWM while saving power.

       Intention: Control one load to be on or off for longer periods of
       time (hours, that is).  The brightness of the load is set by PWM.

       Wiring:

                                                  +5V
                                                   |
               +------------------+                |
         +5V---|Vin               |                |
               |     Arduino      |                C
               |     Pro Mini    9|-----/\/\/----B|<  PN2222
               |     compatible   |      1k        E
               |     (ATmega328)  |                |
         GND---|GND               |                | +
               +------------------+               LED
                                                   | -
                                                   |
                                                   >
                                                   < 1k
                                                   >
                                                   |
                                                   |
                                                  GND

       Implementation:

         * Set watchdog to cause an interrupt in regular intervals (in
           this MWE: 2s).  Count down `cycles` (MWE: 2 or 3) on each
           watchdog interrupt.

         * If `cycles` is 0, toggle the output, set new `cycles` value.
           The real program uses 7200 8s cycles for 16h before the next
           toggle.

         * Go to SLEEP_MODE_PWR_DOWN.

       Expected: attached load is on for 4s, dimmed at 32/256.  Then off
                 for 6s.  Then repeat.

       Observed: In most cases, there's no output in sleep mode, the LED
                 only blinks before sleeping.  But sometimes it is on, so
                 PWM seems to be possible while sleeping!

       The real program (from which this MWE is derived) uses adjustable
       brightness, wakes up from sleep by external interrupts, stores
       brightnes to EEPROM, ...
    */

    /* Setting the following to 0 uses `digitalWrite` instead of
       `analogWrite` to demonstrate that the watchdog and interrupt logic
       do actually work. */
    #define USE_PWM 1

    #include <avr/sleep.h>
    #include <avr/wdt.h>

    #define outputPin 9    // where the PWM load is connected
    #define onCycles 2     // num of watchdog cycles to stay on
    #define offCycles 3    // num of watchdog cycles to stay off

    int brightness = 32;  // PWM duty cycle in 1/256, if the load is on
    int toggle = 1; // current on/off state of PWM load

    /* Number watchdog cycles until next toggle.  This will be modified in
       the watchdog interrupt handler. */
    volatile unsigned long wdt_cycles = onCycles;

    /* Watchdog interrupt handler called when watchdog expires, count down
       remaining cycles.  Does not underflow. */
    ISR(WDT_vect) {
        if (wdt_cycles > 0)
            wdt_cycles--;
    }

    void setup(void) {

        /* Setup watchdog.  See [1] p54, [2] */
        cli(); // BEGIN disable interrupts

        MCUSR &= ~(1<<WDRF); // no system reset on watchdog timeout

        WDTCSR |= 1<<WDCE | 1<<WDE; // allow watchdog configuration

        WDTCSR
            = 1<<WDIE // enable interrupts
            | 1<<WDP2 | 1<<WDP1 | 1<<WDP0 // 2.0 seconds
            ;

        wdt_reset(); // reset timer

        sei(); // END disable interrupts

        /* Setup output pins */

        pinMode(outputPin, OUTPUT);

    #if USE_PWM
        analogWrite(outputPin, brightness);
    #else
        digitalWrite(outputPin, toggle ? HIGH : LOW);
    #endif

    }

    void loop(void) {

        if (wdt_cycles < 1) {
            toggle = !toggle;
            wdt_cycles = toggle ? onCycles : offCycles;
    #if USE_PWM
            analogWrite(outputPin, toggle ? brightness : 0);
    #else
            digitalWrite(outputPin, toggle ? HIGH : LOW);
    #endif
        }

        /* Heartbeat: Short blink of builtin led.  This verifies that we
           are actually sleeping and waking up. */
        digitalWrite(LED_BUILTIN, HIGH);
        delay(50);
        digitalWrite(LED_BUILTIN, LOW);

        /* Got to sleep, see [3].  I want `SLEEP_MODE_PWR_DOWN`, but also
           none of the others works. */
        set_sleep_mode(
                       //SLEEP_MODE_IDLE
                       //SLEEP_MODE_ADC
                       //SLEEP_MODE_PWR_SAVE
                       //SLEEP_MODE_STANDBY
                       SLEEP_MODE_PWR_DOWN
                       );
        sleep_mode();
    }

    /* References
       [1] https://cdn.sparkfun.com/datasheets/Kits/doc8161.pdf
       [2] https://forum.arduino.cc/index.php?topic=63651.0
       [3] https://playground.arduino.cc/Learning/ArduinoSleepCode
     */

title: How can I use PWM in power saving mode (ATmega328)?

Answers: 2

body:
The timers are disabled during SLEEP_MODE_PWR_DOWN, so PWM doesn't work during SLEEP_MODE_PWR_DOWN. You could instead use `SLEEP_MODE_IDLE`, but that only saves a bit of current.

When you put the MCU to sleep, the led will keep the state it was in during PWM. So around 12.5% if the time the leds will be on, and the other times it will be off (during those 2s PWM periods).

body:
Just as a complement to Gerben's answer:

1. You could use `SLEEP_MODE_PWR_DOWN` during the off period, but
   `SLEEP_MODE_IDLE` is the only way to do PWM while sleeping.
2. When in `SLEEP_MODE_IDLE`, you can use [the `power_*_disable()`
   function defined in `<avr/power.h>`][power.h] in order to further
   reduce the power consumption.

[power.h]: http://www.nongnu.org/avr-libc/user-manual/group__avr__power.html


body:
I am looking for the arduino code to stream video to a webpage using the ESP8266.
here is the 4 wire camera I have: https://www.ebay.com/itm/172272466793

The other tutorials I'm finding online are all for a different cameras or are not using the ESP8266 for webpage streaming.

Any help or pointers would be most appreciated.

* As a side note I have LiFePo 3.3v batteries that I plan to use to power both the ESP8266 and the 5v camera (by wiring them in series).
The thing I am completely lost on is how to wire the video and audio to ports and access them with arduino code.

title: connecting 4 wire camera to esp8266

Answers: 1

body:
No.  Your link is to an *analog* NTSC camera.   Digitally handling data from this would require a high speed analog to digital converter and some fairly sophisticated cleanup logic.

It is simply not compatible to use this with a small embedded system.

If you really want a camera for a resource constrained embedded system, seek a *still* camera with a serial or SPI output.

Most video tasks will however be better done on more capable embedded systems falling outside the realm of Arduino-style approaches, and therefore soundly off-topic here.


body:
This is a basic battery monitor for a solar-powered control box.  It keeps the solar panels tracking the sun.

The Arduino monitors the voltage on the battery and turns on an AC-powered battery charger if the voltage drops too low.

It works, but there is an odd quirk.

*  Actual code is posted [here][1]. Too long to post and it does a bunch of other stuff that can be distracting.

One simple `if` statement isn't executing, as described below and shown on the plot.

---
**HERE IS THE KEY CODE SEGMENT WHERE THE FAILURE OCCURS:**

    if (vind < vTriggerOn) {    // Batt low, turn on charger
      digitalWrite(powerPin,LOW);
      digitalWrite(powerPin2,LOW);
      vAC=17.0;
      }
    if (vind > vTriggerOff) {   // Solar panels on, turn off charger
      digitalWrite(powerPin,HIGH);
      digitalWrite(powerPin2,HIGH);
      }

    //  HERE IS THE PROBLEM :  THIS ONE DOESN'T EXECUTE
    if (vind > 15.5) {vind=15.48; vin=15.48;}

This is followed by yet another `if` statement that works.

**Problem:  That `if` statement in question is supposed to keep it from going off-scale above the top of the plot.  Yet it is not executing.**

[![enter image description here][6]][6]

**The two gray lines show that it is detecting the on and off triggers, but the voltage is going off the top.  This should be impossible.**

**The first two `if` statements are executing but the third one is not.**

---
Considered the fact that I hadn't upgraded the Arduino IDE since first installation.  It is "Arduino 2:1.0.6:dpsg2-4"

Tried this:

    sudo apt-get update
    sudo apt-get upgrade
    sudo apt-get install arduino

and it told me I had the latest version.

---
**Question:  How can I make it execute that third `if` statement?**

  [1]: https://www.SDsolarBlog.com/files/OUTSIDE.ino
  [2]: https://www.SDsolarBlog.com/montage
  [3]: https://stackoverflow.com/questions/14564714/arduino-code-anomalies-lcd-fails-with-multiple-if-statements
  [4]: https://electronics.stackexchange.com/questions/3497/serial-nested-if-statements-not-working
  [5]: https://forum.arduino.cc/index.php?topic=120169.0
  [6]: https://i.stack.imgur.com/IpuSY.png

title: Linux IDE 1.0.6 & Nano: Problem with if statement

Answers: 1

body:
This a new answer, upon the complete, original sketch as posted [here][1] by OP.

I deleted all the code that doesn't affect `vind` directly. Also, I replaced the `value=analogRead(A2)` with worst case scenario `value=1023`. Also tested with 781 and 782, which produces values for `vind` around 15.5.

**Reduced sketch**

    const float R1 = 147000.0;
    const float R2 =  47000.0;
    const float constADC = 5.0;
    const float offsetADC = -0.25; //
    const float convADC = constADC / 1024.0;
    const float numReadings = 10.0;
    const float vTrigAlertLow = 12.1;

    float nReadings = 0.0;
    float tReadings = 0.0;

    int value = 0;
    float vout, vin, vind;

    void setup() {
      Serial.begin(9600);
      while (!Serial);
      Serial.println("");
    }

    void loop() {
      int value = 1023;
      vout = value * convADC;
      vin = vout / (R2 / (R1 + R2));
      vind = vin + offsetADC;
      tReadings = tReadings + vind;
      nReadings = nReadings + 1.0;

      Serial.print(nReadings); Serial.print(" "); Serial.print(tReadings); Serial.print(" ");   Serial.println(vind);

      if (nReadings >= numReadings) {
        vind = tReadings / numReadings;
        tReadings = 0.0;
        nReadings = 0;

        Serial.print("Before "); Serial.print(vind);
        if (vind > 15.5) vind = 15.48; // <----  PROBLEM - not executing
        Serial.print(" After "); Serial.println(vind);

        if (vind > vTrigAlertLow) { // Normal, otherwise below vTrigAlertLow it will send alerts in the 'else' below
          Serial.println(vind);
        }
        else {
          Serial.println("LOW VOLTAGE");  // send Texts
        }
        Serial.println("----");
      }
    }

The output is

    1 20.37 20.37
    2 40.74 20.37
    3 61.10 20.37
    4 81.47 20.37
    5 101.84 20.37
    6 122.21 20.37
    7 142.58 20.37
    8 162.95 20.37
    9 183.31 20.37
    10 203.68 20.37
    Before=20.37 After=15.48
    Send to PI 15.48
    ----

The `if` works as intended. It must be something else.

  [1]: https://www.sdsolarblog.com/files/OUTSIDE.ino


body:
First of all, I am using the Feather MO Adalogger from Adafruit with the Ultimate GPS Feather hat to collect some GPS data: time stamp (millisec), GPS Coordinates (latitude & longitude), speed (knots), and altitude (meters). The GPS data is stored on a micro SD card and I have the GPS portion of the code working. The data I want is being stored on the micro SD card. My only problem is that I can't get the data to be appropriately put in columns under their respective "headers". I used .print("\t") after each data type in attempt to tab the data into columns. This worked for the "headers" but not for the data itself. Screenshots and code are below. Thanks in advance!

My txt file: Headers

[![Headers in my txt file][1]][1]

My text file: working GPS data
[![Data in my txt file][2]][2]

Code for Headers
[![headers code][3]][3]

Code for data
[![data code][4]][4]

  [1]: https://i.stack.imgur.com/cXkfs.png
  [2]: https://i.stack.imgur.com/l5IfU.png
  [3]: https://i.stack.imgur.com/zJiDM.png
  [4]: https://i.stack.imgur.com/G8WqV.png

title: Feather MO: How would I change my code to have my txt file data be in columns rather than be staggered?

Answers: 1

body:
Change the `println()`s to `print()`s. Put one `println()` at the end of the list of data prints.  You want each row of data to not take up more than one line in the text file. A `println()` starts a new row after printing.

Also, you’ll want to open the text file in a tabular program like Excel or similar. A plain text editor likely won’t utilize tab characters in the way you like.


body:
I just got a Gikfun ISD1820 voice recording module for an Arduino project that I'm working on. I want to be able to record a few seconds message and then send the message over wifi to another Arduino Mega 2560, which will then play back the message.

The ISD1820 module can record and play back short messages and can be controlled from the Arduino, but I want to know if it is possible to access the memory / read-write the memory of the ISD1820 module to accomplish my goal. And how would I do it?

If it is impossible, what hardware should I get instead? Do I need a wave shield with a SD card or a wifi shield with an SD card?

Thanks!

title: Is it possible to read-write the memory of a Gikfun ISD1820 voice recording module?

Answers: 1

body:
No. You can't. That module can only record and play.

The only possible thing you could do is record onto the chip then play it back recording it on to the Arduino (at ridiculously low quality) - in which case, what would the point of the chip be?

If you want some quality to your recordings you need a powerful microcontroller with an I2S interface and a CODEC chip.  However any powerful MCU (such as the ARM chip on the Due, or the Teensy, or the PIC32 chip on the chipKIT boards) can sample at a reasonable quality through the ADC inputs.

The Arduino Uno can record very short bursts at very low quality (due to lack of memory) without any external hardware (except a suitable microphone preamplifier). The Mega can record slightly more, but the quality will still be very low.


body:
A couple of days ago, I purchased a pulse sensor online for a project. Before actually doing anything with it, I wanted to capture and view its analogue waveform output. One while placing my finger on it and one when in the default state, so that I can see the trend or difference in the two waveforms. But when I captured the output, it seems like there is not much difference. Just some random noise I guess. Also, I checked the company website who may have made this one and it all looks good to me.

1. The image below shows the waveform captured when no finger is placed on the sensor.
[![enter image description here][1]][1]

2. The image below shows the waveform captured when my index finger is placed on the sensor.
[![enter image description here][2]][2]

3. This is my setup for the sensor for measuring pulses.
[![enter image description here][3]][3]

4. This image shows the face of the sensor.
[![enter image description here][4]][4]

I need some insights from folks here regarding this sensor. Is it showing some junk output? or my understanding is wrong and there's a better way to figure this out/ work with this sensor.

  [1]: https://i.stack.imgur.com/FB0Ps.png
  [2]: https://i.stack.imgur.com/aGCWq.png
  [3]: https://i.stack.imgur.com/8AWgx.jpg
  [4]: https://i.stack.imgur.com/v39fA.jpg

title: Is this a fake pulse sensor?

Answers: 1

body: The second trace looks like a pulse to me. With that kind of sensor you don't get the PQRST traces of an ECG - just a slight bump when you get a pulse.


body:
    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup() {
      pinMode(9, OUTPUT);
      // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);
      // HC-05 default speed in AT command more
    }

    void loop() {
      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available())
        Serial.write(BTSerial.read());

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());
    }

I have tried this code but I am not able to change the baud rate. Please suggest me a solution.

title: Change the baud rate of HC-05

Answers: 2

body:
I played a lot with HC-05 and HC-06 until I understand the way they work. Now i've big Android App communicating with HC at 115200 bauds and sending and receving heavy data.

I hope these tips will help you and other guys and save you time:

1) the way the HC-05 and HC-06 detect end of AT command is different:

HC-05 (can be slave and master): each AT command must end by CRLF. So or you add CRLF in your Android code or you select the option "CRLF line ending" in your console.

HC-06 (only slave): need a "time" between AT Command. According to the data sheet if there is more than 1 sec, the HC consider this is the end. Even if your question is about the HC-05 I think it can be VERY interesting to understand the big problem which can happened with the "delay" between AT.
If you use a communication at 9600 bauds and type AT commands on serial monitor and echo both what HC reply and what you send, you will have such things: type AT+VERSION and see on serial monitor AT+OVKERSION  Why ? Because as the delay between each char is long, as soon as the HC had receive "AT" he thinks that's the command and start to reply "OK".
So with a HC-06 you must send the AT command in one "shoot" and then add a delay of 2 sec to be sure.

2) Problem of settings.
The HC save the speed you set as the name and the pin code. So trying to set the pin, name and speed in the setup funcion is not usefull as at each time the Arduino will reset, each time you'll try to set the data.
Also, factory setting of HC seems to be 9600 bauds.
So you have to create a small sketch, which you'll use only ONE time to set the HC. Like this:

    Serial.begin(9600);
    delay(2000);

    // AT+NAMEXXX where XXX is the new name
    Serial.print("AT+NAMEJOHNDOO");
    delay(2000);

    // AT+PINXXXX where XXXX new code (4 number)
    Serial.print("AT+PIN1999");
    delay(2000);

    // AT+BAUDX where X from 1 to 8
    // 1 -> 1200 Bauds
    // 2 -> 2400 Bauds
    // 3 -> 4800 Bauds
    // 4 -> 9600 Bauds
    // 5 -> 19200 Bauds
    // 6 -> 38400 Bauds
    // 7 -> 57600 Bauds
    // 8 -> 115200 Bauds
    Serial.print("AT+BAUD8");

This for HC-06. For HC-05 you must add CRLF and you don't need the delay.

Important: as, at the end of this sketch, the HC is now at 115200 bauds, you must havea serial.begin(115200) for comunicating with it. If you run this sketch two time, the second run will do nothing as the Arduino will try to comunicate at 9600 bauds with a HC listening at 115200.

3) Problem of speed.
On the Arduino, you can use the software serial lib only if you plan to send and receive at up to 19200 bauds. Some say it work at 38400 but I've had problems at this speed.
The best way it to avoid Software serial and use directly the basic RX and TX of the Arduino. Using that you can run at 115200 without any problem.

Even if this answer is a bit "outside the question" I hope this will help you working with the HC.

body:
**HC-05+Arduino+Android**

The problem is the baud rate of devices. The default baud rate of HC-05 is 38400.  First of all set baud rate of HC-05 by using the AT commands (i.e. AT+UART=9600,0,0) to 9600. This baud rate will work with serial in Arduino as well as in android Bluetooth libraries/app without any problem.


body: Is it possible use Arduino nano with wemos sd shield? If I can, how to I connect sd shield to arduino and what modification I need to do on library setting?

title: Arduino nano and wemos sd shield

Answers: 1

body:
No, you can't. The WeMos boards operate at 3.3V, and so does the SD card. If you want to use a 5V Arduino with a 3.3V SD card, you'll need voltage level shifters.

The schematic of the WeMos SD shield will tell you what SD connections go to what pins. Then just google how to use an SD card with Arduino to connect those pins to the correct Arduino pins.


body:
I'm working on a project using steper motor which turn a threaded shaft (long screw) in order to open or close a water valve (high flow, high pressure).

My fear is that, after a long time of use, the grease on the threaded shaft will dissapear and it can became hard for the stepper motor to rotate correctly the threaded shaft.

In order to tell the user to add grease, I have to know when the stepper needs more effort than before to rotate the threaded shaft. So, would it be possible to detect the "effort" made by the stepper in order to get this information on the Arduino?

Any ideas are welcomed!

title: Detecting step motor effort

Answers: 4

body:
I suggest that if the answer involves the Arduino, the question might be appropriate to this forum.

If you can mount your stepper motor in such a manner as to apply pressure to a force sensor, you may have a method to resolve your goal.

As the motor rotates, under normal conditions, pressure on the sensor will give you a baseline on which you can base your program for consideration of the amount of force involved.

Picture the motor mounted in the center of a circle, with cut-outs appropriate for the mounting bolts. On the outside of the circle, you would have suitable bearing surfaces to reduce rotational friction. From the motor circle platform, a lever pressing against a fixed point on the outside of the circle provides the contact points for the pressure sensor.

If you will be rotating the motor in both directions, perhaps a pair of sensors mounted to encase the lever would be suitable.

When the screw is new, clean and lubricated, you can collect pressure readings and establish a safe and comfortable range. Those numbers would be fixed into your code and measured during motor activity.

If the activity results in force outside the range, you can either stop or reverse the motor and have the same checks apply.

The logic and code is beyond my capability, but you'd have very few parameters to examine during operation.

body:
After fred_dot_u answer I have made other research. Not sure this can help us (Look Alterno and me), but some post are talking about "can I detect the over intensity".

Here is a very interresting post (in French, but Google Translate can help). The guy use and Arduino to control a step motor using to open a fence. And he wants to detect when the motor need more effort:

http://forums.futura-sciences.com/electronique/687244-lecture-de-lintensite-dun-moteur-un-arduino.html

Here the text from this site, I translated:

> **QUESTION**
>
> Hello everyone, I have a DC motor powered at 30 V. In normal
> operation, it consumes 2.5A (the power supply is OK, no problem on
> that side). It is an electric gate motor (sliding gate). I want to
> control it with an arduino. So far, not too much trouble, I go through
> a MOSFET (for the moment, I do not run the engine in one direction,
> later, I will make a bridge in H to go both ways). All this works well
> but I would also be able to detect when the engine forces (to stop
> it). When the motor forces, it consumes more, so more intensity in the
> circuit. The problem is that an Arduino can not read an intensity, I
> can only read a voltage between 0 and + 5V. So I was thinking of
> putting a resistor in series with the motor and measuring the voltage
> across the resistor with the arduino. If I take a max intensity not to
> exceed 5 A, Ohm's law gives me a resistance of 1 Ohm to have a voltage
> of + 5V (I'm good?) The problem is that a resistance of 1 Ohm at 5A
> will dissipate 25W (R x I x I, I'm always good?). How to solve this
> power dissipation problem? the big resistors I have at the moment are
> 3/4 W, they will not take long
>
> My problem is the following: if I take a smaller resistance to have a
> smaller power (like 0.1 Ohm or less), the voltage has its limits will
> be too low to be read by my arduino,
>
> How to do ? Does anyone have an idea?
>
> Thank you in advance for your answers.
>
> Steph.
>
> **ANSWER 1** Just amplify the signal: rail-to-rail operational amplifier
> (to power it with a single positive voltage), a non-inverting device
> with a gain of 10 for example.
>
> **ANSWER 2** Indeed, it's an idea. So I was thinking of putting a resistor
> in series with the motor and measuring the voltage across the resistor
> with the arduino. . The risk of this type of assembly is:
> - the maximum voltage overshoot (5V) at the input of the uC (ARDUINO) at the change of direction (see ground point).
> - the maximum voltage surge (5V) at the input of the uC (ARDUINO) in the event of a break in the resistance. Explanations: The ARDUINO
> board must have a common point (Ground) and an Ax input, therefore
> when changing polarity (change of direction of the motor) the DDP is
> no longer 0V-> 5V but 0V-> 30V and there it smokes, ditto in case of
> rupture of this resistance. The good solution in my opinion would be a
> system like http://www.gotronic.fr/cat-courant-1125.htm
> Regards

The answer 2 give link to products like the i-Snail-VC: Current Transducer with 0-5VDC Output. Can be linked directly to the PIN of an Arduino.

body: Yes, most certainly. Use an ammeter to detect the "effort" required to actuate the motor. Both hall-effect and series measurements are acceptable here. Make sure to sample and average because motors can cause huge current spike (both positive and negative) which confuse naive readings. If your averages are climbing, as they eventually should, you know that it's getting harder to do the work. The hard part is deciding how hard is "too hard", and that depends on a lot of factors you're in the best position of judging.

body:
A few ways, assuming that it is a DC motor.

1. Measure the current through the motor: current is proportional to torque, everything else being equal.

2. Put a strain gauge on the axle.

3. Put a frictional plate on the axle.

...

Or to completely abandon the idea and control the movement via a position sensor.


body:
I have an arduino uno and want to react to three sensors, which should trigger an ISR.

I wrote the following program, and for sensor 3 it works, however the other two sensor don't seem to trigger an interrupt. I checked the sensors by connected each one to pin A5, and every sensor worked.

Is there a better way to check which pin caused the interrupt than digitalRead()? Is this maybe even my problem?

    #define pinDrehen 12
    #define pinRevDrehen 13

    volatile boolean triggeredAngleSensor1 = false;
    volatile boolean triggeredAngleSensor2 = false;
    volatile boolean triggeredAngleSensor3 = false;
    volatile unsigned int triggeredTimeAngleSensor1;
    volatile unsigned int triggeredTimeAngleSensor2;
    volatile unsigned int triggeredTimeAngleSensor3;

    ISR (PCINT1_vect) // handle pin change interrupt for for A0 to A6 and reset [only A3 to A5 are enabled]
    {
      if (digitalRead(A3)){//angle sensor 1
        triggeredAngleSensor1 = true;
        triggeredTimeAngleSensor1 = millis();
      }
      if(digitalRead(A4)){//angle sensor 2
        triggeredAngleSensor2 = true;
        triggeredTimeAngleSensor2 = millis();
      }
      if(digitalRead(A5)){//angle sensor 3
        triggeredAngleSensor3 = true;
        triggeredTimeAngleSensor3 = millis();
      }
    }

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

      // pin change interrupt
      PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3
      PCIFR  |= bit (PCIF1);    // clear any outstanding interrupts
      PCICR  |= bit (PCIE1);    // enable pin change interrupts for A0 to A6 and reset

      pinMode(pinDrehen, OUTPUT);
      pinMode(pinRevDrehen, OUTPUT);

      //start turning machine:
      digitalWrite(pinDrehen, HIGH);
      digitalWrite(pinRevDrehen, HIGH);
    }

    void loop() {
      if(triggeredAngleSensor1){
        triggeredAngleSensor1=false;
        Serial.print("Sensor 1 interrupt at time: ");
        Serial.println(triggeredTimeAngleSensor1);
      }
      if(triggeredAngleSensor2){
        triggeredAngleSensor2=false;
        Serial.print("Sensor 2 interrupt at time: ");
        Serial.println(triggeredTimeAngleSensor2);
      }
      if(triggeredAngleSensor3){
        triggeredAngleSensor3=false;
        Serial.print("Sensor 3 interrupt at time: ");
        Serial.println(triggeredTimeAngleSensor3);
      }
      delay(5);
    }

title: interrupt not triggered correctly

Answers: 2

body:
This line:

    PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3

is probably not what you want.

Let's break it down and look at just what you have there.

    bit (PCINT13)

The `bit` function returns the bitmask for a specific bit.  So if you pass it `3` you get a value with the third (counting from 0) bit enabled (`1 << 3`, or `0b1000`, or `0x08`).

`PCINT13` is 5.  So you have `1 << 5`, or 0x20.

So far so good.  Now you OR that with:

    bit (PCINT12 | bit (PCINT11))

And this is the bit that's wrong.  Inside is `bit (PCINT11)` which, with `PCINT11` being 3, results in `0x08`.  That is then ORed with `PCINT12`, which is 4.  The result is 8+4. That's 12. The value 12 is then fed through another `bit()` function, which gives you `1<<12`. That, of course, overflows outside of an 8-bit value, so you end up with `0`.

The final result is ORed together with the `0x20` from before, which of course remains as `0x20`.

What you probably wanted (and intended) is to have:

    PCMSK1 |= bit (PCINT13) | bit (PCINT12) | bit (PCINT11);  // want pin A5 or A4 or A3

body:
the logic in the isr is incorrect.

generally, you want to set up the pcint pins so that they respond to an edge.

in the isr (with multiple pin changes), you will need to either 1) preserve and maintain the previous state so to determine which pins have experienced a state change; or 2) use pin change flags.

what you have there can lead to false determination of triggers.


body:
All I need to do is generate a random integer between 0 and 3 for example.
I am using this function:

    void Crossover(int parents[2][3])
    {
      int ranDpart;
      int ranDparent;
      for(int i=0; i<10; i++)
      {
        for(int j=0; i<3; j++)
        {
          ranDpart = random(0,3);
          ranDparent = random(0,2);
          newGen[i][j] = parents[ranDparent][ranDpart];
        }
      }
    }

where as you see parents is input with size of 2x3 and `newGen` is 10x3 2D array. As seen here in the code, this function is supposed to randomly take one of parent and a part of this parent to make a new "child". Am I doing something wrong? I think that random gives me bad results. I tried some online compiler and random gives me numbers like "`1804289383`" even if I tried to make it long. Can you guys help me with random `int`?

title: Random(0,2) gives bad results

Answers: 3

body:
stdlib.h defines a few psuedo-random number functions. I am not familiar with a *random* function taking two arguments, presumably the low and high end of the desired range, that you've specified in your code.

For what it's worth, in plain old C use the modulo operator to achieve the range you want using stdlib's [srand][1] and [rand][2] functions:

    /* seed psuedo-random number generator during setup with something */
 srand(0xdeadbeef);

and in your function simply use modulus to get your range:

 int ranDpart = rand() % 3; /* range: 0,1,2 */
 int ranDparent = rand() % 2; /* range: 0,1 */

If your ranges should be inclusive e.g. [0,3] and [0,2] then

    int ranDpart = rand() % 4; /* 0,1,2,3 */
    int ranDparent = rand() % 3; /* 0,1,2 */

  [1]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1gacceff9dc95bb3c5562dc9e61fc3d9075.html
  [2]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1gae23144bcbb8e3742b00eb687c36654d1.html

body:
Unfortunatly, "real random" value don't really exist in computer. If you just call a random function many time, you'll get (in many cases) same result. For that, before calling a random generator, you have to set a "seed".
The example here: https://www.arduino.cc/reference/en/language/functions/random-numbers/random/
give a solution, using:

     randomSeed(analogRead(0));

If the PIN 0 (used in this example) is not connected, you'll get some "noise" on it and this will create the seed for your random function.

body:
The random(a,b) function does work. If it doesn't there is something else going on. You mention the program is long. A couple of things to remember when programming Arduinos is that

 1. In C there is no boundary checking, so when an array is indexed out of range unexpected behavior or crashes occur.
 2. Arduinos have very little RAM. The UNO only has 2K. Part of that is used for the stack. When memory runs low the stack can overwrite program variables and again create unexpected results or crashes e.g. endless reboots.

There are some functions that return the amount of free RAM available at run time, use those with Serial.print() for debugging. There are some freeRam() functions [here][1], the last one works well for me (with UNO)

  [1]: http://playground.arduino.cc/Code/AvailableMemory


body:
When I try to upload my script I get this in my serial monitor:

> ets Jan  8 2013,rst cause:4, boot mode:(1,6)
>
> wdt reset

The board I am using is [Uno + Wifi][1]

And this is my sketch:

    /*
    * Arduino Smart Thermometer
    *
    */
    #include <LiquidCrystal.h> // includes the LiquidCrystal Library
    #include <Button.h>
    #include <SteinhartHart.h>

    //LCD constants
    const int rs = 2, en = 3, d4 = 8, d5 = 9, d6 = 10, d7 = 11;

    //Thermsistor variables
    int ThermistorPin = 0;
    boolean degreeChanged = false;
    double temp = 0.0;

    //Buttons
    int decreaseDegreePin = 12;
    int increaseDegreePin = 13;
    int backlightSwitch = 7;

    #define PULLUP false        //To keep things simple, we use the Arduino's internal pullup resistor.
    #define INVERT false        //Since the pullup resistor will keep the pin high unless the
                               //switch is closed, this is negative logic, i.e. a high state
                               //means the button is NOT pressed. (Assuming a normally open switch.)
    #define DEBOUNCE_MS 50     //A debounce time of 20 milliseconds usually works well for tactile button switches.

    Button decreaseDegreeButton(decreaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
    Button increaseDegreeButton(increaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
    Button backlightSwitchButton(backlightSwitch, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button

    //Variables
    int wantedDegree = 20;
    int backlight = 255;
    int switchPin = 4;
    double curTemp;

    // the following variables are unsigned longs because the time, measured in
    // milliseconds, will quickly become a bigger number than can be stored in an int.
    unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
    unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers
    unsigned long previousDegreeUpdateTime = 0;
    unsigned long degreeUpdateDelay = 3000;

    //Libraries
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
    SteinhartHart thermsistor(ThermistorPin);

    void setup() {
      //Initialize backlight
      analogWrite(5,backlight);

      pinMode(switchPin,OUTPUT);

      //Initialize display
      lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }

      //First display
      updateDegree();
      displayCurrentStatus();
    }
    void loop() {
      switchHeather();

      //Initialize backlight
      analogWrite(5,backlight);

      //Recalculate degree
      updateDegree();

      //Buttons initialization
      changeDegreeWithButtons();

      //If degree is updated, update display
      unsigned long currentDegreeUpdateTime = millis();
      if(degreeChanged){
        if((currentDegreeUpdateTime - previousDegreeUpdateTime) > degreeUpdateDelay){
          previousDegreeUpdateTime = currentDegreeUpdateTime;
          displayCurrentStatus();
        }
      }

    }

    void switchHeather(){
      if(wantedDegree > curTemp){
        digitalWrite(switchPin, HIGH);
      }
      else{
        digitalWrite(switchPin, LOW);
      }
    }

    void updateDegree(){

      curTemp = thermsistor.getTempCelsius();

      if(temp != curTemp)
      {
        temp = curTemp;
        degreeChanged = true;
      }
      else{
        degreeChanged = false;
      }
    }

    void displayCurrentStatus(){
        //Print degrees to LCD
        lcd.clear();
        lcd.print("Temperatuur:");
        lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
        lcd.print(temp);
        lcd.print(char(223));
        lcd.print(" Celcius");
    }

    void changeDegreeWithButtons(){
      //Read buttons
      decreaseDegreeButton.read();
      increaseDegreeButton.read();
      backlightSwitchButton.read();

      if (increaseDegreeButton.wasReleased()) {
        wantedDegree++;
        lcd.clear();
        lcd.print("Temperatuur:");
        lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
        lcd.print("Omhoog naar: ");
        lcd.print(wantedDegree);
      }

      if (decreaseDegreeButton.wasReleased()) {
        wantedDegree--;
        lcd.clear();
        lcd.print("Temperatuur:");
        lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
        lcd.print("Omlaag naar: ");
        lcd.print(wantedDegree);
      }

      //Backlight switch
      if (backlightSwitchButton.wasReleased()) {
        if(backlight == 255){
          lcd.clear();
          lcd.print("Backlight: Off");
          backlight = 0;
        }
        else{
          lcd.clear();
          lcd.print("Backlight: On");
          backlight = 255;
        }
      }
    }

Why does this happen and how can I fix it? When I use the same script on my Arduin Uno board it does work. The board [Uno + Wifi][1] however doesn't.

  [1]: https://nl.aliexpress.com/item/UNO-WiFi-R3-ATmega328P-ESP8266-8Mb-memory-USB-TTL-CH340G-Compatible-for-Arduino-Uno-NodeMCU-WeMos/32739934767.html

Also what I used is:

 - An LCD Screen
 - 3 buttons with resistors
 - A thermsistor with resistor
 - A relay (only connected to arduino
 - External power source

title: Getting boot mode 1.6 error

Answers: 1

body:
This message indicates that you currently have the ESP8266 rather than the ATmega connected to the USB interface.

In order to upload Arduino sketches to the ATmega, you need to follow the instructions on the sale page to change the dip switches to `USB<>ATmega328` mode.

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

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

The table is probably sufficient, if not you can puzzle out the German explanatory text or try machine translation.

It's possible you could also install ESP8266 support in your Arduino IDE and run your sketches on the ESP8266 part of the board instead of the ATmega part, however chances are mot of the Arduino headers go to the ATmega, so you would be limited in what peripherals you could connect.


body:
I'm having an issue in controlling a RGB LED with Arduino and a remote control. When including the library IRRemote.h (version 2.2.3), the blue channel only works in on/off logic instead of PWM. If I remove the library, the PWM logic of the blue channel works normally and it does accept the whole range (0-255). I'm using an Arduino/Elegoo Uno R3 board. What could be causing the issue?

Below the code:

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

    #include "IRremote.h"

    int pinRic = 9; // Signal Pin of IR receiver to Arduino Digital Pin 11
    IRrecv ricevitore(pinRic);     // create instance of 'irrecv'
    decode_results results;      // create instance of 'decode_results'
    #define BLUE 3
    #define GREEN 5
    #define RED 6
    #define IR_BPlus  0xFF3AC5  //
    #define IR_BMinus 0xFFBA45  //
    #define IR_ON     0xFF827D  //
    #define IR_OFF    0xFF02FD  //
    #define IR_R    0xFF1AE5  //
    #define IR_G    0xFF9A65  //
    #define IR_B      0xFFA25D  //
    #define IR_W    0xFF22DD  //
    #define IR_B1   0xFF2AD5  //
    #define IR_B2   0xFFAA55  //
    #define IR_B3   0xFF926D  //
    #define IR_B4   0xFF12ED  //
    #define IR_B5   0xFF0AF5  //
    #define IR_B6   0xFF8A75  //
    #define IR_B7   0xFFB24D  //
    #define IR_B8   0xFF32CD  //
    #define IR_B9   0xFF38C7  //
    #define IR_B10    0xFFB847  //
    #define IR_B11    0xFF7887  //
    #define IR_B12    0xFFF807  //
    #define IR_B13    0xFF18E7  //
    #define IR_B14    0xFF9867  //
    #define IR_B15    0xFF58A7  //
    #define IR_B16    0xFFD827  //
    #define IR_UPR    0xFF28D7  //
    #define IR_UPG    0xFFA857  //
    #define IR_UPB    0xFF6897  //
    #define IR_QUICK  0xFFE817  //
    #define IR_DOWNR  0xFF08F7  //
    #define IR_DOWNG  0xFF8877  //
    #define IR_DOWNB  0xFF48B7  //
    #define IR_SLOW   0xFFC837  //
    #define IR_DIY1   0xFF30CF  //
    #define IR_DIY2   0xFFB04F  //
    #define IR_DIY3   0xFF708F  //
    #define IR_AUTO   0xFFF00F  //
    #define IR_DIY4   0xFF10EF  //
    #define IR_DIY5   0xFF906F  //
    #define IR_DIY6   0xFF50AF  //
    #define IR_FLASH  0xFFD02F  //
    #define IR_JUMP3  0xFF20DF  //
    #define IR_JUMP7  0xFFA05F  //
    #define IR_FADE3  0xFF609F  //
    #define IR_FADE7  0xFFE01F  //
    #define incFact 30
    int  brightFact = 0;
    int lv[3];

    void fade7()
    {
    #define delayTime 10 // fading time between colors

      lv[0] = 255; // choose a value between 1 and 255 to change the color.
      lv[1] = 0;
      lv[2] = 0;

      for (int i = 0; i < 255; i += 1) // fades out R bring G full when i=255
      {
        lv[0] -= 1;
        lv[1] += 1;

        analogWrite(RED, lv[0]);
        analogWrite(GREEN, lv[1]);
        delay(delayTime);
      }

      lv[0] = 0;
      lv[1] = 255;
      lv[2] = 0;

      for (int i = 0; i < 255; i += 1) // fades out G bring B full when i=255
      {
        lv[1] -= 1;
        lv[2] += 1;

        analogWrite(GREEN, lv[1]);
        analogWrite(BLUE, lv[2]);
        delay(delayTime);
      }

      lv[0] = 0;
      lv[1] = 0;
      lv[2] = 255;

      for (int i = 0; i < 255; i += 1) // fades out B bring R full when i=255
      {
        lv[2] -= 1;
        lv[0] += 1;

        analogWrite(BLUE, lv[2]);
        analogWrite(RED, lv[0]);
        delay(delayTime);
      }
    }

    void setColor(int r, int g, int b)
    {
      Serial.println("About to write:");
      Serial.println(r);
      Serial.println(g);
      Serial.println(b);
      analogWrite(RED, r);
      analogWrite(GREEN, g);
      analogWrite(BLUE, b);
    }

    void  translateIR() // takes action based on IR code received
    {
    // describing Remote IR codes
      Serial.println(results.value, HEX);
      switch (results.value)
      {
        //case IR_BPlus: setBright(true);break;
        //case IR_BMinus: setBright(false);break;
        case IR_OFF: setColor(0, 0, 0); break;
        //COLORS
        case IR_R: setColor(255, 0, 0); break;
        case IR_G: setColor(0, 255, 0); break;
        case IR_B: setColor(0, 0, 255); break;
        case IR_W: setColor(255, 255, 255); break;
        case IR_B1: setColor(255, 20, 0); break;
        case IR_B2: setColor(0, 255, 20); break;
        case IR_B3: setColor(20, 0, 255); break;
        case IR_B4: setColor(255, 20, 255); break;
        case IR_B5: setColor(255, 90, 0); break;
        case IR_B6: setColor(0, 255, 90); break;
        case IR_B7: setColor(90, 0, 255); break;
        case IR_B8: setColor(255, 150, 255 ); break;
        case IR_B9: setColor(255, 191, 0); break;
        case IR_B10: setColor(0, 255, 191); break;
        case IR_B11: setColor(191, 0, 255); break;
        case IR_B12: setColor(120, 255, 255); break;
        case IR_B13: setColor(255, 255, 0); break;
        case IR_B14: setColor(0, 255, 255); break;
        case IR_B15: setColor(255, 0, 255); break;
        case IR_B16: setColor(150, 255, 255); break;

        //END COLORS
        case IR_FADE7: fade7();
      }// End Case

      delay(100); // Do not get immediate repeat
    } //END translateIR

    void setup()   /*----( SETUP: RUNS ONCE )----*/
    {
      pinMode(RED, OUTPUT);
      pinMode(GREEN, OUTPUT);
      pinMode(BLUE, OUTPUT);
      Serial.begin(9600);
      Serial.println("IR Receiver Button Decode");
      ricevitore.enableIRIn(); // Start the receiver*/

    }/*--(end setup )---*/

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {
      if (ricevitore.decode(&results)) // have we received an IR signal?
      {
        translateIR();
        ricevitore.resume(); // receive the next value*/
      }
    } /*--(end main loop )-- */

title: Problem with PWM function on RGB LED and IR

Answers: 1

body:
By default, the IRremote library uses Timer 2 on an ATmega328P. ([Library documentation][1]) This timer is also used for PWM on pins 3 and 11.
This means that you will have to use a different PWM pin for your blue LED (e.g. 9 or 10, controlled by Timer 1).
Alternatively, you could edit the IRremote library to use Timer 1.

  [1]: https://github.com/z3t0/Arduino-IRremote/blob/master/README.md#hardware-specifications


body: How will I make Arduino with GPS communicate with an Android app? I just need this for my school project.

title: How will Arduino sketch and Android app communicate over GPS?

Answers: 1

body:
> How will i make arduino with gps to communicate with android app? i just need this for my school project.

as gps is one-way communication, you will have to either launch your own birds capable of two way communications, or pick a different school.


body:
Setup:
2XArduino Uno
2x XBees S1
2x Sparkfun xbee shields.

My first arduino reads in values from a photoresistor and sends the values to the second arduino.
I know for sure the arduino is sending  values because when i plugged the second xbee directly into the computer and opened the serial monitor correct values showed up in the serial monitor. But the problem is when i attach the second Xbee onto its sparkfun shield and arduino i get repetitive wrong values .

Can someone please tell me what i am doing wrong?
I am doing this to make sure i get the right values before i beef up the project.

Sender sketch

    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>
    #include <XBee.h>
    int photocellPin = A0;     // the cell and 10K pulldown are connected to a0

    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    int photocellReading;     // the analog reading from the analog resistor divider
     SoftwareSerial XBee(2,3);
    void setup(void) {

      Serial.begin(9600);
      XBee.begin(9600);
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("Wireless LightDimmer");

    }
     void loop(void) {
      photocellReading = analogRead(photocellPin);
      lcd.setCursor(0, 1);
      lcd.print("Photocell= ");
      lcd.setCursor(11, 2);
      lcd.print(photocellReading);
      //Serial.println(photocellReading);
      lcd.setCursor(20, 0);
      lcd.print("Measured in lux");

      delay (500);
      lcd.setCursor(20, 3);
      lcd.print(" ");
     // Serial.print("Analog reading = ");
     // Serial.print(photocellReading);
       photocellReading = 1023 - photocellReading;
     unsigned int LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
       Serial.println( LEDbrightness);
        XBee.print(LEDbrightness);

      delay(1000);
    }

recieving sketch

    #include <SoftwareSerial.h>
    #include <XBee.h>

    SoftwareSerial XBee(2,3);

    void setup() {
     // Begin Serial communication
     Serial.begin(9600);
     }
    void loop(){
     while ( Serial.available() > 0) {
     unsigned int num =  Serial.read();
     Serial.println(num);
     delay(2000);
     }
    }

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

  [1]: https://i.stack.imgur.com/H4pNH.png
  [2]: https://i.stack.imgur.com/Ql4Yz.jpg

title: Xbee shield to shield connection sends but not receives correctly

Answers: 1

body: The xbee pins can only read up about 1.2V which it will show 256 bit. You should check how much the photoresistor is giving out because it might gives something that is more than the xbee pin can handle.


body:
For a simple project I would like to use a ATTiny85 connected to a HC-06 Bluetooth Module so it can talk to my Android phone.

I wrote a code for my Arduino Uno and worked as expected. When I changed the code to use on my ATTiny85 I got an error saying that `'Serial' was not declared in this scope` and assumed that the ATTiny does not support Hardware Serial.

I need to read a String when received and sleep the MCU when not receiving. I went to use SoftwareSerial and was not able to get a String, just the first char.

I approached it in some was, like defining a `char string[10];` as global and `string[i] = mySerial.read(); i++;` inside the loop, but it keeps not working. Whether it is the sleep, or my work to read data, I couldn't make it work.

Can someone provide a way to put a ATTiny85 to sleep, wake up to receive a String through Serial and sleep til the next data through Serial, please?

To sleep I'm using

    void sleep() {
      GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
      PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

      sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
      sei();                                  // Enable interrupts
      sleep_cpu();                            // sleep

      // woke up
      cli();                                  // Disable interrupts
      PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
      sleep_disable();                        // Clear Sleep Enable bit

      sei();                                  // Enable interrupts
    }

    ISR(PCINT3_vect) {

    }

And my loop is something like

    char inputString[10];
    int i = 0;

    void loop() {
      sleep();

      if (serial.available() > 0) {
        char inputChar = serial.read();
        if (inputChar == '2') {    //Char to break
          //Do something and reset i
        } else {
          inputString[i] = inputChar;
        }
        i++;
      }
    }

Thanks to all.

title: ATTiny85 Serial communication with Bluetooth Module

Answers: 1

body:
Hello,

I think you should do this:

    char inputChar = '';    //this in global
    while (serial.available()) {
        inputChar = serial.read();
        if (inputChar == '2') {    //Char to break
            //Do something and reset i
        } else {
            inputString[i] += inputChar;    //= to +=
        }
        i++;
    }


body:
I am using SIM800L module. I am new to GSM modules. I have searched in many web sites about SIM800L, every where they mentioned baud rate 9600 for `SoftwareSerial` but it is not working at all in my case. So I started a trail and error method to match baud rate. Finally I found that its baud rate is 38400. With baud rate of 9600 for Arduino and 38400 I am able to communicate with SIM800L.

The problem is that I am unable to register to network. `AT+COPS=?` shows all available networks. Using `AT+COPS="value"` I am able to select network. But after that the SIM800L module still blinks every second.

In `loop()` I am continuously reading software serial and it's printing the following:

    RDY
    +CFUN: 1
    +CPIN: READY
    Call Ready
    SMS Ready
    RDY
    +CFUN: 1
    +CPIN: READY
    Call Ready
    SMS Ready

The above data is continuously printing on console.

title: SIM800L not registering to network

Answers: 2

body:
Might be some power issues, but I fixed mine by just trying some AT command

    AT+CBAND?

Then, `AT+CBAND="DCS_MODE"`

That works for me. Give it a try man.

body:
I am 90% sure it's a power issue. Not sure on what board/module you're using but the SIM800L/SIM900 needs a burst of current of 2 A during 577 µS (See the [manual][1]).

Try using 4700 µF and a 10 µF capacitor in parallel with the module. Powering it with a proper power source instead of the Arduino wouldn't hurt too.

  [1]: http://img.filipeflop.com/files/download/Datasheet_SIM800L.pdf


body:
Any advice on what coding to adjust. New to Arduino.

    const int sensorPin = A0;
    float voltage=0.0;
    int sensorVal=0;
    int heartbeats=9;
    float BPM=0.0;
    const int led1=2;
    const int led2=3;
    int starttime = 0;
    boolean counted = false;

    void setup() {
    pinMode(sensorPin, INPUT);
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    Serial.begin(9600);
    boolean counted = false;
    }
    void loop() {

    starttime = millis();
    while (millis()<starttime+10000)
    {
      sensorVal = analogRead(sensorPin);
      if (sensorVal >550 && counted == false)
      {
        counted = true;
      }
      else if (sensorVal < 500)
      {
        counted = false;
      }
    }

        BPM = heartbeats*6;
     Serial.println("Your BPM is");
     Serial.println(BPM);
    BPM =0;
    heartbeats =0;

    }

title: Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values

Answers: 2

body:
There's two basic methods of measuring a frequency, which is basically what you are trying to do.

There is Frequency Counting and Frequency Timing. The latter involves measuring the time between successive pulses and calculating the instantaneous frequency from that. Good for rapidly changing frequencies where you need to know the frequency right away.

Frequency counting is what you are attempting, and is basically counting the number of edges that occur within a certain timeframe.

However your method is slightly flawed: chiefly because you forgot to actually count the edges. You wrote some reasonable code for finding an edge, but failed to actually do anything with that edge.

Also your code is blocking for 10 seconds, which may be fine in this scenario, but is not a good habit to allow yourself to get into.

Instead you should consider something more like this:

    void loop() {
        static int count = 0;
        static bool counted = false;
        static uint32_t ts = millis();

        int val = analogRead(sensorPin);

        if ((val > 550) && (counted == false)) {
            counted = true;
            count++;
        } else if (val < 500) {
            counted = false;
        }

        if (millis() - ts >= 10000) {
            ts += 10000; // You could assign ts the millis() value, but
                         // by adding 10 seconds it cancels any drift
                         // caused by other delays in your sketch.
            int BPM = count * 10;
            count = 0;
            Serial.print("BPM: ");
            Serial.println(BPM);
        }
    }

body:
Assuming the input waveform is a low frequency square wave. Multiple ways to do it.

1. Use the input to gate a counter on internal clock. It gives the most precise measurement, with a sub-us resolution.

2. Use external or pcint interrupts to time the start and beginning of an edge.

3. Wait in between edges.

...

Oversampling and algorithm will help smooth out the measurement.