title: How to run functions concurrently

text:
# Question
Title: How to run functions concurrently
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.

# Answer
There is similar questions answered a day ago - Multithreading with Arduino. 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 votes

# Answer
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.
> 0 votes

# Answer
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;
}

```
> 0 votes

# Answer
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*.
> -1 votes

---
Tags: arduino-uno, programming, interrupt
---


# Question
Title: How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data?
I am building a project where I have to store the digital state which is Boolean (either HIGH or LOW) of each I/O port such that after power off the state of I/O ports store in EEPROM and I can retrieve this I/O port's state after power on.

This is my code..

```
    #include <IRremote.h>
    #include <EEPROM.h>
    int EEPROMaddress = 0;
    int EEPROMaddress1 = 1;
    byte EEPROMbyte = EEPROM.read(EEPROMaddress);
    byte EEPROMbyte1 = EEPROM.read(EEPROMaddress1);
    int RECV_PIN = 11;
    int led = 10;//1FE50AF
    int led1 = 9;//1FED827
    boolean previousState = bitRead(EEPROM.read(EEPROMaddress), led);
    boolean previousState1 = bitRead(EEPROM.read(EEPROMaddress1), led1);
    boolean state;
    boolean state1;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      pinMode(10,OUTPUT);
      pinMode(9,OUTPUT);
      irrecv.enableIRIn();
    }
    void loop() {
      if (irrecv.decode(&results))
      {
        Serial.println(results.value, HEX);
        switch(results.value)
        {
           case 0x1FE50AF:
           if (previousState == LOW)
           {state = HIGH;
            digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led,state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);}
           else
           {state=LOW;
           digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led, state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);
           }
           break;
            case 0x1FED827:
           if (previousState1 == LOW)
           {state1=HIGH;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1, state1);
           delay(50);}
           else
           {state1=LOW;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1,state1);
           delay(50);}
           break;
}
        irrecv.resume();
      }
}

```

# Answer
Since this is Arduino SE I'm going to do this with the Arduino functions, there are other ways of course.

Write a bit to EEPROM:

```
byte EEPROMbyte = EEPROM.read(EEPROMaddress);
bitWrite(EEPROMbyte, pinBit, pinState);
EEPROM.update(EEPROMaddress, EEPROMbyte);

```

Read a bit from EEPROM:

```
boolean pinState = bitRead(EEPROM.read(EEPROMaddress), pinBit);

```

This is for updating/reading a single bit at a time as asked. If you need to read/write multiple bits at the same time(as I'd assume you are doing after power on) then it's more efficient(and less wear on the EEPROM in the case of the write) to do all the bits at once instead of one EEPROM read/write per bit.

I assume by "I/O ports" you mean Arduino pins. If you're working directly with the PORT registers(e.g. PORTB) then you can just write or read the whole register to the EEPROM, no need to deal with the individual bits.
> 3 votes

# Answer
Note that writing EEPROM is slow - on the order of milliseconds per write - which may limit the performance of your sketch.

A better technique is to provide a limited backup power supply to the MCU; enough to complete a set of EEPROM writes + a safety margin. A capacitor could possibly provide enough run time if doesn't have to power much else. Then, detect and interrupt on a failure of the main supply, immediately write your backup data to EEPROM, and enter an infinite loop to wait for the backup supply to fail. When the system resets, examine the EEPROM to be sure there is valid backup data there, restore what needs to be restored, and resume your task.

Update:

A search for "arduino backup power" finds a number of articles related to switching an Arduino from mains power to battery power when the mains fails. You would only need a very small battery if you're willing to only save necessary information then shut down until the power returns. A capacitor might keep your MCU running long enough to do that. Designing the circuit depends on too much we don't know about your system, though.

In fact, simply switching a backup battery as some of these articles describe, or better, running on a battery which is kept on a mains charger, may make a much simpler system that can surviVe reasonably long power outages without shutting down. Again, we don't know how often or how long your power goes out, and how reliable your system is required to be.
> 0 votes

# Answer
You can store any bits or bytes into eeprom in byte units. The eeprom itself doesn't care whether the data ISS bits or bytes or multi bytes.

Your code only needs to make sure that consistency is maintained in storying and retrieving of eeprom data.
> 0 votes

---
Tags: memory-usage, eeprom
---


title: Reduce current consumption on ATtiny85

text:
# Question
Title: Reduce current consumption on ATtiny85
I am trying to reduce current consumption on my project. Right now it is using ~1.28mAh, it should be possible to get it much lower (I am using AA batteries as the power source).

The ATtiny85 has its fuses set to run at 1MHZ, with BOD disabled.

I am using this board to mount the CPU. I desoldered the power LED and the regulator, feeding power directly from the batteries to the 5V input.

Nothing was connected to any other pins while measuring, just 5V and GND. The code was running in debug mode, so every 8 seconds it flashed a debug LED. I don't know for how much this could account.

Full code:

```
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

