body:
I run an Arduino Pro Mini on ATMega328 3.3V 8MHz, and I am unable to send data over HC-05 breakout board on this frequency, and on 5V 16Mhz, it has no issues.

The Arduino code is down below:

    #include <SoftwareSerial.h>
    #include <Wire.h>
    SoftwareSerial BT(10, 11);
    byte value;
    unsigned long pmillis_bt = 0;

    void setup() {
      Serial.begin(19200);
      BT.begin(9600);
    }
    ///////////////////main///////////////////

    void loop () {
      if (millis() - pmillis_bt >= 100) {
        byte Data[3];
        byte cmmd[20];
        int insize;
        char str[256];
        int i = analogRead(A0);
        value = BT.read();
        Data[0] = 'a';
        Data[1] = i / 256;
        Data[2] = i % 256;
        sprintf(str, "%d", i, Data[0], Data[1], Data[2]);
        Serial.println(str);
        if (value == 49) {
          for (int j = 0; j < 3; j++)
            BT.write(Data[j]);
          value = 0;
        }
        pmillis_bt = millis();
      }
    }

title: How can I run HC-05 on 8MHz Pro Mini?

Answers: 2

body:
You are probably using the HC-05 Module with a power regulator and levelshifter designed for use with Arduinos that typically run with 5V. What you need is the plain HC-05 as can be found on [AliExpress][1]. Those run with 3.3V but it can be tricky to use them in prototypes.

  [1]: https://www.aliexpress.com/item/1pcs-hc-05-HC05-RF-Wireless-Bluetooth-Transceiver-Module-RS232-TTL-to-UART-converter-and-adapter/32736755254.html

body:
Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.

But in Pro mini 3.3 V level due to you need to [Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module][1]

using this you can easily convert the vlotage level.

if you have to make using simple component also using

[SparkFun Logic Level Converter - Bi-Directional][2]

  [1]: http://www.amazon.in/Generic-Channel-Converter-Bi-Directional-Module/dp/B011ECG2MM?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=452c9032-ae7a-4c0b-bf42-18085457ab13
  [2]: http://file:///C:/Users/Kalarav/Downloads/Logic_Level_Bidirectional.pdf


body:
I have an Arduino Uno and 3 IR led's. Each of my IR led's works fine individually if I connect them to pin 11.

However I want to connect all 3 of the led's to the Uno and have them send different signals according to pin number.

e.g

**IR LED 1** connected to **pin 11** - send signal **0xABCDEFGH**

**IR LED 2** connected to **pin 10** - send signal **0xSJKLMNOP**

**IR LED 3** connected to **pin 09** - send signal **0xZXYRWVUG**

I tried making my own code below but it does not work. If anyone has any pointers i'll be very happy.

    //LED 1

        #include <IRremote.h>

        IRsend irsend;

        void setup()
        {
        }

        void loop() {
            for (int i = 0; i < 11; i++) {
                irsend.sendNEC(0xABCDEFGH, 32); //Settings Menu
                delay(1000);
            }
            delay(1000); //1 second delay
        }

    //LED 2

        #include <IRremote.h>

        IRsend irsend;

        void setup()
        {
        }

        void loop() {
            for (int i = 0; i < 10; i++) {
                irsend.sendNEC(0xSJKLMNOP, 32); //HDMI Port
                delay(1000);
            }
            delay(1000); //1 second delay
        }

    //LED3

        #include <IRremote.h>

        IRsend irsend;

        void setup()
        {
        }

        void loop() {
            for (int i = 0; i < 9; i++) {
                irsend.sendNEC(0xZXYRWVUG, 32); //Switch Off Monitor
                delay(1000);
            }
            delay(1000); //1 second delay
        }

title: Manipulating 3 IR led's on Arduino Uno

Answers: 2

body:
I think what you have done is a perfectly logical thing to do.  You had three programs that worked and so you pasted them all into the same file and compiled it.  The compiler spat its dummy out of the pram and you didn't understand what the h*ll went wrong.  Is that about right?

    // You only need to include each header file once
    #include <IRremote.h>

    // You need to define objects to represent the leds, we could use an array but for now we'll stick to the basics (makes the code a bit longer)
    IRsend irsend_led1;
    IRsend irsend_led2;
    IRsend irsend_led3;

    // This is where you do all the setup, it only gets executed once.
    // You might need to assign the pin numbers to the irsend_ledX variables here.
    void setup()
    {
    }

    // This function is called repeatedly.  You can only have one of these.
    void loop() {
        // I don't understand why you have this for loop, I think you think it may have something to do with pin numbers but I don't think it does.
        // I think the data is being sent multiple times, don't know why though
        for (int i = 0; i < 11; i++) {
            irsend_led1.sendNEC(0xABCDEFGH, 32); //Settings Menu
            delay(1000);
        }
        delay(1000); //1 second delay
        for (int i = 0; i < 10; i++) {
            irsend_led2.sendNEC(0xSJKLMNOP, 32); //HDMI Port
            delay(1000);
        }
        delay(1000); //1 second delay
        for (int i = 0; i < 9; i++) {
            irsend_led3.sendNEC(0xZXYRWVUG, 32); //Switch off monitor
            delay(1000);
        }
        delay(1000); //1 second delay
    }

Give that a try, it might not work, but it will be closer to what you need, I hope I have explained it well enough.

Read the manual for the IR library and find out how to set the port numbers and if you can find out what that loop is about that might help.

body:
@Matt has the main problem resolved, but I do want to add a note.

`<IRremote.h>` has the default IR led pin as pin 3 (last time I checked, maybe it has changed). I don't know how to change it, but if you are considering to use multiple IR leds, you might have to debug that problem!

So try to make 1 code work before you attempt to stick them togheter


body:
So I'm using this `movement()` function inside the slave Arduino Uno, which basically handles two stepper motors and one servo motor. When I call this function through the `Serial.read()` of the Arduino Uno, it works perfectly, both the steppers and the servo.

I have a master Arduino Mega interfaced with the Uno (mentioned above) when I send a wire message from the Mega to Arduino to run the `movement()` function in the Uno, the steppers work fine, but the servo does not work. Although, again I mention that when the function is called upon using the `Serial.read()` of the Uno, it works absolutely fine.

I'm using an Adafruit motor shield on the Arduino Uno as well.

OK so this is the Uno (slave code)

    void setup() {
      servo1.attach(9);
      Serial.begin(9600);
      Wire.begin(5);
      Wire.onReceive(receiveEvent);
      Serial.begin(9600);
    }

    void loop() {
      //other stuff
    }

    void receiveEvent(int howMany) {
      while(Wire.available()) {
        char c = Wire.read();
        int From = Wire.read();
        int To = Wire.read();
        int x = 0;
        movement(From,To);
      }
    }

    int movement(int from,int to) {
      int X_From = from / 10;
      int X_To = to/10;
      int Y_From = from % 10;
      int Y_To = to % 10;
      /* First we have to get the motor position and move the motor to the from position */
      /* === START === */
      int diff_X = X_From - motor_X;
      int diff_Y = Y_From - motor_Y;
      int Y_Value = abs(diff_Y * Y_Steps);
      servoDown();
      if(diff_X != 0) {
        if(diff_X > 0) {
          /* Positive value means the X_Axis motor will move in the forward direction */
          int X_Value = abs(diff_X * X_Steps);
          X_Forward(X_Value);
        } else if(diff_X < 0) {
          /* Negative value means the X_Axis motor will move in the backward direction */
          int X_Value = abs(diff_X * 400);
          X_Backwards(X_Value);
        }
      }
      if(diff_Y != 0) {
        if(diff_Y > 0) {
          Y_Forward(Y_Value);
        } else if(diff_Y < 0) {
          Y_Backwards(Y_Value);
        }
      }
      Serial.println("Motor movement done");
      /* === END === */
      motor_X = X_From;
      motor_Y = Y_From;
      int diff_X_2 = X_To - motor_X;
      int diff_Y_2 = Y_To - motor_Y;
      int Y_Value2 = abs(diff_Y_2 * Y_Steps);
      servoUp();
      if(diff_X_2 != 0) {
        if(diff_X_2 > 0) {
          /* Positive value means the X_Axis motor will move in the forward direction */
          int X_Value2 = abs(diff_X_2 * X_Steps);
          X_Forward(X_Value2);
        } else if(diff_X_2 < 0) {
          /* Negative value means the X_Axis motor will move in the backward direction */
          int X_Value2 = abs(diff_X_2 * 400);
          X_Backwards(X_Value2);
        }
      }
      if(diff_Y_2 != 0) {
        if(diff_Y_2 > 0) {
          Y_Forward(Y_Value2);
        } else if(diff_Y_2 < 0) {
          Y_Backwards(Y_Value2);
        }
      }
      motor_X = X_To;
      motor_Y = Y_To;
      Serial.println("piece movement done");
      return 1;
    }

    void servoUp() {
      for (i = 100; i >= 0; i--) {
        servo1.write(i);
      }
    }

    void servoDown() {
      for (i = 0; i < 100; i++) {
        servo1.write(i);
      }
    }

This is the master Mega Code:

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

    void loop() {
      //check if a condition appeared from sensor and then send the data to Uno to run the movement function through sendData()
      sendData(From,To);
    }

    void sendData(int From,int To) {
      Wire.beginTransmission(5);
      Wire.write('f');
      Wire.write(From);
      Wire.write(To);
      Wire.endTransmission();
    }

Any suggestions what's wrong?

title: Servo motors not working when called upon using I2C

Answers: 2

body:
I don't know if this is the whole problem, but if you call `sendData (0, 270)` you are only going to send 3 bytes to the Uno `0x66, 0x00, 0x01`.  You should be sending 5, `0x66, 0x00, 0x00, 0x01, 0x0E`

The Uno only reads three bytes and receives:
    c = 0x66;  // 'f'
    From = 0x00; // 0
    To = 0x01; // 1

This is because Wire.write() and Wire.read() send/read a single byte (when you call them like this).  What you need is:

    void sendData(int from, int to)
    {
        Wire.beginTransmission(5);
        Wire.write('f');
        Wire.write(&from, sizeof(int));  // Write an array of 'size of int' bytes
        Wire.write(&to, sizeof(int));
        Wire.endTransmission();
    }

    int readInteger (void)
    {
        int result= 0;
        for (int byte = 0; byte < sizeof(int); byte++)
        {
           result = result << 8;  // Left shift the current data (multiply by 2^8)
           result += Wire.read(); // Add the next byte as the LSB
        }
        return result;
    }
    void receiveEvent(int howMany)
    {
      while(Wire.available())
      {
        char c = Wire.read();
        int from = readInteger();
        int to = readInteger();
        int To = Wire.read();
        movement (from, to);
      }
    }