#define DEBUG (true)
#define INT_PIN (0)
#define OUT_PIN (2)
#define LED_PIN (1)

/***************************************************
 *  Name:        ISR(WDT_vect)
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Watchdog Interrupt Service. This
 *               is executed when watchdog timed out.
 *
 ***************************************************/
EMPTY_INTERRUPT(WDT_vect);
EMPTY_INTERRUPT(PCINT0_vect);

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Enters the arduino into sleep mode.
 *
 ***************************************************/
void enterSleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
  sleep_disable(); /* First thing to do is disable sleep. */

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
    for (uint16_t dbg = 0; dbg < 65535; dbg++);
    digitalWrite(LED_PIN, LOW);
  #endif
}

/***************************************************
 *  Name:        setup
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Setup for the serial comms and the
 *                Watch dog timeout.
 *
 ***************************************************/
void setup() {
  pinMode(INT_PIN,INPUT);
  pinMode(OUT_PIN,OUTPUT);
  pinMode(LED_PIN,OUTPUT);
  ADCSRA &= ~_BV(ADEN); // ADC off
  power_all_disable();
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Main application loop.
 *
 ***************************************************/
void loop() {
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(LED_PIN, LOW);
  /*** Setup the WDT ***/
  wdt_reset();
  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   * WDTCR on ATTINY85 / WDTCSR on ATMEGA
   */
  WDTCR |= (1<<WDCE) | (1<<WDE);
  /* set new watchdog timeout prescaler value */
  WDTCR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
  /* Enable the WD interrupt (note no reset). */
  WDTCR |= _BV(WDIE);
  // sleep for 8 seconds x 43200 = 96 hours = 4 days
  for (uint16_t i = 0; i < 43200; i++)
    enterSleep();
  wdt_reset();
  wdt_disable();
  GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT0); // Use PB0 as interrupt pin
  enterSleep();

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
  #else
    digitalWrite(OUT_PIN, HIGH);
  #endif
  enterSleep();
  PCMSK &= ~_BV(PCINT0); // Turn off PB0 as interrupt pin
}

```

# Answer
> 2 votes
Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!

---
Tags: power, attiny, sleep
---


# Question
Title: Servo motors not working when called upon using I2C
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?

# Answer
> 2 votes
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;
     }
}

```

# Answer
> 1 votes
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.

---
Tags: arduino-uno, i2c, servo
---


title: Remote controlled lights

text:
# Question
Title: Remote controlled lights
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.

# Answer
> 0 votes
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 )

---
Tags: wires, remote-control
---


title: ATtiny88 ADC reference voltage setting

text:
# Question
Title: ATtiny88 ADC reference voltage setting
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

# Answer
> 1 votes
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 is

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

```

which overrides reference selections made by just changing ADMUX.

Parameters `INTERNAL` and `DEFAULT` to 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. Also, a forum.arduino.cc thread from late April 2016 has some discussion of reading ADC inputs on tinys; I don't know if it's relevant.

# Answer
> 0 votes
In your setup section, you want to set or clear all relevant bits in admux.

---
Tags: adc, attiny
---


title: Vary the length of square waveform

text:
# Question
Title: Vary the length of square waveform
Here in figure, we can see two waveforms.

Below one is waveform of raw RPM signal. I want to find square waveform which based on that LOW INTERVAL of RPM signal and length must vary according our requirement. So for that purpose, I just made inverter circuit using 74HC14 and Low pass filter(for removing noise).

As a result of that circuit, I got Upper one waveform means square wave signal. Now, you can see it has also one spike beside square wave(I don't want that). And I can't vary length because inverter circuit gives only perfect inverting signal.

Is it possible to make square wave like this and also vary the length of that square wave with help of Arduino?

Here, I want to use Arduino because I have to vary the length of square wave with help of programming. For example, if I want 10ms square wave then just enter value 10 in programming then generate 10ms square waveform. Rising edge must be same. And right now, I have no clue or idea how to do this.

If possible then please give me some suggestion how to do this.

# Answer
The most steightforward decision is to use this spike to trigger interrupt in Arduino. The interrupt procedure starts one of the counters and sets 1 at one of the pins. After N milliseconds by counter or by inner timer the Arduino outputs 0 to the same pin, so you will have needed length of the positive pulse. This will work while pulse length will be less then time between successive spikes. Do not forget to make standard spike amplitude enough to start interrupt, but not too big not to damage Arduino. Of course you can work without interrupts, just testing the input in main cycle, but it will be less presise. You will need a decision, how to conveniently control the pulse length by some tool. It can be infrared pult or some other tool and you must see the set time value, so you will need to use some indicator. May be LCD 1602 keypad shield will be enough for this.
> 1 votes

---
Tags: arduino-uno, programming, arduino-ide
---


# Question
Title: How to run background music while the code for a game is executed
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?

# Answer
> 2 votes
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.

# Answer
> 1 votes
Run the music through a time Interrupt.

---
Tags: arduino-uno, programming, sketch, audio
---


# Question
Title: Serial Getting Garbage Data with real data
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

# Answer
> 2 votes
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.

---
Tags: arduino-uno, serial, visualstudio, c#
---


title: Arduino Countdown without using delay()

text:
# Question
Title: Arduino Countdown without using delay()
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.

# Answer
> 16 votes
## 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:

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

---
Tags: arduino-mega, timers
---


# Question
Title: Replacement crystal on Uno for cold temperatures
I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?

P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost

# Answer
> 1 votes
There is a solution for just this problem, it's a "crystal oven". It is used to keep a crystal at a constant temperature so that the oscillating ferquency remains very stable.

Crystal ovens are usually expensive as they are quite precise and have good insultaion, but here's a kit that you might adapt for your uses: http://www.minikits.com.au/Oscillator-Heater, or google around to see if you find something that might suit you better.

You could also consider making a heater with a simple temperature regulator of your own to keep the crystal warm (many temperature sensors for Arduino are available on the web).

---
Tags: arduino-uno, electronics, system-design, oscillator-clock, components
---


# Question
Title: Arduino time between interrupts in POV led display
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.

# Answer
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`.
> 1 votes

# Answer
The following code was from a rejected suggested edit, by an anonymous user, to the original post. See also Rejected edit results in loss of constructive code modification.

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);

}

```
> 0 votes

---
Tags: led, time
---


# Question
Title: Arduino LCD is displaying gibberish, sometimes
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?

```
// 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);
}

```

# Answer
Used a pot instead of the PWM from pin 9. Thanks for the help!!
> 2 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Endless loop on boot after reflashing ESP-12E with AT firmware
I flashed the ESP-12E from AT firmware 2.0 (running ok) to NodeMCU (running ok). When I reflashed it back to the AT 2.0 it is stuck in endless loop on boot:

```
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2408, room 16
tail 8
chksum 0xe5
load 0x3ffe8000, len 776, room 0
tail 8
chksum 0x84
load 0x3ffe8310, len 632, room 0
tail 8
chksum 0xd8
csum 0xd8

2nd boot version : 1.6
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
no GPIO select!
jump to run user1 @ 1000

rf_cal[0] !=0x05,is 0xFF