This code sends and receives the complete integers, so it should work.

Sorry I can't compile it, but I think its right.

body:
If you are using Servo library, which uses timer (and so interrupts) for manipulating the servos then you may have the problem, that from `loop` it works (as interrrupts are enabled), but from interrupt (ISR) it does not work, because while serving interrupt (from I2C) all other interrupts are (temporary) disabled.

In `receiveEvent()` you are inside interrupt serving, so other interrupts are disabled and so anything, what depends on interrupts does not work, until you leave the function.

So it is the more probable cause, why your servo does not move, while called from `receiveEvent()`, while it moves, if called from `loop()`

And you wait inside the interrupt routine, until all Wire input is read fully and then while the (slow, as it probabely involves mechanical components like motors or servos) `movement(from,to)` ends (if it can even end with interrupts disabled).

The solution would be to do all `movement(..)` in the `loop` and int the `receiveEvent()` just store the already aviable values and put them into some `static volatile` variables, when transfer ends together with mark, that some change was done.

    static volatile int from;
    static volatile int to;
    static volatile int changed;

    void loop() {
    int my_from,my_to;
      if (changed) {
         noInterrupts();  // critical, time-sensitive code here
           my_from=from;
           my_to=to;
           changed=0;
         interrupts(); // enable interrupts, so I2C, servo and such can work again
         movement(my_from,my_to);
      }
    }
    void receiveEvent(int howMany)
    {
      if(Wire.available())
      {
        char c = Wire.read();
        from = readInteger();
        to = readInteger();
        changed = 1;
      }
    }

Not totally perfect (mainly reading the Wire, which I would just tak as much as is ready to some buffer and decode it only when buffer is sufficiently full and syntactically correct, but if would make the idea here more complicated), but should work much better, than the current version.