```

I am sure I flashed it correctly, it was not my first flashing of AT firmware. Just to be sure:

```
esp_init_data_default.bin -> 0x3fc000
blank.bin -> 0x3fe000
boot_v1.6.bin -> 0x0000
user1.1024.new.2.bin -> 0x1000
blank.bin -> 0x7e000

```

I can even reflash it to the NodeMCU firmware and it works, but reflashing to the AT firmware ends in the same endless loop again.

I suspect the problem is in initialization data, but I'm at my wit's end with it.

# Answer
Full answer and writeup to the comments:

The error message is due to the bootloader trying to read the contents of its radio-frontend calibration data (hence the name `rf_cal`). It compares it with a magic number, `0x05`, but fails because it reads `0xFF` at that point. `0xff` is an indication that you read data from flash which was erased. After erasing a flash-sector, the data in it becomes `0xff 0xff 0xff..`. Hence it seems as if the bootloader is trying to access the data from the wrong address, thus only reading erased flash data. The RF-calibration data is stored in the file `esp_init_data_default.bin` and must be flashed to the correct address in order for the bootloader to be able to read it.

The NodeMCU documentation tells us the needed address for `esp_init_data_default.bin` given the size of the flash of our ESP module:

The bootloader messages

```
2nd boot version : 1.6
SPI Speed      : 40MHz
SPI Mode       : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)

```

indicate that the flashed firmware (or that what is overriden by `esptool.py`) uses the 8 MBit flash size. There should be two ways to fix this:

* Put `esp_init_data_default.bin` to the address the 8Mbit (1 MByte) bootloader expects, which is `0xfc000`
* Force the usage of the 32 MBit (4 MByte) Flash map by giving `esptool.py` the parameter `--flash_size 32m`. This makes `esptool.py` overwrite a few bytes in the firmware (at `0x000000`) to adapt the firmware.

By your comments, method one worked. If there are problems however with the flash or the firmware, consider also trying method 2.
> 7 votes

---
Tags: esp8266
---


title: PWM doesn't work with my sketch

text:
# Question
Title: PWM doesn't work with my sketch
I have a weird problem. again. This time it's the PWM. I have used PWM before and I used to work the way I am doing it now. But now it just wont work. The `Fading` sketch from example works. When I compile a code with the similar code it doesn't work. Everything with respect to compilation is same.

The code that works:

```
int ledPin = 3;    // LED connected to digital pin 9

void setup() {
  // nothing happens in setup
}

void loop() {
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
  for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
}

```

The code that doesn't work.

```
#define FAN1 3
#define FAN2 5

void setup() {
  //EMPTY
}

void loop() {
  int speed1 = 25;
  int speed2 = 127;
  analogWrite(5, speed1);
  analogWrite(3, speed2);
  delay(10000);
}

```

Why doesn't the second code work?

**EDIT 1:**

By not working I meant **No output** on *Second Code* and **Expected Output** on *First one*. Currently I'm using `ISIS` for simulation and `Oscilloscope` to view the output along with a `L239D` with motors attached.

In the first code the motor starts and stops as expected, with the expected PWM Waveform.

In second code, nothing. No waveform, no motor movement.

# Answer
One omission from your code which might be causing the problems is the fact that you haven't set the pinMode. You need to set the pins as OUTPUT in setup()

```
#efine FAN1 3
#define FAN2 5

void setup() {
    pinMode(FAN1, OUTPUT);
    pinMode(FAN2, OUTPUT);
}

void loop() {
  int speed1 = 127;
  int speed2 = 25;
  analogWrite(FAN1, speed1);
  analogWrite(FAN2, speed2);
  delay(10000);
}

```

I am curious to know why you declared FAN1 and FAN2, but didn't use them - I'd recommend changing the analogWrite statements to use them instead of referring to the pin numbers directly.

Also, the way you're using the pin and speed means that you're using speed2 for FAN1 and vice versa, I've switched these in my example so FAN1 and speed1 go together.
> 3 votes

---
Tags: arduino-uno, pwm, analogwrite
---


# Question
Title: How to on/off light dimmer using another pin?
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)
  }
}

```

# Answer
> 3 votes
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;
  }
}

```

# Answer
> 0 votes
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.)

---
Tags: arduino-uno, programming, arduino-ide
---


title: How To Read Serial Data With NodeMCU

text:
# Question
Title: How To Read Serial Data With NodeMCU
I am trying to change leds status via serial port screen. Here is my code but it's not reading anything from serial port screen. I got leds on D1 and D2 pins.

```
void setup() {
pinMode(5,OUTPUT);
pinMode(4,OUTPUT);
Serial.begin(115200);

}

void loop() {
// put your main code here, to run repeatedly:
int point = Serial.read();
 if(point == 1)
{
digitalWrite(5,!5);
}
else if(point == 2)
{
 digitalWrite(4,!4);
}

}

```

# Answer
> 1 votes
Your code isn't doing what you expect because of a few issues. As echo\_salik says you are only ever turning off the output pins. If you want to toggle the values then its probably easiest to store the value in a bool and use that to control the LED.

I think - and I may be wrong - that you are pressing the one and two keys and expecting that to work. When you press the 1 key `Serial.read()` will return 49 and 2 will return 50. These are the ASCII values for the keys you are pressing.

Its advisable to test to see if there is any data available to read on the serial port. `read()` will return -1 if there is no data.

```
void loop()
{
  if (Serial.available())
  {
    int point = Serial.read();
    switch (point)
    {
      case 1:
        digitalWrite(5,HIGH); // Not !5 use High and Low
        break;
      case 2:
        digitalWrite(4,HIGH);
        break;
      case 3:
        digitalWrite(5,LOW); // Not !5 use High and Low
        break;
      case 4:
        digitalWrite(5,LOW); // Not !5 use High and Low
        break;
    }  // End of switch
  }  // End of if
  delay(50);  // I have no idea why, but most programs of this sort have a delay in.  (Hope someone explains to me too)
}  // End of function

```

(A switch statement is a more efficient way of doing a number of if elses)

One thing you might want to consider is the values you are checking against. `Serial.read()` is returning a value between -1 and 255. It is not returning the key you pressed. If you want to change it to work with keys then you can do it by changing the case statements that are checking integers `case 1:` to ones that are checking characters i.e. `case '1':`.

---
Tags: serial, nodemcu
---


# Question
Title: Arduino with 12 bit DAC (MCP4725) Not Working
I have an Arduino Mega AT2560 and need to have real DAC. I purchased the Sparkfun 12 bit DAC, however I don't think it is working properly.

I am using the Arduino wire library to communicate with the DAC. When I write 0, I am expecting to see 0v from the DAC's OUT pin. However, I see some seemingly random constant voltage. In reverse, when I write 4095 to the DAC I see the same voltage as when I write 0. I expected to see 5v.

1. Can someone verify that I hooked it up correctly?
2. Can someone verify the code I am using?

```
#include <stdint.h>
#include <stdio.h>
#include <Wire.h>