Better version of `receiveEvent can look like this:

    char buf[20];
    int buf_pos;
    void receiveEvent(int howMany)
    {
      while (Wire.available()) {
        buf[buf_pos] = Wire.read();
        buf_pos++;
        if (buf[0] == 'f') { // starts with known command
          if (buf_pos>= sizeof(char)+2*sizeof(int)) { // have all data already collected
            from=0;
            for (i=0;i<sizeof(int);i++) from=from<<8+buf[sizeof(char)+i];
            to=0;
            for (i=0;i<sizeof(int);i++) to=to<<8+buf[sizeof(char)+sizeof(int)+i];
            changed = 1;
            buf_pos=0;
            } // end of buf_pos>= ...
         } else { // not started with 'f' (or anything it should know) - throw all transfer away as bad
            while (Wire.available()) Wire.read();
            buf_pos = 0;
         }
    }


body:
I'm trying to build almost exactly this device:

http://www.reuk.co.uk/wordpress/reuk-shop-low-voltage-disconnects-lvd/buy-reuk-programmable-low-voltage-disconnect-with-display/

It is a low voltage disconnect but has an interesting feature that requires the "cutoff" and "reconnect" voltages to be reached for 10 seconds before the connection is actually cut/re-connected to prevent premature status changes from voltage spikes/sags (Such as starting a car, or a motor with high start draw)

I need some example code that handles the timer portion. I can handle the "if this voltage is reached, disconnect the relay" (or transistor in the link I provided) part.

I need help making it "If this voltage has reached XX for 10 seconds then -do something-"

title: Building a low voltage disconnect w/ timer - need help with the timer

Answers: 2

body:
Assuming you have a function `voltageIsReached()`, here's a very simple way of doing it, which is OK if you don't have anything else to do in the mean time.

    if (voltageIsReached()) {
        long end = millis() + 10000;   // 10s from now
        boolean voltageWasReachedFor10s = false;
        while (voltageIsReached()) {
            if (millis() >= end) {
                voltageWasReachedFor10s = true;
                break;
            }
            delay(1);
        }
        if (voltageWasReachedFor10s) {
            // Do whatever you have to do
        }
    }

If you *do* have something else to do while you're waiting for this 10s state, you will need to adapt this, but I hope it'll get you started.

body:
Write a function that has a static variable that keeps the previous time that the voltage has not been reached. That routine will read the voltage and reset the static variable to current time whenever the voltage has not been reached.

Such a routines can either return a logic value or a time value , depending on your implementation.


body:
I'm building a scale which reads a value (from a load cell) and outputs it on a LED screen.

There is a function for the scale, *read* which will read the value from the scale.
However this is not instantaneous - it uses the yield function to wait until the scale is ready.

The LED screen has a function, *display* which will display an integer on the screen with no delay. However, this lasts barely a fraction of a second, so it must be repeatedly called.

These functions as is are called one after another inside *loop()*, but it causes only a quick flash of the LED screen followed by a half second of reading.

How would I allow the LED screen to keep displaying a value while the scale reads? I know there's BlinkWithoutDelay - but I'm not using specific times. There is no instance of the function *delay* anywhere in the program. I also am not going to edit the library which reads the load cell.

title: How to run functions concurrently

Answers: 4

body:
Put the `value` variable outside the loop (as a global variable).

Then, call the `display` function **BEFORE** the `read` function.

---

This is not the best, but if should work *fine*.

body:
There is only one execution unit in this MCU so you can not truly run multiple tasks concurrently.

However, you can achieve the appearance of concurrency by running a higher priority task through an interrupt. For example, you cannot afford to have flickering disspplay. So set up a timer that invokees the display routine periodically. If you set the timer interrupt sufficiently small (over 25hz for example), the display will not flicker.

Your other routines can be run in other isr or in the main loop so they are interrupted by the display routine periodically. In a way that's fully transparent to you.

body:
There is similar questions answered a day ago - [Multithreading with Arduino][1]. What your are asking is multitasking or multithreading. Tasks have own loop and task scheduler stops and switches tasks periodically so they appear as if running simultaneously. Task scheduler in turn is usually driver by timer ISR, for AVR a 50-100Hz scheduler timer tick frequency is reasonable.

If there are 2 tasks with same priority (given task scheduler supports priority), they will spare MCU time ~ 50% / 50%. So if timer is 100Hz, each task runs 5ms and interrupted.

Surely task scheduler have overhead, but for small frequency it is negligible, less than 1%. There is no need to modify existing code/library, time sharing is organized transparently.

There are rules to follow when doing multitasking: for example when the scale related function is writing measured value of `double` type into some variable, this task might be interrupted (by scheduler) during the writing (when only half of the values is written) - and another task will see an incorrect value. The easiest way would be disabling the interrupts during such shared variable update. Google for "race condition", atomic operation, synchronization.

  [1]: https://arduino.stackexchange.com/questions/18538/multithreading-with-arduino

body:
Here is sketch in pseudo-code that can keep your display going and still make frequent weight measurements, without having to do any multi-threading or similar. The value of 'if a measurement is ready' (below) may come from a status bit in the scale, or simply a time difference using the millis() function; I don't know the specifics of your hardware.
I showed weight being an integer. Again, you may need to adapt this to your own hardware. But it is an uncomplicated process for displaying frequently to maintain the display, and reading whenever data is available so the display updates as you get new data, no concurrency required.

    void setup()
    {
       // initialize everything;
       // start the first measurement;
    }

    void loop()
    {
       static int16_t weight = 0;

       // if a measurement is ready,
          // read the value and store it in 'weight;'
          // start a new measurement
       // endif

       // display 'weight' on the LCD;
    }


body:
I have a fixed roof light in my room that came with a remote control that can be fully taken apart. The remote control can switch the lights on or off using a radio system. I was wondering if there was any way to use my Arduino to control the remote control (through wires) to control the lights. I do not have any Arduino radio components so it would still need to go through the original remote. I have taken the remote apart and this is what it looks like:

http://go.hma-uk.org/dlt

The buttons are as follows: the top two (K1 & K2) buttons is to turn on/off a coloured LED but these are not important to me. The button K3 is to turn on/off the main light (I want the effect of this button being pressed to be created using the Arduino) and the button K4 is to turn all lights on/off.

  [1]: https://i.stack.imgur.com/pXRMk.jpg
  [2]: https://i.stack.imgur.com/t82kJ.jpg
  [3]: https://i.stack.imgur.com/l0dM1.jpg

title: Remote controlled lights

Answers: 1

body:
I used to use gamepads as input device for USB many years ago. I simply soldered wires paralel to buttons and shortcut them to "simulate" the button press - it worked nice and reliable.

With Arduino - I would measure the voltage on the button in question with Voltmeter - if the voltage is less then Vcc of Arduino (5Volts), I would simply connect Arduino ground to lower side (negative) of the button and output pin to the high side of the button. Then I would set that pin for Input to have the button released (from Arduino side) and to LOW + Output to have it pressed. (maybe I would first shortcut the button with Ampermeter to see, that no more, than 100mA is sinking there).

If the sink is more, or the voltage is more, then I would use relay and shortcut the button with the relay, switching the relay with Arduino.

( something like this http://www.instructables.com/id/Home-Automation-How-to-Add-Relays-to-Arduino/?ALLSTEPS )


body:
I'm writing a simple application that reads voltage from analog input 0. Here is the code:

    #define OUT 5
    #define ADC 0

    void setup() {
      ADMUX &= (0<<REFS0); //Setting reference voltage to internal 1.1V
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(0);
      float voltage = sensorValue * (1.1 / 1023.0);
      if (voltage>0.5) {
        digitalWrite(OUT,HIGH);
      } else {
        digitalWrite(OUT,LOW);
      }
    }

When I apply 1 V on ADC0, the OUT pin is low. Seems like the reference voltage is not set properly. When I set VREF to VCC (5V), everything works fine.

I cannot find the mistake. Would appreciate any help:)

Edit:

Link to datasheet: http://www.atmel.com/images/doc8008.pdf

title: ATtiny88 ADC reference voltage setting

Answers: 2

body: In your setup section, you want to set or clear all relevant bits in admux.

body:
The statement

    ADMUX &= (0<<REFS0);

AND's the current value of ADMUX with zero, resulting in a zero value, and stores it into ADMUX.

To clear the REFS0 bit in ADMUX without affecting the rest of it, one generally would instead say

    ADMUX &= ~(1<<REFS0);

which will AND its value with the complement of `1<<REFS0`.

However, you should use the statement

    analogReference(INTERNAL);

instead of setting ADMUX directly.  One of the first statements executed in the [`analogRead()` source code](http://garretlab.wb.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html) is

    ADMUX = (analog_reference << 6) | (pin & 0x07);

which overrides reference selections made by just changing ADMUX.

Parameters `INTERNAL` and `DEFAULT` to [analogReference()](https://www.arduino.cc/en/Reference/AnalogReference) select either the 1.1 V internal bandgap reference or the default analog reference, Vcc.

---

*Edit 1:*  If you replace `ADMUX &= (0<<REFS0)` with `analogReference(INTERNAL)` in setup and it still doesn't work, you will need to apply some more-powerful debugging aids.  For example, check that you got the sketch to correctly compile and that you uploaded it ok.  Check that AVCC is connected to Vcc, preferably through a low-pass filter, as noted in datasheet sections §1.1.2 and §17.9, “Analog Noise Canceling Techniques”.  Then, try several voltage inputs to see at what level the LED comes on.  If it doesn't ever come on, look for LED problems using a simple sketch like Blink.  If it comes on consistently at some input voltage, work out what reference is being applied.

---

*Edit 2:*  Apparently the source code of `analogRead()` is different for ATtiny parts vs others.  The code that I see for it in ... /arduino/avr/cores/arduino/wiring_analog.c [your path may differ] is like the following (I've elided some comments and blank lines).

    uint8_t analog_reference = DEFAULT;
    void analogReference(uint8_t mode) {
      analog_reference = mode;
    }

    int analogRead(uint8_t pin) {
      #if defined( CORE_ANALOG_FIRST )
        if ( pin >= CORE_ANALOG_FIRST ) pin -= CORE_ANALOG_FIRST; // allow for channel or pin numbers
      #endif
      ADC_SetVoltageReference( analog_reference );
      ADC_SetInputChannel( pin );
      ADC_StartConversion();
      while( ADC_ConversionInProgress() );
      return( ADC_GetDataRegister() );
    }

Some `ADC_...` functions and constants are defined in ... avr/cores/tiny/core_adc.h; and which definition of `ADC_SetVoltageReference()` is used depends on conditional compilation.  For a definitive check on how `analogReference()` is defined for your part, look for `analogReference()` within the assembly listing of your program.  Obtain that listing as explained in several Arduino SE answers, for example in the  “Making assembly listings” paragraph near the end of [my answer to question #33033](https://arduino.stackexchange.com/a/33042/3917). Also, [a forum.arduino.cc thread from late April 2016](https://forum.arduino.cc/index.php?topic=299759.45) has some discussion of reading ADC inputs on tinys; I don't know if it's relevant.


body:
I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.

    int in1 = 4;
    int in2 = 5;
    int in3 = 6;
    int in4 = 7;

    void setup() {
      Serial.begin(9600);
      pinMode (in1, OUTPUT);
      pinMode (in2, OUTPUT);
      pinMode (in3, OUTPUT);
      pinMode (in4, OUTPUT);
    }

    void loop() {
      if (Serial.available()) {
        int command = Serial.read();
        move(command);
      }
    }

    void move(int command) {
        if (command == 'f') forward();
        else if (command == 'b') backward();
        else if (command == 'l') left();
        else if (command == 'L') leftback();
        else if (command == 'r') right();
        else if (command == 'R') rightback();
        else if (command == 's') stop();
    }

Now what I want is to identify whether there is connection or it is lost. For example:

    if(Serial.connectionLost()) stop();

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?

title: How to identify connection lost on HC-06?

Answers: 2

body:
Two possible ways I see:

 - Connect the HC-06 LED anode (or cathode, depending on how it's driven) to an Arduino input pin. Since you can tell from the blink frequency if the module is paired with your phone or not, you can use that (through interrupts maybe) as a means to know if you're still connected to your phone.
 - Find a way to configure the android app (or write your own app) to either regularly ping your Arduino or to respond to ping requests from the Arduino. If the Arduino fails to get a ping request (in the first case) or a ping response (in the second case) after some pre-agreed interval, it decides the connection has been broken and halts the RC car.

Second way is less messy but may require some android programming skills on your part. I remember coming across an app in the Play Store that sends '#' constantly even when idle, with your own characters in between. That would work as well as a ping, if you could find something similar, and the only programming you'd need to do would be on the Arduino's side.

body:
My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.

Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) [datasheet][1].

[![Location of LED edge-pin][2]][2]

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.

[![LED signal detail][3]][3]

  [1]: https://www.olimex.com/Products/Components/RF/BLUETOOTH-SERIAL-HC-06/resources/hc06.pdf
  [2]: https://i.stack.imgur.com/BZsyL.jpg
  [3]: https://i.stack.imgur.com/8agdp.jpg


body:
I've searched the internet quite a bit and all I find is how to make two esp8266 communicate. What I am trying to do is connect a single esp8266 to the arduino and have a two-way communication between them.

I want to send and receive data on both the Arduino and ESP8266. The concept is to send data to the esp8266 over WiFi connection and then send that data to the Arduino. The Arduino will manipulate it and send it back over WiFi.

I feel like this would be a common beginner example to have a two-way communication over a TX/RX connection, but I can't seem to find any. All examples I find are strictly one as sender and other as receiver.

title: Arduino and ESP8266 Two-way Communication

Answers: 2

body:
See https://arduino.stackexchange.com/questions/33540/how-can-i-verify-that-my-esp8266-is-working asked 2 hours before.

use something like https://www.sparkfun.com/products/12009 or https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Usual way is let the Arduino direct the ESP, but if you are able to program ESP too, then any communication can work the same way as between twou ESPs or two Arduinos (with the level shift in mind)

body:
The best way for connecting ESP8266, Arduinos and devices like displays, RTC, etc., is using the serial protocol I2C.

I2C is a master-slave protocol. In this case, ESP8266 will be your master, and every other device (including Arduino) will be a slave. Every slave had an *address*, for id purposes. You can have up to 127 slaves, in theory, but real limits is determined by space, distance, capacitance, etc.

Only masters can initiate communication, so you have to program your ESP8266 to poll the the Arduino for sending back the processed information.

Connection is simple. For a I2C device (slave or master), you need Vcc and GND, plus two lines for communication: SDA and SCL.

For programming, you have lots of tutorials and examples on how to use I2C.

Both ESP8266 and Arduino (an many others MCU I think) can speak I2C. I strongly recommend you to adopt this protocol for everything. If you want to buy some device (like a display), always looks for the I2C version.


body:
I want to integrate Pololu's [vl53l0x Time of Flight distance][1] sensor into a project of mine. They created a [library][2] to interface with the vl53l0x over I2C, which works great on my Uno. The only problem is that Wire.h doesn't work on the ATtiny85.

[TinyWireM][3] is a replacement library for Wire that I think would be compatible. My question is this: how can I go about replacing all the calls to the Wire library with calls to the TinyWireM library? Is it as simple as replacing all instances of Wire with TinyWireM? Is there anything else I need to do to make the library ATtiny85 compatible?

Thanks!

  [1]: https://www.pololu.com/product/2490
  [2]: https://github.com/pololu/vl53l0x-arduino
  [3]: https://github.com/adafruit/TinyWireM

title: Replace Wire library with TinyWireM

Answers: 2

body:
In fact, there would be nothing to do now I guess, as TinyWireM is now included tiny boards packages.

If you just include Wire as usual, it should work as on an UNO.
Except for setting a different clock, if I remember well, it is fixed to 400kHz.

body:
I can't guarantee it will work, but it is probably possible to just modify the library. You can find the source code for that ToF sensor library here:

https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp

The first step is to find the reference to *Wire.h* (line 7 in that file) and change it to *TinyWireM.h*. After that, you would need to find the functions that call the *Wire* library and replace them with the appropriate *TinyWireM* functions instead. Those begin at line 284 (`Wire.beginTransmission(address);`). You can find the source code for TinyWireM here (which should tell you all of the functions in the library):

https://github.com/adafruit/TinyWireM/blob/master/TinyWireM.cpp

So `Wire.beginTransmission(address);` would become `TinyWireM.beginTransmission(address);` and `Wire.write(reg);` would become `TinyWireM.send(reg);`

I'm not sure if that's all of the solution, but I think that's a good start.


body:
I'm making a POV display (4 spokes) on a bike wheel using a Hall effect sensor to measure how long the last revolution took and based on that I calculate delays in the display. By pedalling at a constant rate I should get roughly a nice image but all I got is an unsynchronized mess. It seems like it is going and image is stable but after around half of a turn it scrambles.

I divided the wheel into 32 even parts which uses the same LED colour. Any advice how to achieve full synchronization. Any thoughts?

Here is my code:

    #include "Adafruit_WS2801.h"
    #include "SPI.h"
    #ifdef __AVR_ATtiny85__
    #include <avr/power.h>
    #endif
    #include <time.h>
    #include <stdlib.h>

    #define MIN_TIME 150000
    #define MAX_TIME 1000000
    #define RADIUS 240
    #define MAGNETS_NUM 1
    uint8_t shwFg = 1;
    uint8_t dataPin1  = 2; // White wire on Adafruit Pixels
    uint8_t dataPin2  = 3; // Yellow wire on Adafruit Pixels
    uint8_t dataPin3  = 4; // Yellow wire on Adafruit Pixels
    uint8_t dataPin4  = 5; // Yellow wire on Adafruit Pixels
    uint8_t clockPin1 = 10; // White wire on Adafruit Pixels
    uint8_t clockPin2 = 11; // Green wire on Adafruit Pixels
    uint8_t clockPin3 = 12; // Green wire on Adafruit Pixels
    uint8_t clockPin4 = 13; // Green wire on Adafruit Pixels
    uint8_t hallPin  = 20;
    uint8_t pointer1 = 0;
    uint8_t pointer2 = 8;
    uint8_t pointer3 = 16;
    uint8_t pointer4 = 24;
    uint8_t LED1R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED2R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED3R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED4R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED5R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED6R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED7R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED8R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED1B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED2B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED3B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED4B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED5B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED6B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED7B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED8B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED1G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED2G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED3G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED4G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED5G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED6G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED7G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED8G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    long now = 0;
    long prev = 0;
    int hallState = 0;
    unsigned long previous = 0;
    unsigned long dlyMic = 123456;
    Adafruit_WS2801 strip = Adafruit_WS2801((uint16_t)8, dataPin1, clockPin1);
    Adafruit_WS2801 strip2 = Adafruit_WS2801((uint16_t)8, dataPin2, clockPin2);
    Adafruit_WS2801 strip3 = Adafruit_WS2801((uint16_t)8, dataPin3, clockPin3);
    Adafruit_WS2801 strip4 = Adafruit_WS2801((uint16_t)8, dataPin4, clockPin4);
    int a = 0;
    unsigned long current = 0;
    unsigned long  delta = 0;

    void GetDelay() {
      previous = current;
      current = micros();
    }

    void setup() {
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif
      pinMode(hallPin, INPUT);
      Serial.begin(115200);
      strip.begin();
      strip2.begin();
      strip3.begin();
      strip4.begin();
      attachInterrupt(3, GetDelay, HIGH);
    }

    void delayMicroseconds2(unsigned int us) {
      // calling avrlib's delay_us() function with low values (e.g. 1 or
      // 2 microseconds) gives delays longer than desired.
      //delay_us(us);
      // for the 16 MHz clock on most Arduino boards
      // for a one-microsecond delay, simply return.  the overhead
      // of the function call yields a delay of approximately 1 1/8 us.
      if (--us == 0) return;
      // the following loop takes a quarter of a microsecond (4 cycles)
      // per iteration, so execute it four times for each microsecond of
      // delay requested.
      us <<= 2;
      // account for the time taken in the preceeding commands.
      us -= 2;
      // busy wait
      __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
      );
    }

    void loop() {
    delta  = current - previous;
    delta<<5;
    delta-=6800; //time required for loop

      if (shwFg == 0) {
        int i;
        for (i = 0; i < 8; i++) {
          strip.setPixelColor(i, 0, 0, 0);
          strip2.setPixelColor(i, 0, 0, 0);
          strip3.setPixelColor(i, 0, 0, 0);
          strip4.setPixelColor(i, 0, 0, 0);
        }
      } else {
        strip.setPixelColor(0, LED1R[pointer1] , (LED1B[pointer1] ) , (LED1G[pointer1] ) );
        strip2.setPixelColor(0, LED1R[pointer2] , (LED1B[pointer2] ) , (LED1G[pointer2] ) );
        strip3.setPixelColor(0, LED1R[pointer3] , (LED1B[pointer3] ) , (LED1G[pointer3] ) );
        strip4.setPixelColor(0, LED1R[pointer4] , (LED1B[pointer4] ) , (LED1G[pointer4] ) );
        strip.setPixelColor(1, LED2R[pointer1] , (LED2B[pointer1] ) , (LED2G[pointer1] ) );
        strip2.setPixelColor(1, LED2R[pointer2] , (LED2B[pointer2] ) , (LED2G[pointer2] ) );
        strip3.setPixelColor(1, LED2R[pointer3] , (LED2B[pointer3] ) , (LED2G[pointer3] ) );
        strip4.setPixelColor(1, LED2R[pointer4] , (LED2B[pointer4] ) , (LED2G[pointer4] ) );
        strip.setPixelColor(2, LED3R[pointer1] , (LED3B[pointer1] ) , (LED3G[pointer1] ) );
        strip2.setPixelColor(2, LED3R[pointer2] , (LED3B[pointer2] ) , (LED3G[pointer2] ) );
        strip3.setPixelColor(2, LED3R[pointer3] , (LED3B[pointer3] ) , (LED3G[pointer3] ) );
        strip4.setPixelColor(2, LED3R[pointer4] , (LED3B[pointer4] ) , (LED3G[pointer4] ) );
        strip.setPixelColor(3, LED4R[pointer1] , (LED4B[pointer1] ) , (LED4G[pointer1] ) );
        strip2.setPixelColor(3, LED4R[pointer2] , (LED4B[pointer2] ) , (LED4G[pointer2] ) );
        strip3.setPixelColor(3, LED4R[pointer3] , (LED4B[pointer3] ) , (LED4G[pointer3] ) );
        strip4.setPixelColor(3, LED4R[pointer4] , (LED4B[pointer4] ) , (LED4G[pointer4] ) );
        strip.setPixelColor(4, LED5R[pointer1] , (LED5B[pointer1] ) , (LED5G[pointer1] ) );
        strip2.setPixelColor(4, LED5R[pointer2] , (LED5B[pointer2] ) , (LED5G[pointer2] ) );
        strip3.setPixelColor(4, LED5R[pointer3] , (LED5B[pointer3] ) , (LED5G[pointer3] ) );
        strip4.setPixelColor(4, LED5R[pointer4] , (LED5B[pointer4] ) , (LED5G[pointer4] ) );
        strip.setPixelColor(5, LED6R[pointer1] , (LED6B[pointer1] ) , (LED6G[pointer1] ) );
        strip2.setPixelColor(5, LED6R[pointer2] , (LED6B[pointer2] ) , (LED6G[pointer2] ) );
        strip3.setPixelColor(5, LED6R[pointer3] , (LED6B[pointer3] ) , (LED6G[pointer3] ) );
        strip4.setPixelColor(5, LED6R[pointer4] , (LED6B[pointer4] ) , (LED6G[pointer4] ) );
        strip.setPixelColor(6, LED7R[pointer1] , (LED7B[pointer1] ) , (LED7G[pointer1] ) );
        strip2.setPixelColor(6, LED7R[pointer2] , (LED7B[pointer2] ) , (LED7G[pointer2] ) );
        strip3.setPixelColor(6, LED7R[pointer3] , (LED7B[pointer3] ) , (LED7G[pointer3] ) );
        strip4.setPixelColor(6, LED7R[pointer4] , (LED7B[pointer4] ) , (LED7G[pointer4] ) );
        strip.setPixelColor(7, LED8R[pointer1] , (LED8B[pointer1] ) , (LED8G[pointer1] ) );
        strip2.setPixelColor(7, LED8R[pointer2] , (LED8B[pointer2] ) , (LED8G[pointer2] ) );
        strip3.setPixelColor(7, LED8R[pointer3] , (LED8B[pointer3] ) , (LED8G[pointer3] ) );
        strip4.setPixelColor(7, LED8R[pointer4] , (LED8B[pointer4] ) , (LED8G[pointer4] ) );
      }
      strip.show();
      strip2.show();
      strip3.show();
      strip4.show();

      pointer1++;
      pointer1 &= 31;
      pointer3++;
      pointer3 &= 31;
      pointer2++;
      pointer2 &= 31;
      pointer4++;
      pointer4 &= 31;
      delayMicroseconds2(delta);

    }

Pardon me, it was late in the night and I put wrong code. Of course delay should depend on delta. Changed to newest code with less job in delay. Still yields similar results.

title: Arduino time between interrupts in POV led display

Answers: 2

body:
As noted in a comment, `dlyMic` should be declared as a `volatile` variable.  This is true of any variables where `loop()` gets a value changed by an interrupt service routine, or where it puts a value for the ISR to use.  In either case, if the variable is multibyte, you may wish to surround the get or put by code to turn interrupts off and on, to avoid race conditions where the ISR is reading or changing a value coincidentally with `loop()` changing or reading it.  For example:

    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++somethingimportant;  // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status

Aside from that, your treatment of `dlyMic` resembles a bad random number generator.  It consists of a declaration line; a couple of lines in the ISR; and use as a delay parameter in `loop()`:

    unsigned long dlyMic =123456;
    ...

      dlyMic<<5;
      dlyMic-=6500;
    ...
    delayMicroseconds2(dlyMic);

The following two lines of Python compute the series of numbers that will result as values of `dlyMic`.

    dlyMic=123456; mk = 2**32-1
    for i in range(14): print dlyMic; dlyMic=(dlyMic*32-6500)&mk

They produce:

    123456
    3944092
    126204444
    4038535708
    384117276
    3701811740
    2493852188
    2493852188
    2493852188
    ...

You may wish to connect up your `dlyMic` calculations with your measurement, `delta`.

body:
The following code was from a [rejected suggested edit][1], by an anonymous user, to the original post. See also [Rejected edit results in loss of constructive code modification][2].

 I have reproduced the code here - it may be of some use to someone:

    #include "Adafruit_WS2801.h"
    #include "SPI.h" // Comment out this line if using Trinket or Gemma
    #ifdef __AVR_ATtiny85__
    #include <avr/power.h>
    #endif
    #include <time.h>
    #include <stdlib.h>

    #define MIN_TIME 150000
    #define MAX_TIME 1000000
    #define RADIUS 240
    #define MAGNETS_NUM 1
    uint8_t shwFg = 1;
    uint8_t dataPin1  = 2;    // White wire on Adafruit Pixels
    uint8_t dataPin2  = 3;    // Yellow wire on Adafruit Pixels
    uint8_t dataPin3  = 4;    // Yellow wire on Adafruit Pixels
    uint8_t dataPin4  = 5;    // Yellow wire on Adafruit Pixels
    uint8_t clockPin1 = 10;    // White wire on Adafruit Pixels
    uint8_t clockPin2 = 11;    // Green wire on Adafruit Pixels
    uint8_t clockPin3 = 12;    // Green wire on Adafruit Pixels
    uint8_t clockPin4 = 13;    // Green wire on Adafruit Pixels
    uint8_t hallPin  = 20;
    uint8_t pointer1 =0;
    uint8_t pointer2 =8;
    uint8_t pointer3 =16;
    uint8_t pointer4 =24;

    int addr = 0;

    uint8_t LED1R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED2R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED3R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED4R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED5R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED6R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED7R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED8R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    uint8_t LED1B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED2B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED3B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED4B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED5B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED6B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED7B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED8B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};

    uint8_t LED1G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED2G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED3G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED4G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED5G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED6G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED7G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED8G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};

    long now = 0;
    long prev =0;
    int hallState = 0;
    unsigned long previous = 0;
    unsigned long dlyMic =123456;

    Adafruit_WS2801 strip = Adafruit_WS2801((uint16_t)8, dataPin1, clockPin1);
    Adafruit_WS2801 strip2 = Adafruit_WS2801((uint16_t)8, dataPin2, clockPin2);
    Adafruit_WS2801 strip3 = Adafruit_WS2801((uint16_t)8, dataPin3, clockPin3);
    Adafruit_WS2801 strip4 = Adafruit_WS2801((uint16_t)8, dataPin4, clockPin4);

    int a = 0;
    unsigned long current=0;
    unsigned long  delta=0;
    void GetDelay() {
      previous = current;
      current = micros();

    //  previous = micros();

    }

    void setup() {
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif

     pinMode(hallPin, INPUT);
     Serial.begin(115200);

      strip.begin();
      strip2.begin();
      strip3.begin();
      strip4.begin();
      attachInterrupt(3, GetDelay, RISING);

    }
    void delayMicroseconds2(unsigned int us)
    {
            // calling avrlib's delay_us() function with low values (e.g. 1 or
            // 2 microseconds) gives delays longer than desired.
            //delay_us(us);
            // for the 16 MHz clock on most Arduino boards

            // for a one-microsecond delay, simply return.  the overhead
            // of the function call yields a delay of approximately 1 1/8 us.
            if (--us == 0)
                    return;

            // the following loop takes a quarter of a microsecond (4 cycles)
            // per iteration, so execute it four times for each microsecond of
            // delay requested.
            us <<= 2;

            // account for the time taken in the preceeding commands.
            us -= 2;

            // busy wait
            __asm__ __volatile__ (
                    "1: sbiw %0,1" "\n\t" // 2 cycles
                    "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
            );
    }
    void loop() {
     // prev = micros();
      //    noInterrupts();

      delta  = current - previous;

      if (delta > MAX_TIME) {
        shwFg = 0;
      }else{
        shwFg = 1;
      }

      shwFg = 1;
      delta<<1;
      delta-=650;

        if (shwFg == 0) {
            int i;
            for (i = 0; i < 8; i++){
              strip.setPixelColor(i, 0, 0, 0);
              strip2.setPixelColor(i, 0, 0, 0);
              strip3.setPixelColor(i, 0, 0, 0);
              strip4.setPixelColor(i, 0, 0, 0);
            }
        }
        else {

          strip.setPixelColor(0, LED1R[pointer1] ,(LED1B[pointer1] ) ,(LED1G[pointer1] ) );
          strip2.setPixelColor(0, LED1R[pointer2] ,(LED1B[pointer2] ) ,(LED1G[pointer2] ) );
          strip3.setPixelColor(0, LED1R[pointer3] ,(LED1B[pointer3] ) ,(LED1G[pointer3] ) );
          strip4.setPixelColor(0, LED1R[pointer4] ,(LED1B[pointer4] ) ,(LED1G[pointer4] ) );

          strip.setPixelColor(1, LED2R[pointer1] ,(LED2B[pointer1] ) ,(LED2G[pointer1] ) );
          strip2.setPixelColor(1, LED2R[pointer2] ,(LED2B[pointer2] ) ,(LED2G[pointer2] ) );
          strip3.setPixelColor(1, LED2R[pointer3] ,(LED2B[pointer3] ) ,(LED2G[pointer3] ) );
          strip4.setPixelColor(1, LED2R[pointer4] ,(LED2B[pointer4] ) ,(LED2G[pointer4] ) );

          strip.setPixelColor(2, LED3R[pointer1] ,(LED3B[pointer1] ) ,(LED3G[pointer1] ) );
          strip2.setPixelColor(2, LED3R[pointer2] ,(LED3B[pointer2] ) ,(LED3G[pointer2] ) );
          strip3.setPixelColor(2, LED3R[pointer3] ,(LED3B[pointer3] ) ,(LED3G[pointer3] ) );
          strip4.setPixelColor(2, LED3R[pointer4] ,(LED3B[pointer4] ) ,(LED3G[pointer4] ) );

          strip.setPixelColor(3, LED4R[pointer1] ,(LED4B[pointer1] ) ,(LED4G[pointer1] ) );
          strip2.setPixelColor(3, LED4R[pointer2] ,(LED4B[pointer2] ) ,(LED4G[pointer2] ) );
          strip3.setPixelColor(3, LED4R[pointer3] ,(LED4B[pointer3] ) ,(LED4G[pointer3] ) );
          strip4.setPixelColor(3, LED4R[pointer4] ,(LED4B[pointer4] ) ,(LED4G[pointer4] ) );

          strip.setPixelColor(4, LED5R[pointer1] ,(LED5B[pointer1] ) ,(LED5G[pointer1] ) );
          strip2.setPixelColor(4, LED5R[pointer2] ,(LED5B[pointer2] ) ,(LED5G[pointer2] ) );
          strip3.setPixelColor(4, LED5R[pointer3] ,(LED5B[pointer3] ) ,(LED5G[pointer3] ) );
          strip4.setPixelColor(4, LED5R[pointer4] ,(LED5B[pointer4] ) ,(LED5G[pointer4] ) );

          strip.setPixelColor(5, LED6R[pointer1] ,(LED6B[pointer1] ) ,(LED6G[pointer1] ) );
          strip2.setPixelColor(5, LED6R[pointer2] ,(LED6B[pointer2] ) ,(LED6G[pointer2] ) );
          strip3.setPixelColor(5, LED6R[pointer3] ,(LED6B[pointer3] ) ,(LED6G[pointer3] ) );
          strip4.setPixelColor(5, LED6R[pointer4] ,(LED6B[pointer4] ) ,(LED6G[pointer4] ) );

          strip.setPixelColor(6, LED7R[pointer1] ,(LED7B[pointer1] ) ,(LED7G[pointer1] ) );
          strip2.setPixelColor(6, LED7R[pointer2] ,(LED7B[pointer2] ) ,(LED7G[pointer2] ) );
          strip3.setPixelColor(6, LED7R[pointer3] ,(LED7B[pointer3] ) ,(LED7G[pointer3] ) );
          strip4.setPixelColor(6, LED7R[pointer4] ,(LED7B[pointer4] ) ,(LED7G[pointer4] ) );

          strip.setPixelColor(7, LED8R[pointer1] ,(LED8B[pointer1] ) ,(LED8G[pointer1] ) );
          strip2.setPixelColor(7, LED8R[pointer2] ,(LED8B[pointer2] ) ,(LED8G[pointer2] ) );
          strip3.setPixelColor(7, LED8R[pointer3] ,(LED8B[pointer3] ) ,(LED8G[pointer3] ) );
          strip4.setPixelColor(7, LED8R[pointer4] ,(LED8B[pointer4] ) ,(LED8G[pointer4] ) );
       }

        strip.show();
        strip2.show();
        strip3.show();
        strip4.show();
        //delay(10);
        pointer1++;
        pointer1&=31;

        pointer3++;
        pointer3&=31;

        pointer2++;
        pointer2&=31;

        pointer4++;
        pointer4&=31;
      //       interrupts();
       // now =micros();
        delayMicroseconds2(delta);

      //Serial.println(now - prev);

    }

  [1]: https://arduino.stackexchange.com/review/suggested-edits/22215
  [2]: https://arduino.meta.stackexchange.com/questions/2421/rejected-edit-results-in-loss-of-constructive-code-modification


body:
I am looking for a way to choose a pin on the Arduino Uno. This pin will be used to send the signal of an IR LED. I am using the **[IRremote][1]** library.

e.g.

Below is the IR send demo which uses pulse width modulation pin 3 to send the IR signal. I want to change that pin to any other pin.

Any pointers will make me very happy thanks.

  [1]: https://github.com/z3t0/Arduino-IRremote

    /*
     * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
     * An IR LED must be connected to Arduino PWM pin 3.
     * Version 0.1 July, 2009
     * Copyright 2009 Ken Shirriff
     * http://arcfn.com
     */

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
     for (int i = 0; i < 3; i++) {
      irsend.sendSony(0xa90, 12);
      delay(40);
     }
     delay(5000); //5 second delay between each signal burst
    }

title: How to choose a transmit pin in the IRremote library for an Arduino Uno?

Answers: 2

body:
As the pin does not appear to be able to be defined when creating an object from the `IRsend` class, it seems as if you will have to modify the [IRremote][1] library itself.

I recently had the same problem with the [USB Host library][3], see [Change select pin of USB Host library][2]. It *is* annoying when you can't define the pin(s), that a particular library uses, yourself... However, the authors of the library probably have their reasons for doing so.

Looking through the various headers of the library, I found in `boarddefs.h` on [lines 134-138][4]:

    // Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
    // ATmega48, ATmega88, ATmega168, ATmega328
    #else
     //#define IR_USE_TIMER1   // tx = pin 9
     #define IR_USE_TIMER2     // tx = pin 3

So, the line to change, for the Uno, would seem to be [line 138 in boarddefs.h][5]

     #define IR_USE_TIMER2     // tx = pin 3

However, it is not, as that merely states that for the Arduino Uno `IR_USE_TIMER2` is used...

Looking further down to where the Timers are defined, you will see the section for Timer 2, on [line 146][6]. In that section the transmit pin, for a number of versions of the Arduino, is defined as `TIMER_PWM_PIN` on [lines 189-197][7]:

    #elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \
    || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \
    || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \
    || defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \
    || defined(__AVR_ATmega164P__)
    # define TIMER_PWM_PIN  14             // MightyCore
    #else
    # define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc
    #endif                      // ATmega48, ATmega88, ATmega168, ATmega328

You will have to change this line in the library, [Line 196 in boarddefs.h](https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L196):

    # define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc

You could try changing the `3` so that you can use another pin. It might work. For example to use pin 5, en lieu of pin 3, change the `3` to a `5`, like so:

    # define TIMER_PWM_PIN  5              // Arduino Duemilanove, Diecimila, LilyPad, etc

**Be careful** not to choose a pin that is used by something else, **AND** I think that the pin will need to be PWM capable.

Note that the definitions that are in `boarddefs.h` used to be in `RemoteInt.h`, in earlier versions of the library. See this comment at the very top:

    // This file contains all board specific information. It was previously contained within
    // IRremoteInt.h

 So, make sure that you have the latest version of the [IRremote library][1].

-----

The above hack should also work for the Mega2560 as is uses the same timer, Timer 2, see [lines 68-71][8]:

    // Arduino Mega
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
     //#define IR_USE_TIMER1   // tx = pin 11
     #define IR_USE_TIMER2     // tx = pin 9

Other boards are also defined in this file. If you have another type of board, the timer may be different, but the process to find which line to change would be very similar...

  [1]: https://github.com/z3t0/Arduino-IRremote
  [2]: https://arduino.stackexchange.com/questions/33379/change-select-pin-of-usb-host-library
  [3]: https://github.com/felis/USB_Host_Shield_2.0
  [4]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L134
  [5]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L138
  [6]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L146
  [7]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L196
  [8]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L68

body:
I tried to find where the pin is defined and gave up, I ended up swapping to pin9 by commenting out timer2, like this:

    #define IR_USE_TIMER1   // tx = pin 9
    //#define IR_USE_TIMER2     // tx = pin 3

Not ideal since I needed 9 also and I will add how annoying this library is that although I only need to receive signals and never send...it still takes up a pin for sending.

ANyway, the posts above helped me at least get my motor shield working, thanks guys.


body:
I have made an app in VS2015 C#.Net which sends data to Serial port. The data i am sending is:

    stat>temp:39,38,;load:17,4,42,;fans>50,50,;

Where as I am receiving:

    ððððstat>temp:39,38,;load:17,4,42,;fans>50,50,;

**What I have tried:**

 - Set SerialPort Encoding to ASCII in C#
 - Set SerialPort Encoding to UTF8 in C#
 - Set SerialPort Encoding to Default in C#

All have no effect.

**Some observations:**

 - When I send the data via Serial Monitor of Arduino there is no garbage data.
 - When I send data via a USB to TTL converter via my App, no garbage. (This part confuses me more)

BAUD RATE IS: 115200.

This is the only thing I have not changed yet and I dont want to change this as the string length will increase over time. this is 43 bytes of data. It can grow to up-to around 64 or 100 bytes and that would take longer to send and even longer to read adding delays in functions that are already working before the serial interrupt.

Regards

title: Serial Getting Garbage Data with real data

Answers: 1

body:
The Arduino should read only whole lines (non-newlines until a newline). Discard the line if it doesn't start with "stat>".

This will make your program more robust and less likely to fail with bad input. Fixing the transmitting app instead still leaves your Arduino vulnerable.

Consider the rule of thumb for serial communication: "Be restrictive in what you'll transmit; be lax in what you'll receive." Specify your communication protocol (e.g. "Packets will begin with 'stat>' and end with <newline>", maximum length of a packet, formats of variables and numbers, etc.). Then write your sender to hold as tightly to the spec as possible and write your receiver to accept whatever minor variations in otherwise good packets, that won't cause you to mistakenly accept bad ones. This principle will make your communications systems more robust and easier to get working in the first place.


body:
I am working with an Arduino Due and I am having some issue with the serial Rx buffers size. I am using a GSM module and some of the replies to the Arduino exceed the number of bytes I can store in the buffer at once.

I have read about ways to increase the buffer size by modifying the Arduino default install files but I cannot take this route as my code may then be compiled on a machine with standard buffer sizes in the default install files and the module would not work correctly.

I am not sure if it is possible but I was hoping that someone might know how to increase the serial buffer size using the source code. If I can do it this way the buffer would always be the size I have specified.

title: Increase Serial Rx buffer

Answers: 1

body: Use timer interrupts to read and store the data from serial. Lets assume you are receiving data at baud rate of 115200 in default configuration (8data bits, 1 stop bit), 115200/9=12800 bytes per second, approximately 80 micro seconds for every byte, create a timer interrupt that is called once every 2 millisecond(Choose best time for your application making sure that receiver buffer does not overflow), In 2milli seconds 25bytes of data will be available in the buffer. So you can read data in batches of 25 each. From the interrupt read and store the available data from the buffer.


body:
i have a BGM113 bluetooth module that sends messages as binary form. I have to work on each bit separately. i am not sure about `Serial.read()` gets it as binary but when i am trying to see at on the serial port screen with `Serial.println(Serial.read(), BIN)` it shows me as string something like `[]...[]`
What should i do ?

title: Working on Binary code with arduino

Answers: 0


body:
In recent project, I'm working with light dimmer.

Let me explain with example of fan. In switch board, we have a fan switch which can able to ON/OFF our fan & FAN REGULATOR which vary speed of our fan. Now, when our switch ON then our fan start and then with help of regulator we can vary speed of fan. And when we switch OFF then our fan stop and we can't do anything means not vary fan speed. Same things I want in my light dimmer. One push button pressed once then it's just start my light dimmer and vise versa operation. And When push button pressed again then it's just stop my light dimmer.

Here is my full code.

    int kPinPWM = 9; // This pin provides PWM values

    int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
    int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

    int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

    int i = 0;

    int temp = 0; // Flag

    void setup()
    {
      pinMode(kPinPWM, OUTPUT);

      pinMode(kPinSW1, INPUT);
      pinMode(kPinSW2, INPUT);

      digitalWrite(kPinSW1, HIGH);
      digitalWrite(kPinSW2, HIGH);

      pinMode(kPinSw, INPUT);

      digitalWrite(kPinSw, HIGH);
    }

    void loop()
    {
      if(digitalRead(kPinSw) == LOW && temp == 0) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 0
      {
        temp = 1; // Change value to 1 // temp = 1

        digitalWrite(kPinPWM, HIGH); // Turn ON PWM pin (PIN 9)

        if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
        {
          i++;

          if(i > 4)
          {
            i = 4;
          }

          while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON pressed
        }

        if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
        {
          i--;

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

          while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
        }

        switch (i)
        {
          case 0:
                  analogWrite(kPinPWM, 0); // When Button pressed not pressed send 0 value
          break;

          case 1:
                  analogWrite(kPinPWM, 64); // When Button pressed and i = 1 send 64 value
          break;

          case 2:
                  analogWrite(kPinPWM, 128); // When Button pressed and i = 2 send 128 value
          break;

          case 3:
                 analogWrite(kPinPWM, 192); // When Button pressed and i = 3 send 192 value
          break;

          case 4:
                 analogWrite(kPinPWM, 255); // When Button pressed and i = 4 send 255 value
          break;
        }
      }

      if(digitalRead(kPinSw) == LOW && temp == 1) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 1
      {
        temp = 0; // Change value to 0 // temp = 0

        digitalWrite(kPinPWM, LOW); Turn OFF PWM pin (PIN 9)
      }
    }

title: How to on/off light dimmer using another pin?

Answers: 2

body:
Thank you for the clarification.

Here's some code which should do that:

    int kPinPWM = 9; // This pin provides PWM values

    int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
    int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

    int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

    // Startup settings:
    int level = 0;          // Lowest level
    boolean on = false;     // Off

    void setup()
    {
      pinMode(kPinPWM, OUTPUT);

      pinMode(kPinSW1, INPUT);
      pinMode(kPinSW2, INPUT);
      pinMode(kPinSw, INPUT);

      digitalWrite(kPinSW1, HIGH);
      digitalWrite(kPinSW2, HIGH);
    }

    void loop()
    {
        // Read each button in turn
        if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
        {
           level++;

           if(level > 4)
           {
             level = 4;
           }

           while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON released
        }

        if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
        {
           level--;

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

           while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
        }

        if(digitalRead(kPinSw) == LOW ) // Pressed PUSH BUTTON to switch on/off
        {
            // If we're already on, switch off.
            if (on) on=false;
            // If we're already off, switch on.
            else on=true;

            while(digitalRead(kPinSW1) == LOW); // Until button is released
        }

        // Now set the PWM output
        if (on)
        {
            // We're on, so set the level
            switch (level)
            {
                case 0:
                    // Maybe you don't want this "off" level..?
                    analogWrite(kPinPWM, 0);
                break;

                case 1:
                    analogWrite(kPinPWM, 64);
                break;

                case 2:
                    analogWrite(kPinPWM, 128);
                break;

                case 3:
                    analogWrite(kPinPWM, 192);
                break;

                case 4:
                    analogWrite(kPinPWM, 255);
                break;

                default:
                    // This should never happen but we should
                    // handle it "just in case"
                    analogWrite(kPinPWM, 255);
            }
        }
        else
        {
            // We're off, so stop the PWM
            analogWrite(kPinPWM, 0);
        }
    }

We hold two variables: the level, and on/off state.

Buttons 6 and 7 affect the level, and button 10 affects the on/off state.

As with a fan, this code lets us change the "level" even when it's switched off.  It has no immediate effect, but when you switch back on, the level will have changed.

---

Some things to say about the question in general:

 1. Try to explain more clearly exactly what you want to achieve.  For example, what *exactly* do you want button 10 to do?  Switch the PWM on?  On to what value?  I've chosen mid-way, but you could possibly want the highest value, or the lowest value, or the value it was last time you pressed button 10.
 2. There's no need to comment code so literally.  We know *literally* what `if(temp==0)` does.  What would be helpful is to give things proper names, and/or explain their *meaning*.  What are you trying to achieve with `temp`?  (It wasn't clear to me at all, so I removed it.)

body:
Finally I find out solution. Here, I detect when switch becomes pressed instead of  button is pressed. So, for that I used StateChangeDetection. So while loop just removed from code. And I made function to perform dimmer and vise versa operation.
k
So, now I'm able to ON/OFF the PWM pin. And also vary PWM pin. Thanks everyone for your effort.

Here, it's my full code.

    const int buttonPin1 = 2;
    const int buttonPin2 = 3;
    const int buttonPin3 = 4;

    const int pwmPin = 9;

    const int onOffPin = 10;

    int buttonState1 = 0;
    int lastButtonState1 = 0;

    int buttonState2 = 0;
    int lastButtonState2 = 0;

    int buttonState3 = 0;
    int lastButtonState3 = 0;

    int buttonPushCounter = 0;

    int onOffCounter = 0;

    void setup()
    {
       pinMode(buttonPin1, INPUT);
       pinMode(buttonPin1, INPUT);

       pinMode(pwmPin, OUTPUT);

       pinMode(onOffPin, OUTPUT);

       Serial.begin(9600);
    }

    void loop()
    {
       buttonState3 = digitalRead(buttonPin3);

       if(buttonState3 != lastButtonState3)
       {
         if(buttonState3 == HIGH)
         {
           onOffCounter++;
           Serial.println("Button 3 on");
           Serial.print("number of button 3 pushes:  ");
           Serial.println(onOffCounter);
         }
         else
         {
           Serial.println("Button 3 off");
         }
         delay(50);
       }

       lastButtonState3 = buttonState3;

       if(onOffCounter % 2 == 0)
       {
         Serial.println("Switch is OFF");

         analogWrite(pwmPin, 0);
       }
       else
       {
          PWM_fun();

          Serial.println("Switch is ON");
       }
    }

    void PWM_fun()
    {
      buttonState1 = digitalRead(buttonPin1);

      if (buttonState1 != lastButtonState1)
      {
        if (buttonState1 == HIGH)
        {
          buttonPushCounter++;
          Serial.println("Button 1 on");
          Serial.print("number of button 1 pushes:  ");
          Serial.println(buttonPushCounter);

          if(buttonPushCounter > 4)
          {
             buttonPushCounter = 4;
          }
        }
        else
        {
          Serial.println("Button 1 off");
        }
        delay(50);
      }

      lastButtonState1 = buttonState1;

      buttonState2 = digitalRead(buttonPin2);

      if(buttonState2 != lastButtonState2)
      {
        if(buttonState2 == HIGH)
        {
          buttonPushCounter--;
          Serial.println("Button 2 on");
          Serial.print("number of button 2 pushes:  ");
          Serial.println(buttonPushCounter);

          if(buttonPushCounter < 0)
          {
             buttonPushCounter = 0;
          }
        }
        else
        {
          Serial.println("Button 2 off");
        }
        delay(50);
      }

      lastButtonState2 = buttonState2;

      switch (buttonPushCounter)
      {
          case 0:
                  analogWrite(pwmPin, 0);
          break;

          case 1:
                  analogWrite(pwmPin, 64);
          break;

          case 2:
                  analogWrite(pwmPin, 128);
          break;

          case 3:
                  analogWrite(pwmPin, 192);
          break;

          case 4:
                  analogWrite(pwmPin, 255);
          break;
      }
    }


body:
I have some background music. If I put it at the top of the `void loop()`, it'll first play the music and then execute the game code afterwards.

How do I have the code run while the background music is playing?

title: How to run background music while the code for a game is executed

Answers: 2

body: Run the music through a time Interrupt.

body:
It all depends on the architecture of your game. The first games probably interleaved their music and gameplay, as the comment above says. This is probably the level of complexity you are looking for, on an Arduino.

First you need to pick some "framerate" that the game advances with. You could, for example, play 4 frames of music for every video frame, or something like that. It also depends how you are playing music. If you are just playing notes with the analog out, this approach would work. Here is some pseudocode that updates the PWM output 4 times faster than the game code:

    set n = 0
    set quit = false

    // main game loop
    while !quit
        // set music output pwm here
        if n % 4 == 0
            // advance game here
        endif
        n++
    endwhile

If you are playing music from something like an SD card, you are constrained by the bit rate of the music.

Also, here is an article on Arduino **protothreading** that might interest you. https://create.arduino.cc/projecthub/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37. My suggestion is to look at how the old game systems implemented their state machines.


body: I carefully followed [Andy Sigler's tutorial](http://andysigler.com/teaching/nodejs-arduino-yun/) on how to setup node.js on Arduino Yun. But I'm getting this error "Cannot find module 'serialport'". my node.js file is in mnt/sda1/arduino/node folder. and I have installed node-serialport successfully through ssh. Kindly helpc

title: Error: Cannot find module 'serialport'. node.js, Arduino Yun

Answers: 1

body:
I solved the problem by following these steps:

Make a folder node_modules in mnt/sda1/

cd /mnt/sda1

wget http://wiki.linino.org/lib/exe/fetch.php?media=wiki:serialport-1.6.1_mips-25-ubuntu.tar.gz -O serialport-1.6.1_mips-25-ubuntu.tar.gz

run $ tar xvf serialport-1.6.1_mips-25-ubuntu.tar.gz -C /mnt/sda1/node_modules


body:
I've started to prototype something using an Arduino Mega and Yún Shield.

It's simple. It reads an ADC at 50Hz and sends data to a server through a socket. But because of that combination, I need to use Bridge to send data through the socket. It's very slow.

Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

Here is my code, maybe I did something wrong.

Arduino code:

    #include <Bridge.h>
    #include <Process.h>
    #include <Time.h>
    #include <TimeLib.h>
    #include <stdlib.h>

    boolean interruptFlag = 0;
    int HD = A0;
    int HG = A1;
    int CD = A2;
    int CG = A3;
    int ECG = A5;
    String analogSignals = "";
    static char outstr[15];
    int count = 0;
    float x = 0.0;

    void setup() {
      // Bridge startup.
      Bridge.begin();
      // Initialize Bridge values.
      Bridge.put("data", "");
      noInterrupts(); // Stop interrupts.
      TCCR1A = 0; // Set entire TCCR1A register to 0.
      TCCR1B = 0; // Same for TCCR1B.
      TCNT1  = 0; // Initialize counter value to 0.
      // Set compare match register for 50Hz increments.
      OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
      // Turn on CTC mode.
      TCCR1B |= (1 << WGM12);
      // Set CS12, CS11 and CS10 bits for 64 prescaler.
      TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
      // Enable timer compare interrupt.
      TIMSK1 |= (1 << OCIE1A);
      interrupts(); // Allow interrupts.
      // Launch Python script.
      /*Process p;
      p.begin("python");
      p.addParameter("/root/test/send.py");
      p.run();*/
    }

    ISR(TIMER1_COMPA_vect) {
      if (!interruptFlag) {
        interruptFlag = 1;
      }
    }

    void loop() {
      if (interruptFlag) {
        writeAnalogSignals();
        interruptFlag = 0;
      }
    }

    void writeAnalogSignals() {
      String HDReading = convertToVoltage(analogRead(HD));
      String HGReading = convertToVoltage(analogRead(HG));
      String CDReading = convertToVoltage(analogRead(CD));
      String CGReading = convertToVoltage(analogRead(CG));
      String ECGReading = convertToVoltage(analogRead(ECG));
      if (analogSignals.length() == 0) {
        analogSignals =  String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
      } else {
        analogSignals += "|" + String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
      }
      x += 0.02;
      count += 1;
      if (count >= 50) {
        Bridge.put("data", analogSignals);
        analogSignals = "";
        count = 0;
      }
    }
    // Convert the analog reading to voltage.
    String convertToVoltage(int analogSignal) {
      dtostrf(analogSignal * (5.0 / 1023),8, 6, outstr);
      return outstr;
    }

Python code:

    import socket
    import sys
    import getopt
    import time

    def main(argv):
     try:
      sys.path.insert(0, '/usr/lib/python2.7/bridge/')
      from bridgeclient import BridgeClient as bridgeclient
      # Create a UDP socket.
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      server_address = ('192.168.1.100', 9050)
      bridge = bridgeclient()
      previous = ""

      # Send data
      while 1:
       data = bridge.get("data")
       if data != previous:
        sent = sock.sendto(data, server_address)
        previous = data
       time.sleep(0.5)

     finally:
      sock.close()

title: Which Arduino is the most suitable for my project?

Answers: 4

body:
The Bridge running in Python in Linux is the biggest problem. Open a terminal (for example with putty) and run `top` to see the CPU usage. Try to keep it under 50%.

A few parameters at 5 times per second with `Bridge.put()` is possible, but I don't recommend it, because of the CPU load in Linux. The 50Hz is way too much. Beside that you have also a Python script to send them to a server.

There is about 30 MB of fast RAM storage in /tmp and more storage if you add an SD memory card. You could do a test to write the data to a file, and upload the file every few seconds.

If you really need 50Hz, then I suggest to try the Raspberry Pi (or the ESP8266, as mentioned).

The `dtostrf()` function does not return a String, but a buffer. You could easily get rid of the Strings, to have more time in the Arduino. A good use of` millis()` is just as accurate as a timer. I think you can do the same without the hardware timer and without the interrupt.

**ADDED:** Chris Stratton pointed out that the Bridge is not the problem, so I did a small test.

Using 4 values with short names (like: "temp"). Writing them with `Bridge.put()` every second, and reading them in a webpage via `zepto.min.js` every second is a CPU load of 6% for `python -u bridge.py`.

Writing them 50 times per second and reading 1 time per second is a CPU load of 25% for the bridge.

Writing them 50 times per second and reading them 50 times per second does not change a lot, it adds extra load for uhttpd, resulting in a total of about 60 to 70%. That is still okay to run commands from a terminal.

This 'clean' test is different from my previous tests. It is therefore indeed possible to send data through the Bridge at 50 times per second. Sorry for my wrong answer.

body:
> Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

You didn't quite say what kind of performance gains you had in mind. Looking at your code, it doesn't have any particular needs to justify a fancier Arduino.

With that said, I wanted to highlight one particular aspect of ATmega32u / Leonardo that in my view made it a particularly interesting chip for mixed signal application: its ADC unit features a PGA (1x, 10x, 200x) in differential mode with bipolar readings.

it can be quite handy for some applications.

body:
Both Mega 2560 and Due can handle 4 channels of 1,440 samples per second A-to-D and the least significant byte of the system time stamp sent as a continuous stream of vectors through the USB port to Linux.

In the lab I train at, we see almost no variance in time increment between samples or between receiver read operations, indicating that the bottleneck is our deliberate delays between samples.

The Due is running at full resolution too and communicates via the native port. The receiver process is running in normal user process priority, not boosted for real time.

We use C++ for both endpoints, the embedded Arduino code and the receiver, but the C++ on the Arduino side runs just as fast as the same loop in Arduino sketch language. Python low-level reads are generally able to handle this same level of throughput with ease too, so it is not likely that your hardware or speed goals that are the problem.

I can see a few design issues right away.

1. Don't use libraries for what one can do in just a few low level lines of code.
2. Don't place numbers in strings. Keep them as numbers.
3. Send the numbers as messages placed carefully into byte arrays using bitwise operations.
4. Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
5. Most importantly, find the various code examples that people posted on the Arduino blogs when testing USB baud rates (speed).

The lab engineers started with that speed testing code, replicated the throughput published with it, and then added A-to-D conversion and other features one step at a time.

It is recommended that you place the code under version control and then, with each change, test the speed again. That way you'll notice any bottleneck you introduce immediately and can see the exact changes that must have caused it.

body:
@JonathanAnctil, @ChrisStratton, I have done some more tests, and the Bridge.put takes an average of 7 milliseconds in the sketch. For 5 values at a rate of 50Hz, that alone takes 1.7 seconds. The Bridge can not keep up with that rate, but the overall cpu load in linux is still under 50%. Therefor the cpu load does not indicate if everything is running okay.

Because I was looking at the cpu load, I took the wrong assumption that it was possible. These tests confirm my previous experiences that the Bridge is too slow.

I have installed extra packages in linux, but I think they will not influence the slow Bridge.put.

With more tests with Bridge.put I learned that Bridge.put takes 4ms, plus 0.3ms per character for the key name and the value text, plus the delay caused by things running at the other side of the Bridge in linux.

The value must be a zero terminated string, it is not possible to send binary data. Suppose turning it into readable hex values, then 20 bytes are needed for the value.
With the key name as a single character, and a value of 20 bytes, it takes 10 ms. However, then the values have to be retrieved (and converted) at the other side of the Bridge. I assume that Python will also slow down the Bridge.put, just like Javascript does.

This is my test sketch.

    // Showing the webpage on the other side of the Bridge with zepto.min.js
    // and 50 updates per seconds slows down the sketch, because the Bridge.put
    // in the sketch will take a lot more time.
    // A Bridge.put takes about 7 to 260 ms when the webpage is in a browser
    // with 50Hz updates.
    // A Bridge.put takes about 7 ms when the webpage is not shown in a browser.
    // A itoa takes about 13 us.
    //
    // When showing the webpage with 50Hz updates:
    //     Only the counter : 43 seconds for 1000 counts = 23 Hz
    //     With 6 analog inputs and the free ram : 342 seconds for 1000 counts = 3 Hz
    // When showing the webpage with once per 5 seconds updates:
    //     Only the counter : 20 seconds for 974 counts = 49 Hz
    //     With 6 analog inputs and the free ram : 50 seconds for 985 counts = 20 Hz

    #include <Bridge.h>

    Process yunProcess;

    unsigned long previousMillis;

    #define NUM_PINS 6
    const int pins[NUM_PINS] = { A0, A1, A2, A3, A4, A5, };
    const char * names[NUM_PINS] = { "A0", "A1", "A2", "A3", "A4", "A5" };

    void setup()
    {
    //  SerialUSB.begin(115200);
    //  while(!SerialUSB);
    //  SerialUSB.println("Started");
      Bridge.begin();
    //  SerialUSB.println("Bridge is running");
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      // A software timer of 50Hz.
      if(currentMillis - previousMillis >= 20UL)
      {
        previousMillis = currentMillis;

        // The fastest way to turn an integer into text is with itoa.
        // The function itoa takes about 13us.
        // A buffer is used for itoa.
        char buffer[20];

        for(int i=0; i<NUM_PINS; i++)
        {
          int adc = analogRead(pins[i]);
          itoa(adc, buffer, 10);
          Bridge.put(names[i], buffer);
        }

        int freeram = freeRam();
        itoa(freeram, buffer, 10);
        Bridge.put("freeRam", buffer);

        // a counter.
        static int count;
        count++;
        itoa(count, buffer, 10);
    //    unsigned long t1 = micros();
        Bridge.put("counter", buffer);
    //    unsigned long t2 = micros();
    //    SerialUSB.println(t2 - t1);

    //    SerialUSB.println(count);
      }
    }

    int freeRam ()
    {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

And my test webpage is:

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test</title>

    Show JSON data

    Analog Input A0 = ---

    Analog Input A1 = ---

    Analog Input A2 = ---

    Analog Input A3 = ---

    Analog Input A4 = ---

    Analog Input A5 = ---

    freeRam = ---

    counter = ---


body: I am working on a project which requires countdown from 30sec to 0sec. I can't use delay() function because I am taking input from keyboard during countdown. millis() function wont help because my board will be active for more than 50 days. I require something like counter which I can reset after or before completion of 30sec.

title: Arduino Countdown without using delay()

Answers: 1

body:
## Background

The function `millis ()` returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).

See: <http://arduino.cc/en/Reference/Millis>

Example:

    unsigned long startTime = millis ();

Since there are 232 bits in an unsigned long it can count from 0 to 4294967295.

Computing this in terms of days we have:

    2^32 / 1000 / 60 / 60 / 24 = 49.710 days

So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

---

## Is this bad?

No. Is it bad your clock overflows (goes back to zero) at midnight? No it isn't.

Let's clear up some misconceptions:

* The processor does not reset when the timer overflows.
* The timer does not stop.
* Nothing "bad" happens.

All that happens, on a timer overflow, is that it goes back to zero and starts counting up again. Just like your clock does.

---

## How do I time an event?

There are two ways of timing something (eg. a minute from now). You can add or subtract. Because of the way that unsigned arithmetic works, **subtracting** is the correct way.

---

## Example of adding - **not recommended**!

I want to detect a minute in the future...

    unsigned long startTime = millis ();
    unsigned long whenToStop = startTime + 60000;

    ...

    if (millis () >= whenToStop)
      {
      // do something
      }

This will work most of the time, but not when the timer overflows. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

    2^32 - 50000 = 4294917296 (0xFFFF3CB0)

Now we add 60000, and get:

    2^32 - 50000 + 60000 = 10000 (0x2710)

Our "whenToStop" variable has overflowed and is now quite small. And thus it is immediately less than the current time, and our check for when a minute is up fails, it appears to be up immediately.

---

## Example of subtracting - recommended

I want to detect a minute in the future...

    unsigned long startTime = millis ();
    unsigned long interval = 60000;

    ...

    if (millis () - startTime >= interval)
      {
      // do something
      }

This will work **all the time**. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

    2^32 - 50000 = 4294917296 (0xFFFF3CB0)

In 50 seconds the timer wraps around and goes to zero. Subtracting now gives us:

    // millis () - startTime   = elapsed interval
        0        - 4294917296  = 50000 (0xC350)

The subtraction "wrapped around" and gave us a small number. If you use a scientific calculator and try the above you may get a result of `0xFF0000C350`. The initial 0xFF is the "extended sign bit", in effect, however as the field is unsigned, and only four bytes long, the sign bits are dropped, giving a small positive number, not a large negative one.

Demo using the Mac Calculator app:

[![millis() rollover][1]][1]

In 60 seconds the timer goes to 10000. Subtracting now gives us:

    // millis () - startTime   = elapsed interval
        10000    - 4294917296  = 60000 (0xEA60)

So the elapsed interval (the difference) is now 60000, which is what we wanted.

Directly after we set up startTime and millis we will see a sequence like this:

    millis ()   -  startTime    =  difference
                                 (modulo 2^32)
    4294917296     4294917296               0  <-- we start timing here
    4294917297     4294917296               1
    4294917298     4294917296               2
    ...
    4294967295     4294917296           49999  <-- largest unsigned long value
             0     4294917296           50000  <-- wraps here back to zero
             1     4294917296           50001  <-- keeps counting up
    ...
          9999     4294917296           59999
         10000     4294917296           60000  <-- time's up!

---

## Recommended method

*  Use unsigned long (not just long) for "time" variables.
*  Record the start time of some event (eg. a debounce, when you start feeding the fish, etc.)
*  Subtract the start time from the time now, giving a difference.
*  See if the difference exceeds the desired interval.

eg.

    startedFeedingFish = millis ();

    ...

    if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
      {
      // stop feeding the fish
      }

---

## Can't I just reset millis?

You can, but you **don't need to**. Plus it may well throw out any library you are using that does not expect millis to be reset. Plus you have to decide exactly when to do it. It would need to be a time when you aren't using millis. For example if you happened to be feeding the fish in the above example, and your code reset millis, then the fish will get an awful lot of food!

---

## What about micros?

The function `micros()` returns the number of **microseconds** since reset. This also wraps around, however since there are 1000 microseconds to a millisecond it will wrap around faster.

     2^32 / 1000 / 1000 / 60  = 71.58 minutes

<http://arduino.cc/en/Reference/Micros>

However you can use exactly the same technique to keep track of time to the microsecond interval. Be aware that you can't time more than 71.58 minutes this way though.

Also be aware that the resolution of `micros()` is four microseconds (because of the timer prescaler) so you won't ever be able to time a one or two microsecond interval.

---

## Limitations

If you are using millis() you cannot time more than 49.71 days, and if you are using micros() you cannot time more than 71.58 minutes, without extra code to detect the wrap-around. For long intervals I suggest a real-time clock, since that would be more reliable during power failures, or when you replace batteries, etc.

---

## Reference

This answer taken from my page <http://www.gammon.com.au/millis>

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


body:
Below is my code and a picture of the gibberish.  It's different every time.  If i pull out the temp sensor, i still get gibberish, sometimes.  I'm at a loss as to what to even be looking at now. Any ideas?

 [![gibberish][1]][1]

<!-- language: c -->

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    //set capacities
    int keg1_volume = 19;
    int keg2_volume = 19;
    const int temperaturePin = 0;

    void setup() {
      //initial delay
      delay(1000);

      //set contrast
      pinMode(9, OUTPUT);
      analogWrite(9, 100);

      // set up the LCD's number of columns and rows:
      lcd.begin(20, 4);

      // Print header to the LCD
      lcd.setCursor(6, 0);
      lcd.print("BeerView");
      lcd.setCursor(0,1);
      lcd.print("Keg (C)");
      lcd.setCursor(10,1);
      lcd.print("Keg (F)");

      //initialize serial for debugging
      Serial.begin(9600);

      //get voltage and calculate temp
      float voltage, degreesC, degreesF;
      voltage = getVoltage(temperaturePin);
      degreesC = (voltage - 0.5) * 100.0;
      degreesF = degreesC * (9.0/5.0) + 32.0;

      //display temp
      lcd.setCursor(0,2);
      lcd.print(degreesC);
      Serial.println(degreesC);
      lcd.setCursor(10,2);
      lcd.print(degreesF);
      Serial.println(degreesF);

    }

    void loop() {
    }

    float getVoltage(int pin)
    {
      return (analogRead(pin) * 0.004882814);
    }

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

title: Arduino LCD is displaying gibberish, sometimes

Answers: 1

body: Used a pot instead of the PWM from pin 9.  Thanks for the help!!


body:
I'm using a heart rate sensor along with an Arduino for a project of mine. I have to determine whether the heartbeat is following a particular pattern (eg: when when heartbeat regularizes a lot after a period of increased or largely varying, I need to trigger an alarm to show that it has regularized).

Can anyone give me suggestions on how I can go about doing this? Are there any libraries or software for doing basic statistical analysis on data like this?

title: Pattern detection in sensor data

Answers: 1

body:
[This Arduino topic](http://forum.arduino.cc/index.php?topic=43713.0) is an over-simplification and not very robust, but it presents in code the basic principle of threshold detection and the subtraction of adjacent pulse times (period).  BPM = 60.0 / period in seconds.

If you want something that would work under a larger range of conditions, you can add the three primary missing features used by medical instrumentation.

 1. Automated zeroing, which can be accomplished with an analog filter and pull-up or with a digital high pass filter that attenuates frequencies below 0.3 Hz.  This can be done with a series capacitor leading to the analog input being sampled, with a pull up resistor to V+ and another resistor to ground to center the Voltage to an appropriate positive steady state value.
 2. Attenuation of frequencies above those representing a pulse to avoid false triggers from high frequency noise, cross-talk, or transients, which can be accomplished with an analog filter or with a higher sample rate and a digital low pass filter that attenuates frequencies above 100 Hz 1.
 3. [Dynamic range compression](https://en.wikipedia.org/wiki/Dynamic_range_compression), which detects the trend in pulse amplitude and continuously adapts the trigger threshold accordingly to avoid false indication of beats or the missing of weaker but legitimate beats.

To do the filtering digitally, you may want to read up on DSP (digital signal processing).  There are several great books on it, and you can search for simple algorithms for both low pass filters and high pass filters in GitHub or elsewhere in the open source community.

---

[1] [Wikipedia's article on low pass filters](https://en.wikipedia.org/wiki/Low-pass_filter)


body:
I want to construct a constant current hot wire anemometer. For this, resistance is the input of the Arduino. There is a relationship between wire resistance and air velocity.

How can I calculate velocity from wire resistance?

title: How to calculate air velocity from wire resistance?

Answers: 1

body:
Its very simple really, all you need to do is code the equations on this page and then supply some heat and you will be able to do it.  Just remember integer division rounds down :)

http://www-g.eng.cam.ac.uk/whittle/current-research/hph/hot-wire/hot-wire.html