#define MCP4725_ADDR 0x60 // [0000 0110]
/*
* 12 Bit DAC MCP4725 gives a range of 4096 possible values.
*
*/
void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MCP4725_ADDR);
  Wire.write(64);            // cmd to update the DAC [0100 0000]
  Wire.write(4095 >> 4);        // the 8 most significant bits...
  Wire.write((4095 & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();
}

```

# Answer
> 1 votes
Sorry I'm late -- I realize this question was asked 8 months ago, but it doesn't look like you fixed it, and I figure others can always benefit (or you might even, if you still want to try).

Your code looks correct (I compared it to the Sparkfun example, and also to the datasheet for the MPC4725).

However, it does look like you're using the wrong address for the part. (The actual value for the address is not given in the Sparkfun example -- at least, I couldn't find it).

Your line:

```
#define MCP4725_ADDR 0x60 // [0000 0110]

```

is wrong in two places:

1) 0x60 is 0110 0000, not 0000 0110

2) According to the datasheet (section 7.2), the address should begin with the device code %1100, and then the address gets appended. So assuming an address of A2 = 0, A1 = 0, and A0 = 0 (default), the value for MCP4725\_ADDR looks like it should be 0xC0 or %1100 000x. If you soldered the address line to Vcc instead of ground, the address should be 0xC2 or %1100 001x.

The x in the address line represents the read/write bit. If you're trying to command the DAC, it should not be asserted, so the addresses above are correct. If you're trying to read the current value, it should be asserted, which makes your address 0xC1 or 0xC3.

If you have the address wrong, even though the rest is correct, the part will ignore it, so that's probably the issue you're seeing.

Hope this helps someone!

# Answer
> 1 votes
1. you want to make sure that there are pull-ups on the SCL/SDA lines;
2. you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.

---
Tags: atmega2560, digital-analog-conversion
---


# Question
Title: How to calculate air velocity from wire resistance?
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?

# Answer
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
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How can I concatenate multiple byte Arrays into one Array
I have three byte arrays. I first change their values during runtime and after that I want to combine them into one bigger 4th array.

```
byte a1[] = { 0x01, 0x00, 0x01 };
byte a2[] = { 0x00, 0x11, 0x01 };
byte a3[] = { 0x11, 0x00, 0x01 };

byte c1[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

```

I first tried this, but it did not compile.

```
c1 = a1 + a2 + a3;

```

I also tried `strcat()` and I did got a error.

# Answer
> 6 votes
You can concatenate with `memcpy`. You just need to set the pointer at the right place inside the `c1` array.

```
memcpy(c1, a1, sizeof(a1));
memcpy(c1+sizeof(a1), a2, sizeof(a2));
memcpy(c1+sizeof(a1)+sizeof(a2), a3, sizeof(a3));

```

# Answer
> 1 votes
You can do it like this

```
byte c1[] = {0x01, 0x00, 0x01, 0x00, 0x11, 0x01,0x11, 0x00, 0x01 };
byte *a1 = c1;
byte *a2 = c1+3;
byte *a3 = c1+6;

```

Note that This does not make a copy byt you can access the C1 and a1 a2 and a3 as you liked.

# Answer
> 0 votes
```
byte *src;
byte *tgt;
tgt=c1;
src=a1;
for (int i=0;i<3;i++) *(tgt++)=*(src++);
src=a2;
for (int i=0;i<3;i++) *(tgt++)=*(src++);
src=a3;
for (int i=0;i<3;i++) *(tgt++)=*(src++);

```

---
Tags: c++, c, array
---


# Question
Title: How can I switch a 1.5V buzzer with my Arduino?
I want to make my alarm clock “smart”. I'm very new to this stuff, that is, the hardware side. The programming shouldn't present too many problems.

I’m currently experimenting with a simulator (http://circuits.io) and want to start with controlling the alarm’s buzzer with my Arduino.

I did some reading on transistors and this is what I came up with:

I’ve turned pin D3 to high and hooked it up to the base of a NPN transistor. I’m trying to run 1.5V through the transistor, but nothing happens. Any thoughts?

# Answer
> 3 votes
You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.

---
Tags: hardware, transistor
---


# Question
Title: Problem to convert rotary encoder output to angle
I'm using this incremental rotary encoder with a rotating disc.

Here is my system:

I will explain the system briefly and above is the illustration for that:

The rotary encoder(blue) is attached/fixed to a larger disc(yellow) concentrically at its origin, so both the encoder and the disc rotate together the same angle. The disc is rotating on a fixed plane(gray). The plane has a fixed point mark(red X) on its surface. There is also a fixed red arrow on the disc.

Each time before the system is powered, I will manually rotate the disc such that its red arrow will be aligned to the red X mark on the surface. This adjustment each time at the beginning will provide the reference point.

After this adjustment I want to output the actual angles via Arduino.

I tried the following example code from Arduino website:

```
#define encoder0PinA  2
#define encoder0PinB  4

volatile unsigned int encoder0Pos = 0;

void setup() {

  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor

  attachInterrupt(0, doEncoder, CHANGE);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");                // a personal quirk

}

void loop(){
// do some stuff here - the joy of interrupts is that they take care of themselves
}

void doEncoder() {
  /* If pinA and pinB are both high or both low, it is spinning
   * forward. If they're different, it's going backward.
   *
   * For more information on speeding up this process, see
   * [Reference/PortManipulation], specifically the PIND register.
   */
  if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos++;
  } else {
    encoder0Pos--;
  }

  Serial.println (encoder0Pos, DEC);
}

/* See this expanded function to get a better understanding of the
 * meanings of the four possible (pinA, pinB) value pairs:
 */
void doEncoder_Expanded(){
  if (digitalRead(encoder0PinA) == HIGH) {   // found a low-to-high on channel A
    if (digitalRead(encoder0PinB) == LOW) {  // check channel B to see which way
                                             // encoder is turning
      encoder0Pos = encoder0Pos - 1;         // CCW
    }
    else {
      encoder0Pos = encoder0Pos + 1;         // CW
    }
  }
  else                                        // found a high-to-low on channel A
  {
    if (digitalRead(encoder0PinB) == LOW) {   // check channel B to see which way
                                              // encoder is turning
      encoder0Pos = encoder0Pos + 1;          // CW
    }
    else {
      encoder0Pos = encoder0Pos - 1;          // CCW
    }

  }
  Serial.println (encoder0Pos, DEC);          // debug - remember to comment out
                                              // before final program run
  // you don't want serial slowing down your program if not needed
}

```

But this code increases one count for each encoder tick at CW direction, and decreases one count for each tick at CCW direction. It keeps increasing from zero to 65535 in CW and decrease from 65535 to 0 in CCW. I want to translate this code such that I can output the angle in degrees.

My encoder says its ppr is 15 and 30 ticks. This code increase/decrease one count for each tick.

Any idea how to extract the angle from this setup? (It doesn't have to use the specific code I provided.)

# Answer
Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:

```
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos += 24;
} else {
    encoder0Pos -= 24;
}
encoder0Pos = encoder0Pos % 360;

```

BUT... the code you posted has some problems.

1. "The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
2. You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
3. You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.

This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.

```
#include <Bounce2.h>

#define encoder0PinA  2
#define encoder0PinB  4
#define STEP_SIZE 12

byte encoder0Pos = 0;

Bounce debouncerA = Bounce();
Bounce debouncerB = Bounce();

void setup()
{
    debouncerA.attach(encoder0PinA, INPUT_PULLUP);
    debouncerA.interval(5); // interval in ms
    debouncerB.attach(encoder0PinB, INPUT_PULLUP);
    debouncerB.interval(5); // interval in ms

    Serial.begin (9600);
    Serial.println("start");                // a personal quirk

}

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }

    if (EncVariation != 0)
    {
        encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

        Serial.println (encoder0Pos, DEC);
    }
}

```

Disclaimer: I haven't tested this, but I'm pretty confident this will work.

I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See here for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)
> 1 votes

# Answer
As noted in a comment, treating the numbers modulo 360° will put results into the range you want.

Note, however, that you can (and should) avoid use of `long` arithmetic by taking the pulse count modulo 30 *before* multiplying by 12°.

To compensate for the reference point adjustment, have the program set your tick count to correspond to 0° when the arrows align. If you set the base count to some value that's a multiple of 30, say 120, and store it in an unsigned byte, the code would look like so:

```
angle = 12*(count%30);

```

Since the base count 120 is a multiple of 30, it falls out automatically when the modulus is taken. To make this work in the long run, you would set the encoder count to 120 whenever the arrows align (or to `(current%30)+120` if required to adjust it at other times).

If your base count were 0 instead of 120 and the count an unsigned integer instead of a byte, when the rotor goes CCW the modulus counts would have 15 extra counts. For example, a count of 0 correctly converts to 0°, but a count of 65535 is 15 modulo 30, so converts to 180° instead of 348°.

Note, there is no need to debounce rotary encoder inputs if a proper state machine is used; and debouncing slows processing to the point that ticks will be lost. See my answer to question 32572 which includes code for reading several encoders active at once.
> 1 votes

---
Tags: rotary-encoder
---