# Question
Title: Particle Spark (Arduino) How to flash 2 LED sequences at the same time?
I can't find any information that relates to my problem. The few things I did find confused me (I'm quite new to this).

I'm trying to flash 2 sequences of 4 lights at the same time. I can get 1 set flashing but I don't know how to run other sequences at the same time. My probably laughable attempt at the code is below:

```
int led1 = D0;
int led2 = D1;
int led3 = D2;
int led4 = D3;
int led5 = D4;
int led6 = D5;
int led7 = D6;
int led8 = D7;

void setup() {
  setupPart1();
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  setupPart2();
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  pinMode(led8, OUTPUT);
}

void loop() {
  loopPart1();
  digitalWrite(led1, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led2, LOW);
  digitalWrite(led3, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led3, LOW);
  digitalWrite(led4, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led4, LOW);
  loopPart2();
  digitalWrite(led5, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led5, LOW);
  digitalWrite(led6, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led6, LOW);
  digitalWrite(led7, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led7, LOW);
  digitalWrite(led8, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led8, LOW);
}

```

# Answer
> 1 votes
I cover this exact question in my web page: http://www.gammon.com.au/blink

Example code that blinks two LEDs at different rates:

```
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop

```

# Answer
> 1 votes
This kind of problem (doing several things in parallel) is frequent enough to merit a more elegant solution. While projects like this are excellent (Tasks: A Time-Triggered Scheduler for Arduino), I can't get it working.

I wrote this minimal self-contained example of how to do two things simultaneously. It will blink the built-in LED and write "\*" to the serial monitor:

```
--- Task Scheduler ---
Runtime in SS:MMMM
10:9 **********
110:64 **********
210:89 ***

```

This is the sketch. Study it and adapt it to your own problem:

```
/*
 * Task Scheduler for Arduino/ESP2866 by Look Alterno - 2017/8/9.0
 * Show how to execute tasks at regular intervals without using delay() or interrupts.
 * For educational purposes only; not production ready.
 *
 * This sketch have two example tasks running:
 * - Task 1 blinks the builtin led every second
 * - Task 2 write lines with run time and one "*" every ten seconds in the Serial Monitor.
 * Tasks are run in sequence, so keep them short.
 * No interrupts are used; you have to call runTasks() in each loop() pass.
 */

// Definition: Every task must receive nothing and return nothing.
typedef void (*fcnptr)();
//  Here we must declare our task functions (required by C)
void fcnBlink();      // Task 1
void fcnSerial();     // Task 2
//  Add more tasks here.

//  The interval between fcnBlink execution. Adjustable between 25 to 250 ms.
//  LED still will blink every second at the same freq (250ms on, 750ms off).
#define BLINK_LEN 25

//  The task list
struct {
    uint8_t  runnable;  // The task is runnable (true/false).
    uint32_t start;     // Next start time for the task (ms).
    uint32_t interval;  // Execution interval in ms.
    fcnptr fcn;          // Function to execute.
} taskList[] = {
    {true, 0, BLINK_LEN,fcnBlink}, // Execute fcnBlink every 25 ms, blink LED every second
    {true, 0, 10000,    fcnSerial} // Execute fcnSerial every 10 seconds.
    // Here you can add other tasks.
};
// The number of task in our task list.
const uint8_t nTasks = sizeof(taskList) / sizeof(taskList[0]);

void setup() {
  // Just a standard setup. Nothing is required for task execution.
  Serial.begin(9600);
  while(!Serial) {};
  randomSeed(analogRead(A0));
  Serial.println("");
  Serial.println("--- Task Scheduler ---");
  Serial.println("Runtime in SS:MMMM");
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  // Here you write your processing code (without using delay())
  // --- Start of your code.
  // Some random delays to simulate work
  // Just a bit less than half fcnBlink interval length.
  // You can change BLINK_LEN to test other scenarios.

  delay(random(1, BLINK_LEN / 2));

  // --- End of your code
  runTasks();  // At the end of the loop(), but can be anywhere.
}

/*
 * Check the task list and execute them.
 * Sequence of execution guaranteed: tasks could be delayed,
 * but not omitted or executed of order.
 */
void runTasks() {
  uint32_t now = millis();
  for(uint8_t i=0; i < nTasks; i++) {
    if(taskList[i].runnable) {
      uint32_t diff = now - taskList[i].start; // ms since last execution.
      if(diff >= taskList[i].interval) {
        taskList[i].start = now; // Have to be the same for all task, to keep sync.
        taskList[i].fcn();
      }
    }
  }
}

/*
 * Blink the led.
 */
void fcnBlink() {
  // Called every 25 milliseconds. Turn on the led in the
  // 10 first passes and turn off in the next 30.
  static uint8_t count = 0;
  count++;
  if(count <= 250 / BLINK_LEN) {
    digitalWrite(LED_BUILTIN, HIGH);
  } else {
    digitalWrite(LED_BUILTIN, LOW);
    if(count == 1000 / BLINK_LEN) {
      count = 0;
    }
  }
}

/*
 * Print run time (s) and a row of ten "*"
 */
void fcnSerial() {
  static uint8_t count = 0;
  count++;
  // Print run time in seconds:miliseconds at the start of each line
  if (count == 1) {
    uint32_t now = millis();
    Serial.print(now/1000);
    Serial.print(":");
    Serial.print(now%1000);
    Serial.print(" ");
  }
  Serial.print("*");
  if(count == 10) {
    Serial.println();
    count = 0;
  }
}

```

---
Tags: led
---


# Question
Title: How to vibrate Adafruit Feather 32u4 Bluefruit LE device?
I have 11 Adafruit Feather 32u4 Bluefruit LE devices. I want to vibrate my devices using a signal through an app. Is there any signal (Code from app like 0x56-NeoPixel checking, 0x43-clear color) or any sketch? Please provide me.

# Answer
> 3 votes
The Adafruit Feather you are talking about is a small format Arduino compatible with BlueTooth Low Energy, USB and battery connector. It doesn't have any way to vibrate without adding external hardware.

Now, having Bluetooth in the package means that it can comunicate with an Android Phone, and can send/receive commands, post results, anything you need.

We don't provide sketchs for particular projects. You must learn how to program Arduino and Android. Follow the examples and tutorials widely available in the Web.

---
Tags: arduino-uno, arduino-mega, sketch, adafruit
---


# Question
Title: Breaking out of while loop using IR remote input
I'm trying to control a series of LEDs using an IR remote. I have a problem when I try to play a sequence with the LEDs where they all light up in a line and turn off accordingly. I loop through the sequence and I am trying to make it so the instant I press a button on the remote it breaks out of that sequence. The issue lies in the Flash(); function, I think. What can I do?

```
#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

int recvPin = 11;
IRrecv irrecv(recvPin);
decode_results results;

#define BUTTON_ON 0xF076C13B    // codes for different buttons on the remote
#define BUTTON_OFF 0xFF9186B7
#define BUTTON_R 0xE5CFBD7F
#define BUTTON_G 0x8C22657B
#define BUTTON_B 0x2A89195F
#define BUTTON_FLASH 0x35A9425F

int rLED = 5;
int gLED = 4;
int bLED = 3;
int stR = LOW;  // intital state of red LED
int stG = LOW;  // intital state of green LED
int stB = LOW;  // initial state of blue LED
int flash = false;

void setup() {
  Serial.begin(9600);   // Status message will be sent to PC at 9600 baud
  pinMode(rLED, OUTPUT);
  pinMode(gLED, OUTPUT);
  pinMode(bLED, OUTPUT);

  irrecv.enableIRIn();
}

void Flash() {    // flashing function
  while (flash == false) {
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, LOW);
    digitalWrite(bLED, LOW);
    digitalWrite(rLED, HIGH);
    delay(75);
    digitalWrite(gLED, HIGH);
    delay(75);
    digitalWrite(bLED, HIGH);
    delay(75);
    digitalWrite(rLED, LOW);
    delay(75);
    digitalWrite(gLED, LOW);
    delay(75);
    digitalWrite(bLED, LOW);
    delay(75);
    stR = LOW;
    stG = LOW;
    stB = LOW;
    if (results.value == BUTTON_OFF)    // attempting to make it so when i press the OFF button on the remote,
    {                                   // the loop breaks/stops and I can go back to pressing any button on
      break;                            // the remote
    }
  }
}

void loop() {
  if (irrecv.decode(&results))
  {
    if (results.value == BUTTON_ON)
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, HIGH);
      digitalWrite(bLED, HIGH);
      stR = HIGH;
      stG = HIGH;
      stB = HIGH;
    }
    if (results.value == BUTTON_OFF)
    {
      digitalWrite(rLED, LOW);
      digitalWrite(gLED, LOW);
      digitalWrite(bLED, LOW);
      stR = LOW;
      stG = LOW;
      stB = LOW;
    }
    if (results.value == BUTTON_R)
    {
      digitalWrite(rLED, !stR);
      stR = !stR;
    }
    if (results.value == BUTTON_G)
    {
      digitalWrite(gLED, !stG);
      stG = !stG;
    }
    if (results.value == BUTTON_B)
    {
      digitalWrite(bLED, !stB);
      stB = !stB;
    }
    if (results.value == BUTTON_FLASH)
    {
      Flash();    // calling flash func
    }
    irrecv.resume();
  }
}

```

# Answer
Replace delay with millis in `Flash()`.

You do this by making every delay it's own state and give each state a number. Then inside `flash` you check which state you are in to set the LEDs and how long you have been in it to trigger the next state.

```
boolean flashing = false;
int flashingState = -1;
long nextFlashingState = 0;

void Flash() {    // flashing function
  if(!flashing ){
    flashingState =-1;
    return;
  }

  long ms = millis();
  switch(flashingState ){
  case -1:
    flashingState =0;
    nextflashingState = ms+75; //init "timer"
    //fallthrough
  case 0:
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, LOW);
    digitalWrite(bLED, LOW);
    digitalWrite(rLED, HIGH);
    if(nextflashingState < ms){
        flashingState =1;
        nextflashingState +=75;
    }
    break;
 case 1:
    digitalWrite(gLED, HIGH);
    if(nextflashingState < ms){
        flashingState = 2;
        nextflashingState +=75;
    }
    break;
 case 2:
    digitalWrite(bLED, HIGH);
    if(nextflashingState < ms){
        flashingState = 3;
        nextflashingState +=75;
    }
    break;
  case 3:
    digitalWrite(rLED, LOW);
    if(nextflashingState < ms){
        flashingState = 4;
        nextflashingState +=75;
    }
    break;
  case 4:
    digitalWrite(gLED, LOW);
    if(nextflashingState < ms){
        flashingState = 5;
        nextflashingState +=75;
    }
    break;
  case 5:
    digitalWrite(bLED, LOW);
    if(nextflashingState < ms){
        flashingState = 0;
        nextflashingState +=75;
    }
    break;
  }
}

```

I used state `-1` as the init state to start the timer, the case block will fall through to the next case. The `millis()` function returns the number of milliseconds since the arduino booted up (it overflows every ~1.5 months). So when I start a timer I set the the `nextFlashingState` to the time when it should start the next state.

Then in loop you call it every time.

```
void loop() {
  if (irrecv.decode(&results))
  {
    if (results.value == BUTTON_ON)
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, HIGH);
      digitalWrite(bLED, HIGH);
      stR = HIGH;
      stG = HIGH;
      stB = HIGH;
    }
    if (results.value == BUTTON_OFF)
    {
        flashing =false;
      digitalWrite(rLED, LOW);
      digitalWrite(gLED, LOW);
      digitalWrite(bLED, LOW);
      stR = LOW;
      stG = LOW;
      stB = LOW;
    }
    if (results.value == BUTTON_R)
    {
      digitalWrite(rLED, !stR);
      stR = !stR;
    }
    if (results.value == BUTTON_G)
    {
      digitalWrite(gLED, !stG);
      stG = !stG;
    }
    if (results.value == BUTTON_B)
    {
      digitalWrite(bLED, !stB);
      stB = !stB;
    }
    if (results.value == BUTTON_FLASH)
    {
        flashing =true;
    }
    irrecv.resume();
  }

  Flash();
}

```
> 2 votes

---
Tags: arduino-uno, led, ir
---


# Question
Title: Data from RC522 to firebase real time database
```
#include<ESP8266WiFi.h>
#include<SPI.h>
#include "MFRC522.h"
#define RST_PIN D3
#define SS_PIN D4
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }

  Serial.print(F("Card UID: "));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for ( byte i = 0; i< bufferSize; i++ ) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

```

I am able to get the unique ID of the RFID tag & card. But now the problem is that how can I send the unique ID from ESP8266 to the firebase realtime database.

The hexadecimal values that are generated are they unique? or they are something else? Because in some youtube videos I saw people using only numbers as a unique ID from RFID to distinguish between 2 cards or tags.

The wifi connection and firebase auth all are set peoperly ony the unique id number is the problem.

# Answer
The "UID" of the card is supposed to be unique. Most RFID chips also have blocks of readable/writable space, but some systems do only use the UID from the chip as the complete identifier.

It may be that you come across RFID chips that have utilized random bytes as the UID, in which case there is a chance of duplication. Depending on the number of possible cards to be used in your system, this may or may not be a big worry for you. If it is a big worry, you may want to use the actual memory on the RFID chips to store your user's ID data.

Regarding HEX versus numbers -- Hexadecimal is just one way to represent numbers. Your code:

```
Serial.print(buffer[i], HEX);

```

tells the print command to take the byte at `buffer[i]` and print its value in Hexadecimal format. You could replace `HEX` by `DEC` to see the base-10 (decimal) value instead. The actual bits underneath would be the same -- it's just one way to display/represent the underlying number.

One byte (8 bits) of data can be represented in decimal as the numbers 0 through 255. The same byte can be represented in Hexadecimal as 0x00 through 0xFF. ('0x' is one way to denote that what follows are hexadecimal values.) Each 'digit' in hex represents 4 bits of data (0-15 in decimal), so 2 hex digits can represent 16^2 values (256 decimal), hence 0-255 as the 1-byte range of decimal values.

(That explanation assumes un-signed types.)
> 0 votes

---
Tags: esp8266
---


# Question
Title: Arduino Uno and ESP01: can't issue AT commands [Solved]
I would like to connect an Arduino Uno and an ESP 01 module. I use the Arduino IDE and I tried to test communication via serial monitor. I get the "ready" message from the ESP 01, but I am not able to issue AT commands from the serial monitor. It only displays random characters on the console.

It seems that no newline character is issued, because if I try to insert commands, they are inserted next to previous characters. I use "Both NL & CR" and 115200 baud settings in Arduino IDE. I tried 9600 baud too, but then the text is unreadable.

I used the following pins on my ESP-01:

```
Vcc -> 3,3V
Gnd -> Gnd
Rx  -> Tx(pin 0) of my Arduino, used voltage divider to make it 3.3V.
Tx  -> Rx(pin 1) of Arduino
CH_PD -> 3.3V

```

Please see serial monitor screenshot:

**EDIT: PROBLEM RESOLVED:**

My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

# Answer
> 1 votes
Just to have an answer instead of just an edit/addition to the question:

> EDIT: PROBLEM RESOLVED:
>
> My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Ok... sure... your Uno's Atmega384 was talking with pins 0 and 1 to the USB adaper chip (Atmega16u2 on Uno R3) and at the same time to the ESP-01.

Read the fine schematic: Arduino Uno R3

# Answer
> 0 votes
It could be the case, that the **Arduino power supply is insufficient**.

"\[...\] note that the Arduino 3.3V regulated output (50 mA max) can't drive the current requested by the ESP (Up to 200 mA). Some tutorials on the Internet use the Arduino 3.3V to power the ESP, but it didn't worked for me. I'm using an external power supply (An old 5V Android charger)."Source

*Possible*, that the power consumption was within range when the readable text was printed and too high when all the unreadable stuff was sent.

---
Tags: arduino-uno, esp8266
---


# Question
Title: How to make two small micros communicate with my Arduino over BLE?
I want to do a project with an Arduino Uno and two other BLE (or regular bluetooth) capable modules. I want the Bluetooth modules to be hooked up to buttons (one button for each Bluetooth module). I then want the Bluetooth-capable modules to send the state of their buttons to a central Arduino board.

Is this possible? Can I have two different BLE boards connected to one Arduino?

I have a RedBear BLE (Bluetooth low energy) shield for my Arduino. What micro-controllers should I get for the peripheral modules? And where can I learn about pairing Bluetooth modules? Everything I read seems to be about pairing Bluetooth boards to a phone.

Can I do this all with BLE or am I going to need to get a new shield for my Arduino to talk with the two peripheral boards?

Thanks.

# Answer
You can use SoftwareSerial to communicate with two modules from an uno. But You will have to wire 'em up separately, not through your shield. (making the total number of bluetooth modules 4.

You could also use your existing sheild and poll between the two remotes. I.e. disconnecting from one and connecting to the other at a regular interval.

For the micros and bluetooth for your button, you could use a HM10 with an ATtiny like in this instructable. He uses two HM10 modules to talk to each other. HM-10 is a popular BLE module. If you want regular bluetooth(2.0), you can use HC-05.
> 0 votes

# Answer
The page for the RedBear BLE shield that you note indicates that the BLE chip is the nRF8001, which it says supports peripheral (slave) role only. This means it must be connected to from a BLE Central role device.

Since you want your Uno to be the central device, listening for data from these 2 remote buttons, your RedBear shield won't work this way.

A short overview of BLE is available by AdaFruit.
> 0 votes

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Why does the RCSwitch.available return false?
I am trying to use this example code from the RCSwitch library:

```
/*
  Simple example for receiving

  https://github.com/sui77/rc-switch
*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    Serial.print("Is avail");
    int value = mySwitch.getReceivedValue();

    if (value == 0) {
      Serial.print("Unknown encoding");
    } else {
      Serial.print("Received ");
      Serial.print( mySwitch.getReceivedValue() );
      Serial.print(" / ");
      Serial.print( mySwitch.getReceivedBitlength() );
      Serial.print("bit ");
      Serial.print("Protocol: ");
      Serial.println( mySwitch.getReceivedProtocol() );
    }

    mySwitch.resetAvailable();
  }
}

```

It seems like the mySwitch.available() is returning false, but since there seems to be no documentation for the library I don't know what it means.

So why is that?

I am trying to use this code on a A-Star 32U4 Micro, which supports Arduino code.

# Answer
> 1 votes
I think that the value of available just determine if there is a message to receive or not.

# Answer
> 0 votes
Your code is OK. It seems that the transmitter's remote control frequency is different from the receiver. Both transmitters and receivers must have the same frequency. 433MHZ - TX with 433MHZ - RX 315MHZ - TX with 315MHZ - RX

---
Tags: library
---


# Question
Title: Bluetooth HM-10 in central mode bonding with another bluetooth device
I have a bluetooth HM-10 configured in central mode. I have successfully connected it to another bluetooth device (a hexiwear bluetooth wearable). The problem now is that the hexiwear requires me to provide a 6 digit pin before it will bond with my HM-10.

Would anyone know the AT command that I could use to send the 6 digit pin from the HM-10 to the hexiwear?

Thank you.

# Answer
> 1 votes
The manual for the HM-10 can be found here.

Page 11 has the AT command you are interested in: `AT+PIN`:

```
AT+PIN123456
OK+Set:123456

```

By default the PIN is `000000`.

(The manual is quite vague about the role of that command, so I assume since it is the only reference to PIN codes that it does what you require).

---
Tags: bluetooth
---


# Question
Title: Known conflicts between use of HC-12 and Ethernet Shield on Mega2560?
I have two somewhat similar sketches that use both HC-12 \[for data collection\] and a W5100-type Ethernet Shield \[for Email construction and transmit\]. Both sketches run fine until the code for the Ethernet Shield is invoked, which creates a connection and successfully transmits an Email. Once this happens, the HC-12 no longer receives transmits. No exceptions are raised, and I am at a loss to determine the cause of the problem. \[The HC-12 is using pins 50-52.\]

I have other sketches that use either the HC-12 or the Ethernet Shield, and they work fine. Before I build a custom sketch to attempt problem isolation, I thought I would simply ask the question of whether known conflicts exist. I know that many questions are resolved by posting the sketch and someone other than the author scanning it. I think that impractical in this particular case. The sketch comprises 6,000+ lines of code.

If no helpful responses are forthcoming, I will continue with problem isolation, and post again if no success is achieved.

# Answer
> 0 votes
As suggested by Majenko, the problem results from using Software Serial for the HC-12, and unfortunately choosing the pin set 50-52, which conflicts with the pin usage specification for the Ethercard Library. Hence, the HC-12 code works fine until usage of the Ethernet shield is finally activated. From that point on, the Ethernet code functions properly, whilst the HC-12 code does not. The recommended solution, which does indeed solve the problem, is to abandon usage of SoftwareSerial for the HC-12, and use Serial1, or Serial2, or Serial3 instead.

I do not feel that the solution to the problem is truly mine, but post it only that the information may be of subsequent use to a user encountering a problem of similar nature.

---
Tags: arduino-mega, ethernet-shield, hc-12
---


# Question
Title: Using Multiple identical sensors - Beginner
I'm trying to make an interactive installation where I have 6 pressure pads that each control an Air Fan. The pressure sensors ideally will be on chairs.

I would like the changes in pressure to change the speed of the Air Fans.

What is the easiest way for me to do this? Can I do it with just an Arduino?

I haven't bought anything yet as I'm assessing what the best route is.

# Answer
> 0 votes
Yes one Arduino have enough in and out-put to make your project fly.

The sensor that would detect pressure sensor is called "Force Sensitive Resistor".

Example: http://www.ladyada.net/make/midisense/forcesensors.html

They need some amplifier circuitry that could adapt the sensors low output signal to an Arduino analog input.

And to make six digital output that uses PWM to control the FAN's is also quite straight forward. but may also be subject to some driver circuit.

# Answer
> 1 votes
If you mean this kind of sensor:

The sensor is a simple microswitch with mechanical pressure switching point, which means your Arduino just needs to monitor 6 digital inputs. That is entirely possible.

The sensors would have one side connected to ground, and the other to a GPIO pin on the Arduino, with a pull-up resistor to 5V. Your code should just check each of the 6 GPIO inputs. If the pressure sensor is tripped, the input would be `LOW`, otherwise `HIGH`.

# Answer
> -1 votes
> What is the easiest way for me to do this?

you have to figure out how those sensors output their pressure measurements. if it is analog, you will need 6 analog pins, or have to a way to mux 6 analog inputs.

if it is digital, you will have to figure out how - 6 parallel output or 6 serial output; 6 GPIO digital or 6 numerical digital, ......

basically, do your homework first so others can help you help you.

---
Tags: arduino-uno, sensors, pressure
---


# Question
Title: Connecting Arduino Uno to a smartwatch via bluetooth
I have a U80 Smartwatch from Bluetooth Watch International, which has bluetooth function. It is meant to be connected via to my smartphone (and it works perfectly).

I also have an Arduino Uno board and a corresponding BLE ZS-040 bluetooth chip.

I need for my smartphone to be able to detect my Arduino board, so I can send data from a simple circuit connected to the Arduino board to the smartphone.

Basically, my circuit is meant to be a simple push button. When the button is pushed, and the circuit is closed, the Arduino board will send a signal to the smartwatch. This will cause the smartwatch to ring and vibrate, as if it is receiving a call. Then to turn off the ringing and vibrating, the user can simply 'answer the phone call', and it will stop.

From what I understand, (I'm very new to Arduino) I have to connect the Arduino board to the smartwatch first, which means I have to somehow get the board to be detected by my watch, which it's not doing yet, eventhough the bluetooth module is connected to the board.

Then the push button needs to send a signal to the watch. Which means the command {if buttonpush='1', send (receiving call)}, so when the button is pushed, the signal is sent and the watch acts as if it is receiving a call. Basically showing all the physical signs (eg. vibrating and/or ringing based on the watch's setting, showing 'answer/deny call', etc.). Btw, the push button is not to be held down. As long is the button is pushed and released once, the signal should be sent, and the watch will buzz until the 'phone call' is answered or denied.

1. I have absolutely no idea how to get the board connected to the smartwatch via bluetooth.
2. And while I have a rough idea on the push button circuit I need, I also need to send the signal for the watch to act like it has received a call.

Mainly, I'm looking for any help with coding here. If anyone can help with the physical circuit connections, that would be awesome too.

# Answer
> 3 votes
HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).

The two are not compatible.

You will need a BLE module for the Arduino which is capable of running as a "Central Device".

# Answer
> 1 votes
This isn't exactly an answer but I will like to share my experience after attempting a similar project for the past week.

I have an Arduino UNO and a HM-10 Bluetooth module that is capable of functioning in central mode. I referred to http://www.martyncurrey.com/hm-10-bluetooth-4ble-modules to setup.

I am trying to connect the Arduino UNO/HM-10 with a Hexiwear (http://www.hexiwear.com) bluetooth IoT development smartwatch that is capable of sending sensor data such as steps, heartrate, temperature etc. via bluetooth to a BLE central device.

The Hexiwear will generate a random 6 digit pin when you attempt to connect to it. It works with its own companion Android app and reads sensor data perfectly. Someone managed to pull in the hexiwear's sensor data to a Raspberri Pi via BLE here: https://mcuoneclipse.com/2016/12/19/tutorial-ble-pairing-the-raspberry-pi-3-model-b-with-hexiwear/comment-page-1/#comment-97375.

With my Arduino UNO, I managed up to the point were I could connect the hexiwear and it pops up to ask for the random 6 digit pin so that it could pair to my Ardunio.

And then I am stuck, because I know nothing about the Arduino UNO and HM-10 that can send the pin code back to the Hexiwear.

Here's where I thought might be useful:

1) Do you have the U80's BLE specifications. This is how much hexiwear's BLE specification looks like https://github.com/MikroElektronika/HEXIWEAR/blob/master/documentation/HEXIWEAR%20Bluetooth%20Specifications.pdf.

My Hexiwear wearable comes with source code. If I try hard enough I can probably hack it to make what I want to do possible.

2) Does U80 require pairing with pin code? I am stuck here in my project.

3) Is the library for your BLE chip capable to sending said BLE requests and responses to communicate with the U80? This is where I believe I am going to be stuck further.

Hope this helps in some ways.

---
Tags: arduino-uno, programming, bluetooth
---


# Question
Title: Broadcasting parallel data from Arduino using router
I'm looking to read data from sensors using an ArduinoUNO in a greenhouse and then access the data wirelessly through a router. Hopefully through a webpage. No need for internet access, just local network access is good enough.

Preferably the only components involved would be the Arduino, the circuit, and a router with OpenWRT/DD-WRT to host the webpage and broadcast the network.

Pretty new to Arduinos in general, would this be possible? And how? The following 2 links from instructables.com seem to be the most relevant, can anyone give their input on how similar/different is this to my project?

http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/

http://www.instructables.com/id/Getting-Arduino-data-to-a-web-Page/

# Answer
Use a NodeMCU (ESP8266 based) because it have WiFi included. It can work as a light web server. You can serve HTML, but not large files (like many .js).

Instead of HTML you can use websockets to get only data from NodeMCU and all the other files (html, js, images) from another bigger server. Websockets is fast, but you still have to deal with .html, .css, .js and other files in your webserver.

If you want something even easier and lighter, take a look at MQTT, which was developed with IoT in mind.

There is lot of MQTT client for Android/Iphone/PC/Mac. You use your client to send data and commands to your NodeMCU. No need to program anything here; you simply construct a visual interface by adding controls (buttons, meters) to a blank slate. No brains job.

You will need a *broker*, a server that acts as a relay, receiving commands/data from your Android and resending it to your NodeMCU. And your NodeMCU can publish temp, humidity, light levels and other data to your broker. You can use multiple client at once. There is no limit.

Your broker can be an public Internet broker (many) or a private one in your LAN. There is many brokers available for different platforms. You can run one in your smartphone or any old PC. Mosquitto is a free one.

Depending on your configuration, you will be even able to access your green house from Internet and look at your girls from far away.
> 1 votes

---
Tags: arduino-uno, wireless
---


title: PWM on non PWM pins

text:
# Question
Title: PWM on non PWM pins
Why does this code not function in a similar way to the example fade sketch? I have had to resort to using bit-banging as a way to implement PWM onto non PWM pins due to a lack of available free pins on my Arduino Pro Mini. I am using a sketch that supposedly should fade an LED ranging from maximum brightness to minimum brightness. My code however does not work. Can anyone figure out why my code does not operate in the same way the fade sketch does?

My current code is:

```
int brightness = 0;
int fadeAmount = 50;
void setup()
{
  pinMode(12, OUTPUT);
}
void loop()
{
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  digitalWrite(13, HIGH);
  delayMicroseconds(brightness); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 100);
}

```

And I want it to work in the same way as:

```
int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
  pinMode(led, OUTPUT);
}
void loop() {
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  delay(30);
}

```

If possible could anyone provide a correct version to help me with my project.

# Answer
You seem to have a typo on the pin number: you are configuring pin 12 and driving pin 13.

In other words: `pinMode(12, OUTPUT);` and `digitalWrite(13, HIGH);` do not match.
> 1 votes

# Answer
Your code here is not quite right:

```
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(1000 - 100);

```

Your two delays should add up to the total period (wavelength), or the reciprocal of the frequency (scaled to microseconds).

Hence the `- 100` in the second delay - that is subtracting the "on" time from the total time to give the "off" time. It should be replaced with `- brightness` as such:

```
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(1000 - brightness);

```

And of course the brightness is in the range 0 - 1000 not 0 - 255 like `analogWrite()`. To make it 0-255 you should replace the 1000 with 255, which of course makes it all run at a much higher frequency. (1 / 0.000255 = 3922Hz).

```
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(255 - brightness);

```

Mind you, all this is not good regardless of your calculations. This is a *blocking* system in which you are unable to do anything else at all in your program whilst generating PWM. Instead you should be using a timer (like the `tone()` command does) and switch between two different time periods each interrupt for "on" and "off" time periods. That way it can function asynchronously ("in the background") like `analogWrite()` does.
> 1 votes

# Answer
It's not strongly related to your question but i suggest you to use external library as SoftPWM.h

You can find the whole documentation on https://github.com/bhagman/SoftPWM
> 1 votes

# Answer
A more generic version of your approach would be like this.

1. Set the output pin - don't hardwire the pin number but instead use a macro for it.
2. Delay for it's duty cycles.
3. Clear the output pin.
4. Delay for period - duty cycles used in step 2 above.

You can put that in a routine and call it.

With that said the routine has limited use in a real application as it can drive one output pin and ties up the whole mcu needlessly.

A better approach is to use an interrupt and test for duty cycles in the interrupt . This can drive multiple pins with independent duty cycles. All without tying up the mcu.
> 0 votes

---
Tags: pwm, arduino-pro-mini, digital, digital-analog-conversion
---


# Question
Title: How to flash/blink I2C LCD backlight without delay function?
Since I am an using I2C LCD backpack, I'm unable to call in for pinmode to set variables like `#define BACKLIGHT_PIN 13`. I know `lcd.setBacklight(HIGH);` and `lcd.setBacklight(LOW);` controls the I2C LCD backlight, but if I use delay in the loop it slows down the whole loop.

How do I flicker the LCD backlight without using delay? I tried for example to blink without delay, but I don't know how to assign a global variable to `lcd.setbacklight` so as to control it.

I want to use an if statement to warn the user that so and so has happened, eg:

```
#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//Ticker flashBacklight(toggleBacklight, 100);
// when I use ticker here am getting not declared in scope
const int buttonPin = 3;
int buttonState = 0;
// pls declare flashBacklight, long flashBacklight = 100; ??
// pls declare toggleBacklight

void toggleBacklight() {
  // lcd.setBacklight(!lcd.getBacklight());
  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}

void setup() {
  lcd.begin(20, 4);
  lcd.setBacklight(HIGH);
  pinMode(buttonPin, INPUT);
 }

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    // if button goes high the back light must keep on flashing until it's released
    flashBacklight.start();
    //flash the lcd backlight
  } else {
    flashBacklight.stop(); // Stop flashing the backlight
  }
  flashBlacklight.update();
}

```

But delay slows down the whole loop, so how do I flash the backlight without it? Thank you.

# Answer
Besides the standard 'compute a target `millis()` and compare' standard, which can get clunky when you have to handle more than 1 repeating or delayed event, there are also more than one decent library that abstract the concept, but also add features.

One example is the Ticker library.

With these methods, you create a **callback** function and pass that function name into the object constructor, along with the timing parameters.

So you might:

```
[various #include, #define, etc.]

Ticker flashBacklight(toggleBacklight, 100); //call toggleBacklight() every 100ms

// Create the callback function, which just toggles the backlight each call.
void toggleBacklight() {
  lcd.setBacklight( !lcd.getBacklight() );
}

setup() {
  [...]
}

loop() {
  // Start or stop the ticker based on your own situation. Once started, it will call your callback function at the specified interval until stopped.

  if (warningSituation) {
    flashBacklight.start();
  } else {
    flashBacklight.stop();
  }

  flashBlacklight.update();
}

```

Another related library is SimpleTimer

**EDIT**

Your code example, updated:

```
#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void toggleBacklight();

Ticker flashBacklight(toggleBacklight, 100); //when i use ticker here am getting not declared in scope

const int buttonPin = 3;
int buttonState = 0;
                      // pls declare   flashBacklight   , long flashBacklight = 100;   ??
                      //   pls declare toggleBacklight

void toggleBacklight() {
 // lcd.setBacklight( !lcd.getBacklight() );  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}
void setup() {
   lcd.begin(20, 4);
 lcd.setBacklight(HIGH);
 pinMode(buttonPin, INPUT);
 }
void loop() {
      buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH)          // if button goes high the back light must keep on flashing untill its released
   {
    flashBacklight.start();          //flash the lcd backlight
  } else {
    flashBacklight.stop();           // Stop flashing the backligh
 }
   flashBacklight.update();
  }

```
> 2 votes

# Answer
You will need to alter the pin / bit tied to the backlight led.

To do that you will need to be able to read the state of all the pins on the i2c expander.

That can be done by reading back the pin state from the i2c expander or to hold the pin state in a buffer.

Once you know the pin state, you can OR or NEG it to clear or set the pin.
> 0 votes

# Answer
You record the timestamp when you want the LED to turn off again and then check that against millis in the `loop()`

```
  if ( level 1 > level 0)
  {

     NewTone(4,1000,50); // initiate alarm
     blinking = true;
     lcd.setBacklight(HIGH);
     lcdToggleTime = millis();// this is a global
     lcdOn = true;
  }else {
     blinking = false;
     lcd.setBacklight(LOW);
  }

  //at the start or end of loop(); make sure it's always checked.
if(blinking){
      if(millis() - lcdToggleTime>+100) {
         if(lcdOn)
             lcd.setBacklight(LOW);
         else
             lcd.setBacklight(HIGH);
         lcdOn = !lcdOn;
         lcdToggleTime = millis();// this is a global
     }
}

```
> -1 votes

---
Tags: arduino-uno
---


# Question
Title: Advice on cabling, packaging and connectors for 12v light project
My project is to have a 12V solar LED strip lighting system throughout my apartment. This has 6 individual lights, with 5 white and 1 RGB = 8 channels.

I've got the whole setup working on my breadboard. Now it's time to transfer it to a "live" setup. Since it's my first such project, I'm looking for any and all recommendations on cabling and connectors to deal with reliability, isolation, modularity, aesthetics and of course safety.

Schematically, it all looks something like this

```
solar panel------\
                  charge controller--5v regulator--arduino--mosfets x 8--\__lights
12v battery_fuse_/                  \____________________________________/

```

So I have questions such as:-

1. should I use a prototype shield, or a discrete pcb?
2. do the MOSFETs (RFP30N06LE) need a heatsink, and any recommended unit?
3. what connectors are recommended?
4. any suggestions on box/packaging for the above?
5. wire gauge? Maximum run is 4m to the furthest light.

And any other hints, tips and suggestions greatly appreciated. Bonus appreciation for amazon links to the parts :-)

update The breadboard is simply the mosfets, each with a current limiting resistor on the gate. The lights range from 8W to 40W. I will generally have them dimmed using PWM.

# Answer
> 2 votes
generic DC connector advice:

avoid the use of connectors which connect serially, like headphone jacks. you make strange combinations while plugging in

avoid connectors which do not latch, like headphone jacks

in a system like yours, with stages and signal processing in between, use different connectors for each phase, so you can not get it wrong

use connectors that can not be connected backwards for DC. I prefer:

Hopkins 47965 2-Pole Flat Extension for raw solar power.Not because it's a great connector, but because it's common in low power solar

* Anderson Power Poles for regulated DC power. you can secure them
together with a tie wrap; you can't connect them backwards without
doing things that are obviously counter intuitive.
* Fuel injection connectors from Autozone for signal wires. they got a million of them, they are made for DC at useful current levels
* Trailer connectors for multiple lead serious power.
* XLR connectors can be found from 3 to 6 pins, and you can't jam a 5 pin into a 6 pin, so you can't cross connnect

keep things dummy proof.

---
Tags: arduino-uno, power, led, mosfet
---


# Question
Title: How to keep a 24 hour maximum and minimum temperature
I am keeping a simple weather station to monitor humidity and temperature in my greenhouse. I have a ds18b20 and dht probes. everything works great and I even used a little trick to hold my maximum and minimum values, but I would like them to reset every 24 hours. Is there anyway i can code the arduino to reset itself. i tried several examples of connecting digital pins to the reset pin and i couldn't get any of those to work. i tried to reset the values of my max and min to 0 and 99 respectively after my millis() reached the equivalent of a day, but they just stuck at 0 and 999. I understand fully why it does this i just don't know how to fix it. all i want to do is reset my minimum and maximum temperatures after 24 hours.

```
//       Green HAUS Version 1 by Kent Scipione 9/3/2017
//       Monitors temperature and humidity
long timenow;
long day = 86400000; // 86400000 milliseconds in a day
long hour = 3600000; // 3600000 milliseconds in an hour
long minute = 60000; // 60000 milliseconds in a minute
long second =  1000; // 1000 milliseconds in a second

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
#define ONE_WIRE_BUS 10
double temp;  // sensor is precise to .1 degree.
//Double gives smoother serial graph, byte doesn't overflow oled screen
Adafruit_SSD1306 display(OLED_RESET);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#include <Adafruit_Sensor.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

int maxtemp=0;
int mintemp=999;

void setup() {

  Serial.begin(9600);
  Serial.println("green HAUS Version 1 by Kent Scipione 9/3/2017");
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  display.setTextColor(WHITE);
  sensors.begin();
  dht.begin();

}

void loop() {
  timenow = millis();
  sensors.requestTemperatures();
  temp = sensors.getTempFByIndex(0);
  int humid = dht.readHumidity();
  float dtemp = dht.readTemperature(true);
  if (temp > maxtemp) {
    maxtemp=temp; }
  if (temp < mintemp) {
    mintemp=temp; }

  if (timenow >= day){
      digitalWrite(4, HIGH);
      pinMode(4, OUTPUT);       //*************************this is the part where I'm trying to reset the mintemp and maxtemp**********

    }

  Serial.print("Probe Temperature: ");
  Serial.println(temp); Serial.println("*F");
  display.setCursor(0,0);  //refreshes display
  display.clearDisplay();
  display.setTextSize(1); display.print("Probe "); display.println(temp);  //line 1 of text
  display.print("DHT  "); display.print(dtemp); display.print("  "); display.print(humid); display.println(" %");  //line 2 of text
  display.print("HIGH "); display.println(maxtemp);           //line 3 of text
  display.print("LOW  "); display.println(mintemp);   //line 4 of text
  display.display();

}

```

Thank you so much for your help this is driving me mad haha

# Answer
> 2 votes
You should also keep a timestamp of the last time you reset the min and max otherwise the arduino will keep thinking it's a new day:

```
//add to globals
unsigned long lastDay = 0;

```

and inside loop()

```
  if (timenow-lastday >= day){

      maxtemp=0;
      mintemp=999;
      lastDay = timenow;
  }

```

---
Tags: millis, reset
---


title: Allocation, initialization and scope

text:
# Question
Title: Allocation, initialization and scope
I realized I don't fully understand how Arduino code handles variable lifetime. My tendency is to keep variables in the narrowest scope (which I realize isn't as important in Arduino code, but, habits...). But how inefficient is this?

Given these possible variations:

```
 const int c1 = 2, c2 = 7, c3 = 9;

 void functy();

 int foo[3] = {c1 | c2, c3, c2 | c3};

 static int foo[3] = {c1 | c2, c3, c2 | c3};

 const int foo[3] = {c1 | c2, c3, c2 | c3};

  ....

```

In case 1, foo is both allocated and initialized each call.

In case 2, foo is allocated only once, but is it initialized on each call?

In case 3 I assume that allocation and initialization are done only once? Is that true?

# Answer
Here's a pretty definitive list for you:

```
// Allocated once in the global area and assigned during
// program startup
int foo = 1;

// May not even be allocated - the compiler will most likely
// optimise it out.
const int foo = 1;

// Allocated once and assigned during program startup. Cannot be
// accessed from outside the file.
static int foo = 1;

// The static here has no real effect.
static const int foo = 1;

void function() {
    // Allocated in the stack each call and initialised each call.
    // Only accessible from inside this function.
    int foo = 1;

    // Allocated in the global area and initialized on the first call
    // of the function. Only accessible from inside this function.
    static int foo = 1;

    // May not be allocated at all. Only accessible from inside
    // this function.
    const int foo = 1;
}

```

Note that non-simple `const` values, things like arrays and strings, depending on the architecture (i.e., if it's a Harvard architecture or not) may be copied into a block of global RAM for simpler access. See `PROGMEM` in the Arduino Reference Manual for more information.
> 2 votes

---
Tags: c++, variables
---


title: Arduino Controlling a stepper motor

text:
# Question
Title: Arduino Controlling a stepper motor
How can I get an Arduino to do the following to a Stepper Motor installed on a "Lead-screw" attached to my table-saw's Fence?

1. Turn the "lead-screw" clockwise when I press a given button, UNTIL I release the button.
2. Turn the same "lead-screw" counter-clockwise, when I press another button, UNTIL I release the button.
3. Adjust a "speed" knob, to control the motor's speed when the fence is moving; from very fast to very slow; and even stop when the control is completely counter-clockwise.
4. Turn a switch off, which will remove all control to the motor; so I can turn the shaft manually without resistance, whenever I do not want the fence to be under control of the motor.

That is ALL I need.

It is that simple. So what do I need? What do I need to purchase? I am a novice.

# Answer
I've got to ask here. Why use a stepper? This would be fairly easy with two button switches and a regular DC motor. One switch provides power to drive the motor CW the 2nd motor drives it CCW.

You would still need to choose a motor with the right torque but IMHO this method would be WAY easier than using a stepper, and arduino, writing code, etc.
> 1 votes

# Answer
We can't tell you what to buy. We can help you understand how it will work, though, and what you should look for.

First off you need a suitable stepper motor. We can't help you with that. You need one that will a) connect to your lead screw in some way, and b) have enough power to drive the screw. Maybe the robotics stack-exchange can help you better with that.

Once you have identified your stepper motor you need a driver that can control it. There's two kinds of stepper motor - "unipolar" and "bipolar" and the type of stepper motor you have chosen will determine the type of driver you need. Suffice it to say if you have a "unipolar" stepper motor you need a "unipolar" driver.

In brief: a bipolar stepper motor usually has 4 wires and needs a pair of H-bridges to drive it. A unipolar stepper driver normally has 5 or 6 wires and just needs beefy MOSFETs to drive it.

Your driver will, of course, need to be able to provide enough current to drive your stepper motor. For the finer details of the driver the electronics stack-exchange will most likely have the most expertise.

One further thing you will need is a potentiometer (and fancy knob etc) to set the speed.

Then it's just a matter of "gluing" everything together through the Arduino and writing the software.

How you write the software for the Arduino depends on the driver for your stepper motor. There are libraries with examples for most types. Adding in an `analogRead(...)` and `map(...)` to convert the voltage from the potentiometer into a speed should be simple enough.
> 0 votes

---
Tags: arduino-uno, stepper
---


title: Efficiency of a cast vs a shift

text:
# Question
Title: Efficiency of a cast vs a shift
I'm using a supplied library which uses a number of (non-sequential) outputs to latch a multiplexer. The code looks (in part) like this:

```
 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 3)>>1);
 digitalWrite(_S2, (chan & 7)>>2);
 digitalWrite(_S3, (chan & 15)>>3);

```

Those masks seem a little odd, but it would work. More natural to me would be:

```
 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 2)>>1);
 digitalWrite(_S2, (chan & 4)>>2);
 digitalWrite(_S3, (chan & 8)>>3);

```

But overall, would it be more efficient to do this?

```
 digitalWrite(_S0,       (chan & 1));
 digitalWrite(_S1, (bool)(chan & 2));
 digitalWrite(_S2, (bool)(chan & 4));
 digitalWrite(_S3, (bool)(chan & 8));

```

...or is shifting already pretty efficient?

I've actually re-written the code to build a mask and use PORTx to latch it all at once, so this is really an academic question, but I'm still curious.

# Answer
I tried compiling your three snippets with avr-gcc 4.9.2 at the `-Os` optimization level (standard with Arduino) but *without* `-flto`. The results were:

* The first snippet generated inefficient code: the ands and shifts were translated in assembly quite literally, the shifts were done on 16 bits even though `chan` was declared `uint8_t`, and the last shift was even implemented as a loop roughly equivalent to `uint16_t tmp1 = chan & 15; uint8_t tmp2 = 3; while (--tmp2) tmp1 <<= 1;`
* The second and third snippets were translated identically and efficiently, using the `bst` (bit store) and `bld` (bit load) instructions to copy the relevant bit of `chan` into the second argument of the `digitalWrite()` call.

Personally I would just write

```
digitalWrite(_S0, chan & 1);
digitalWrite(_S1, chan & 2);
digitalWrite(_S2, chan & 4);
digitalWrite(_S3, chan & 8);

```

as `digitalWrite()` expects an integer as its second argument, and it interprets it just like the `(bool)` cast does. If you want to be sure to always call `digitalWrite()` with either 0 (`LOW`) or 1 (`HIGH`), then use either your second of third form. The first form seems formally equivalent to the second, but since it is *not* an usual C idiom, the compiler could not catch the optimization opportunity.
> 3 votes

# Answer
If you look at the assembly code the compiler produces, you can see it compiles to the exact same thing - when using a constant.:

```
void setup() {
  ....
  digitalWrite(_S1, (chan & 2)>>1);
 282:   84 e0           ldi r24, 0x04   ; 4
 284:   0e 94 6b 00     call    0xd6    ; 0xd6 <digitalWrite.constprop.0>
 ....
  digitalWrite(_S1, (bool)(chan & 2));
 29a:   84 e0           ldi r24, 0x04   ; 4
 29c:   0e 94 6b 00     call    0xd6    ; 0xd6 <digitalWrite.constprop.0>

```

However, using a variable produces different results:

```
void loop() {
  digitalWrite(_S0, (chan & 1));
 2a2:   c0 91 00 01     lds r28, 0x0100 ; 0x800100 <__data_start>
 2a6:   d0 91 01 01     lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
 2aa:   6c 2f           mov r22, r28
 2ac:   61 70           andi    r22, 0x01   ; 1
 2ae:   83 e0           ldi r24, 0x03   ; 3
 2b0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S1, (chan & 2)>>1);
 2b4:   6c 2f           mov r22, r28
 2b6:   66 95           lsr r22
 2b8:   61 70           andi    r22, 0x01   ; 1
 2ba:   84 e0           ldi r24, 0x04   ; 4
 2bc:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S2, (chan & 4)>>2);
 2c0:   c2 fb           bst r28, 2
 2c2:   66 27           eor r22, r22
 2c4:   60 f9           bld r22, 0
 2c6:   85 e0           ldi r24, 0x05   ; 5
 2c8:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S3, (chan & 8)>>3);
 2cc:   c3 fb           bst r28, 3
 2ce:   66 27           eor r22, r22
 2d0:   60 f9           bld r22, 0
 2d2:   86 e0           ldi r24, 0x06   ; 6
 2d4:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>

 ....

  digitalWrite(_S0,       (chan & 1));
 2a2:   c0 91 00 01     lds r28, 0x0100 ; 0x800100 <__data_start>
 2a6:   d0 91 01 01     lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
 2aa:   6c 2f           mov r22, r28
 2ac:   61 70           andi    r22, 0x01   ; 1
 2ae:   83 e0           ldi r24, 0x03   ; 3
 2b0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S1, (bool)(chan & 2));
 2b4:   be 01           movw    r22, r28
 2b6:   76 95           lsr r23
 2b8:   67 95           ror r22
 2ba:   61 70           andi    r22, 0x01   ; 1
 2bc:   84 e0           ldi r24, 0x04   ; 4
 2be:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S2, (bool)(chan & 4));
 2c2:   be 01           movw    r22, r28
 2c4:   76 95           lsr r23
 2c6:   67 95           ror r22
 2c8:   76 95           lsr r23
 2ca:   67 95           ror r22
 2cc:   61 70           andi    r22, 0x01   ; 1
 2ce:   85 e0           ldi r24, 0x05   ; 5
 2d0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S3, (bool)(chan & 8));
 2d4:   be 01           movw    r22, r28
 2d6:   23 e0           ldi r18, 0x03   ; 3
 2d8:   76 95           lsr r23
 2da:   67 95           ror r22
 2dc:   2a 95           dec r18
 2de:   e1 f7           brne    .-8         ; 0x2d8 <main+0xc0>
 2e0:   61 70           andi    r22, 0x01   ; 1
 2e2:   86 e0           ldi r24, 0x06   ; 6
 2e4:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>

```
> 3 votes

---
Tags: programming, c++, compile
---


# Question
Title: Cannot mount NodeMCU with MicroPython on Mac OS X
I've recently bought a NodeMCU board and flashed MicroPython in it. I've read about the `boot.py` and `main.py` scripts, but I can't understand how to access them...

I have succesfully connected to the Python REPL with the screen command and everything works fine. Is there a way to mount it as an external drive on Mac OS X? Because I haven't found a way till now.

Thanks in advance!

# Answer
The typical NodeMCU board uses a fixed function CP-210x USB-Serial chip. This cannot appear to a host operating system as any ordinary sort of storage device, so it is not "mountable" via conventional storage drivers.

Access would need to be through some client program - or else, at a bit of a stretch, some highly specialized driver that created something fitting the host operating system's idea of filesystem, but proxying the actions through operatings the CP-210x and software running in the ESP8266 can support.
> 2 votes

# Answer
You have a NodeMCU; not a pyboard. I'm not sure that the USB Drive option is available in the NodeMCU.

I flashed microPython in a NodeMCU and Linux doesn't recognize it as a external drive or any other media type, but REPL thru serial monitor works fine.
> 1 votes

---
Tags: python, nodemcu
---


# Question
Title: I2C Temperature Sensor Communication Issue
I'm currently learning I2C and having some issues displaying the correct temperature in the serial monitor.

I am using an Arduino Uno and an SI7021 temperature sensor from Sparkfun; here's the datasheet I'm looking at.

The datasheet says that its device address is `0x40` and the temperature register is `0xF3` (maybe I am looking at this wrong?). However when I print the result to the screen it reads -1 degrees F.

Here's my code:

```
// SparkFun Si7021 Humidity and Temperature Sensor
#include <SparkFun_Si7021_Breakout_Library.h>
#include <Wire.h>

//Weather sensor slave address
int WeatherAddress = 0x40;

#define Temperature_Register_DATA 0xF3

//initialize humidity and temperature variables
float humidity = 0;
float tempf = 0;

//create a sensor from the Weather library
Weather temp_rh_sensor;

void setup() {
  Serial.begin(9600);
  //create wire object
  Wire.begin();
  //begin weather sensor
  temp_rh_sensor.begin();
}

void loop() {
  //begin transmission to weather sensor
  Wire.beginTransmission(WeatherAddress);
  //ask particular register for data (temperature register)
  Wire.write(Temperature_Register_DATA);
  Wire.endTransmission();
  //request the transmitted single byte from the register
  Wire.requestFrom(Temperature_Register_DATA, 1);
  if(Wire.available() <= 1) {
    tempf = Wire.read();
  }
  Serial.print("Temp: ");
  Serial.print(tempf);
  Serial.println("F, ");
  delay(1000);
}

```

# Answer
Reading this sensor is a little more involved. You don't just select a register and then read the value from it. Instead you send it a command to begin a read of a parameter (e.g., temperature) and then you need to wait for it to perform that command before you can read the result.

You need to use command 0xF3 for read with *no hold master mode* which will return NACK from a read request if the command isn't completed (which you are doing) - you then need to keep retrying the read until you don't get a NACK.

Also you need to read *two* bytes, not one:

```
//begin transmission to weather sensor
Wire.beginTransmission(WeatherAddress);

//ask particular register for data (temperature register)
Wire.write(Temperature_Register_DATA);

Wire.endTransmission();

// Keep retrying the read until it succeeds, or times out
uint32_t start = millis();
while (Wire.requestFrom(WeatherAddress, 2) < 2) {
    if (millis() - start > 2000) { // 2 second timeout
        break;
    }
}

if (Wire.available() < 2) { // It timed out
    Serial.println("Timeout");
} else {
    // Read the two bytes
    uint8_t hi = Wire.read();
    uint8_t lo = Wire.read();

    // and combine them into a 16 bit value
    uint16_t temp = (hi << 8) | lo;

    // Now convert the returned value into a real temperature:
    tempf = ((175.25 * temp) / 65536.0) - 46.85
    Serial.print("Temperature: ");
    Serial.println(tempf);
}

```
> 1 votes

# Answer
```
Wire.requestFrom(Temperature_Register_DATA, 1);

```

This should have the WeatherAddress as parameter instead of the register.

```
Wire.requestFrom(WeatherAddress, 1);

```
> 2 votes

# Answer
> The datasheet says that its device address is: 0x40

there is no standard notation on how to code i2c addresses - it all depends on how the particular library is coded. In this case, try 0x80 and 0x40 and see which one works.
> 0 votes

---
Tags: i2c, communication, temperature-sensor
---


# Question
Title: What good designs are available for Geiger counters using an Arduino?
Are there any good circuit designs for Geiger-counter projects using an Arduino?

If so, what Geiger-Muller tubes should I choose to detect different types of radiation?

# Answer
> 9 votes
There are a few good, open-source, designs for Geiger counters using cheap G-M tubes and Arduino boards out there. Which one is best for you depends on what you want to achieve, so let's start by taking a look at what you might want to detect.

---

## What are these "types" of radiation?

(*source: Wikipedia*)

**Alpha radiation**: basically consists of helium-4 nuclei (i.e. two protons and two neutrons). These interact with matter strongly because they are relatively heavy and carry a positive charge. However, because of their mass they will normally only penetrate a few centimetres of air. Alpha particles can be stopped in their tracks by a single sheet of paper.

You may not realise it, but the sensor in most smoke detectors uses a very small amount (~0.2μg) of Americium - 241Am.

**Beta radiation**: consists of highly energetic electrons. Because these particles are relatively light, they can penetrate somewhat further than Alpha particles. Even so, beta radiation can be stopped by a thin sheet of aluminium.

The big risk to human health from alpha- and beta-emitters is when they are ingested or inhaled. In these cases, the particles are brought into close contact with sensitive live tissue where the ionising radiation has the potential to cause various types of cancers.

**Gamma radiation:** is electromagnetic radiation having a higher frequency and shorter wavelength than X-rays.

One way to think of gamma-radiation is like a kind of "super X-ray". Gamma rays can pass through virtually anything. To build an effective shield, you need to have either *very* thick walls or a shield made from something with a high atomic weight, such as lead.

Gamma rays are produced naturally by the sun and stars - this is the source of what we call "cosmic radiation".

---

## So which tubes should you choose?

Once you have decided what types of radiation you want your Geiger counter to detect the next step is choosing the tube. In general, they are all high-voltage tubes, typically operating at ~ 400V.

At the moment, the cheapest available tubes are probably the Russian SI-3BG Geiger Muller tubes, which can be picked up on eBay for about £5 GB. These are not very sensitive, but I've found they do work OK for beta and gamma radiation. However, it doesn't detect alpha radiation (which, as mentioned earlier, is what is emitted by the source in the sensor in many smoke detectors!)

One thing to watch out for is that these tubes are all different sizes, ranging from about 20mm long to more than 200mm. This matters. If you are going to design or buy a PCB for your project, just check that it has been designed to fit the sensor that you intend to use.

The following table lists the most popular G-M tubes, together with their main characteristics:

Follow the links below for further data on each tube:

Your choice of tube is going to be determined by your budget, the types of radiation you want to detect and the sensitivity you want to achieve with your G-M counter.

---

## Circuit designs

OK, so now we understand the radiation types, and we've chosen our tube, what Geiger counter designs are out there that use the Arduino.

(***disclaimer***: I have no connection with any of the companies mentioned in this answer)

Well, it turns out there are a few good designs out there (Google is your friend here), but one that does stand out from the pack (IMHO) is the Geiger Counter - Radiation Sensor Board for Arduino and Raspberry Pi from Cooking Hacks.

This is an open hardware design, and the code can be downloaded on a GPL licence.

It's a relatively simple design, and has a kit available pretty much off-the-shelf. Software can be downloaded for the Arduino and/or the Raspberry Pi. If you decide to buy the kit, they assure us that the shield/hat has been tested with the Arduino Uno and all models of the R-Pi.

Alternatively, you can just download the circuit diagram on the link above and design your own PCB (I don't think they offer the Gerber or Eagle files to download).

It is worth mentioning that the tutorial page also includes all the lovely useful background theory you'll need to understand how Geiger counters work, and how to get the most out of it.

---

---

**Final thoughts**. If you were thinking of building a Geiger counter without using an Arduino (Yes, yes, I know. But there may be some strange people out there who want to go this route!), there are still some nice designs out there you can play with.

The Geiger counter from MightyOhm is also open-source and uses the SBM-20 Geiger-Muller tube. Again, it is available as a kit, but if you prefer the DIY route, the design files are available to download.

Having looked at it, adapting this design to interface with an Arduino would probably also be relatively straightforward ...

If you are on a really tight budget there is a $15 Geiger counter on Hackaday. This uses the Russian SI-3BG G-M tube (discussed above) and a modified power-supply from a disposable camera.

I built one of these with a friend who was just starting out studying electronics and wanted to have a go at this project. I can confirm that it works, but that $15 price-tag is very optimistic.

(Having built this one, my friend decided that her next project would be to design a better one with greater sensitivity and which could detect alpha-, beta- and gamma-radiation and which incorporated an Arduino Uno. In hindsight, I should probably have mentioned the design from Cooking Hacks ..!).

---
Tags: arduino-uno, sensors
---


# Question
Title: Serial - Send data to Arduino while Arduino sending data
Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. `Serial.available()` returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?

PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.

Example code:

```
void loop(){

  if(Serial.available())
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

```

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.

# Answer
> 1 votes
Following up on what Nick Gammon says, don't try to use the serial output to debug serial. Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.

The following is how I've been reading a line at a time using non-blocking operations:

```
const int SERIAL_BUFFER_LENGTH = 100;

// The +1 assures we'll always have room for null termination
char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
int g_char_count;         // index into serial buffer

void setup() {
  Serial.begin(9600);  // or 115200 if your host supports it
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  g_char_count = 0;
}

void loop() {
  while(Serial.available() > 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    char c = Serial.read();   // won't block because Serial.available() > 0
    if (c == '\n') {
      g_serial_buffer[g_char_count] = '\0';  // null terminate
      process_buffer(g_serial_buffer);
      g_char_count = 0;
    } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
      g_serial_buffer[g_char_count++] = c;
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
  Serial.print(".");
}

// process_buffer: do whatever it is you intended to do with a
// line of received text...
void process_buffer(char *buffer) {
}

```

# Answer
> 0 votes
Try this:

```
  if(Serial.available())
    while(Serial.read());
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

```

I think you have to read what you get in the serial port.

---
Tags: serial, arduino-mega, code-review
---


# Question
Title: How to send data from an Arduino GPRS module to a Django application hosted on Heroku?
I have a Django web application hosted on a Heroku server. Currently I am using the free package for hosting. I want to send data from an Arduino using a SIM900L GPRS module to the web application. I want to know if it is possible. I have searched for a solution but couldn't find a proper guide or example for it. My web application accepts get requests and updates values in the database when url is entered. However if the Arduino sends data using the same url I get the following error:

> AT+CIPSTART="TipCP","https://.herokuapp.com",80 ERROR

Any tested example or suggestions about what I am doing wrong or what I should be doing instead?

```
     void gprs(float *value1, float *value2, float *value3, float *AFR, float *value5, float *value6)
{

  String APN = "";
  String UNAME = "";
  String PWD = "";
  char fid[] = "";
  char nid[] = "";
  char s_ip[] = "https://<appname>.herokuapp.com";
  char apikey[] = "";

  wdt_reset();
  digitalWrite(A4, HIGH);
  Serial.println(F("GPRS-1 Function"));
  delay(5000);
  wdt_reset();
  delay(5000);
  wdt_reset();

  char buffer1[10];

  uint8_t GSMTries = 0;
  String res;

  //wdt_reset();
  // the below code establishes connection and if not successful
  // tries three times in total
  do {
    sendData(F("AT\r\n"), 1000, DEBUG);
    sendData(F("AT+CIPSHUT\r\n"), 2000, DEBUG);
    sendData(F("AT+CIPMUX=0\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    sendData("AT+CSTT= \"" + APN + "\", \"" + UNAME + "\", \"" + PWD + "\"\r\n", 2000, DEBUG);

    sendData(F("AT+CIICR\r\n"), 2000, DEBUG);
    sendData(F("AT+CIFSR\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
    scnt += s_ip ;
    scnt += "\",80\r\n" ;

    res = sendData(scnt, 10000, DEBUG);
    GSMTries++;

    wdt_reset();

  } while (((res.indexOf("ERROR") != -1) || (res.indexOf("CONNECT") == -1)) && (GSMTries < 3));
  /*
    if(res.indexOf("ERROR") != -1){
    delay(200);
    sendData(scnt, 10000, DEBUG);
    }
  */

  String api = "GET /value?apkey=" ;
  api += apikey;
  api += "&&fid=";
  api += fid;
  api += "&&nid=";
  api += nid;

  Serial.println(F("API......."));
  Serial.flush();
  Serial.println(F("here-1"));

  String Data1 = "";

  //wdt_reset();
  //Co ordinator data is compiled along with html commands
  //and sent through GPRS
  String sensor = dtostrf(*value1, 4, 2, buffer1);
  Data1.concat(api);
  Data1.concat(F("&field1="));
  Data1.concat(sensor);

  sensor = dtostrf(*value2, 4, 2, buffer1);
  Data1.concat(F("&field2="));
  Data1.concat(sensor);

  sensor = dtostrf(*value3, 4, 2, buffer1);
  Data1.concat(F("&field3="));
  Data1.concat(sensor);

  sensor = dtostrf(*AFR, 4, 2, buffer1);
  Data1.concat(F("&field4="));
  Data1.concat(sensor);

  sensor = dtostrf(*value4, 4, 2, buffer1);
  Data1.concat(F("&field5="));
  Data1.concat(sensor);

  sensor = dtostrf(*value6, 4, 2, buffer1);
  Data1.concat(F("&field6="));
  Data1.concat(sensor);

  Data1.concat(F("\r\n"));

  delay(1000);

  String cipSend = "AT+CIPSEND=";
  cipSend.concat(Data1.length());
  cipSend.concat("\r\n");
  sendData(cipSend, 8000, DEBUG);
  sendData(Data1, 8000, DEBUG);
  sendData(F("AT+CIPCLOSE\r\n"), 5000, DEBUG);
  digitalWrite(A4, LOW);

  wdt_reset();

}

```

The above is a part of code used in arduino to upload data to website. This code was being used before to upload data to thingspeak through its IP address and worked fine.

# Answer
There's a number of errors in your program regarding your understanding of basic networking:

Let's start with this bit:

```
String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
scnt += s_ip ;
scnt += "\",80\r\n" ;

```

That constructs a string:

```
AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80

```

and sends it to the modem. Now:

1. There is no such protocol as "TipCP" - I think you meant "TCP"
2. You need to provide an FQDN (Fully Qualified Domain Name), *not* a URL. FQDNs don't start with "https://". I think you meant to use "foobar.herokuapp.com" where "foobar" is the name of your application.

You then go on to form a GET request and send it.

Now: the URL you used instead of an FQDN starts with https:// - that tells me you want to be using SSL for your communications. I don't know if that is required for Heroku or not, but if it is then you cannot use `AT+CIPSTART` with it unless you feel like trying to implement the entirety of SSL in your program. Also you would be connecting to port 443 not port 80.

Assuming you don't need SSL fixing your protocol and FQDN may be enough. However using the `AT+HTTP...` commands instead of manual manipulation of a raw TCP socket may be an easier option.

If you *do* need SSL (and it is advisable that you do if you can) then you will have to use the SIM900's `AT+HTTPS...` command set (detailed here).
> 1 votes

---
Tags: python
---


title: Interrupt problem...?

text:
# Question
Title: Interrupt problem...?
I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.

In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:

```
#include <Encoder.h>   // is this library the cause??...

#define PIN_1 4
#define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
#define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

void setup() {
  pinMode(PIN_B, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(PIN_B, ButtonPressISR, FALLING);
  attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
}

void loop() {
  Serial.println("Don't interrupt me");
  delay(10);
}

void ButtonPressISR() {
  Serial.println("Yay, I'm pressed!");
  delay(1000);
}

void ButtonReleaseISR() {
  Serial.println("Yay, I'm released!");
  delay(1000);
}

```

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.

When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.

The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 2 votes
Neither delay or print should be used in an interrupt routine as they use interrupts themselves, instead set a flag (usually a volatile variable) and test for that in the loop. Also be aware that due to contact bounce the interrupt will trigger multiple times for each button press.

# Answer
> 0 votes
> They, however, refuse to work,

more accurately, you are unable to make them work.

1. don't delay large amount of time;
2. be careful with calling routines that are also called outside of the isr;
3. one isr for one pin.

---
Tags: interrupt
---


# Question
Title: What is the worst time case for Arduino Mega?
I'm going to implement home automation using an Arduino Mega with 8\*6=48 channels relay in my new home. I have prepared an Android app for an HC-05 Bluetooth controller. How much time can I keep running an Arduino Mega with all the appliances in a home? Can I keep it working 24/7 for a while?

# Answer
> Can I keep it working 24/7 for a while?

yes, if properly designed.
> 0 votes

# Answer
Yes.

(For better guidance than that, we'd need to know more.)
> 2 votes

# Answer
I would be wary of going "all in" if the MCU holds+controls the state of all the relays, especially if there's networking happening in the sketch. That creates a single-point of failure for the whole house. I've found that a brief power outage or an MCU freeze/reboot resets the state. That can be frustrating and downright dangerous in a emergency situation.

An obvious solution is to save the relay states in EEPROM or externally on a server. The issue with those is that EEPROM wears out, and your server might not be available soon after a power-cycle when the MCU needs it to resume (router re-connecting, computer rebooting slower than MCU, etc).

The real solution, and the one that preserves life-safety is having local hardware state for each relay. You need the ability to both read state from the Arduino, and change the state from the Arduino. This can be as simple (yet expensive) as physically latching relays, or a capacitor-backed 1-bit state machine like an RS flip-flop. You can build the flip-flop in a variety of circuits, from shift registers, to a 555, to a simple NPN+n-channel MOSFET coupling (my pref).

The big downside is that this needs two pins for each relay. But, with such "smart relays", you can unplug the Arduino and nothing happens around the house. It also allows non-Arduino things (even a simple button/switch) to control the state of a relay, no matter what's happening with the Arduino at the time, but with the ability of the Arduino to react to that change and not over-write or forget the state. The MCU can reboot on a schedule to keep responsive, without anyone noticing the reboot.

Yes, it adds more complexity and cost, but a manageable amount of both, and the satisfaction difference is hard to truly express. In short, any system should work as reliably as lights did 100 years ago: switches work, and never unexpectedly change. If lights are not working or are turning off unexpectedly in a small fire, things can get ugly quick, especially with guests.
> 0 votes

---
Tags: arduino-mega, relay, hc-05, home-automation
---


title: What are these wires called?

text:
# Question
Title: What are these wires called?
I'm currently developing a quad copter for my school project and I am coming to the part where I am collecting all the parts before I assemble everything.

I have recently encountered a roadblock. I am going to solder an Arduino nano onto a strip board, but the problem is I cannot seem to find cables/wires to connect the nano to the module.

Excuse my ignorance, but where can I find these cables for soldering and what are they called?

# Answer
> 5 votes
If they are an intentional part of the design they are *jumper wires*. If they are to correct a mistake in the design they are *bodge wires*.

They aren't anything special, just wire. They look to be in the range of 24 to 30 AWG and PVC jacketed.

You can buy it in any electronic store.

You can also salvage it from things like old SCART cables and similar things.

# Answer
> 3 votes
If you want to wire your board with stranded wire, you can ask for ***NYAF*** and solder the edges with the tip. Otherwise you can ask for ***hook-up wires***.

But if you are using breadboard, which i recommend you to use solid wire, you can ask it as ***wire wrap***.

You can find them at an electronic store.

# Answer
> 2 votes
Read this tutorial about working with wires.

Sorry for the link-only answer, but I can't copy the article in full.

# Answer
> 1 votes
> but where can I find these cables for soldering and what are they called?

hook-up wires.

pretty much any hardware stores should have it.

---
Tags: arduino-uno, arduino-nano, wires
---


title: Atmega328p screen + midi, possible?

text:
# Question
Title: Atmega328p screen + midi, possible?
I'm trying to build this Midi2CV (control voltage for analog synths) using a Arduino Nano:

https://photos.app.goo.gl/3IhhFL3PrLELLODB3

I was hoping to use this Nokia screen too for settings and debugging purposes, but I just realized there's only one hardware serial port on 328p and software serial seemed to be doomed for MIDI:

SoftwareSerial too slow for MIDI?

So I have three peripherals:

* DAC (MCP4822)
* Nokia 5110 screen
* MIDI

I've gotten both the DAC and screen to work fine on normal pins so I'm thinking I'm good with just using the hardware serial for MIDI and the DAC and screen can use software. Or am I in for a world of pain without getting a more powerful chip with more hardware serial ports? And if so, what's the recommendation? (shoestring budget)

# Answer
> 1 votes
Of your three functions (DAC, screen and MIDI) only one (MIDI) actually uses UART.

The other two devices are SPI devices which, while it is a *serial* protocol isn't UART (serial is a *concept* not a protocol).

Connect the DAC and screen to the SPI port (you can share SCK, MOSI and MISO, but select different CS pins) and you have the UART pins (0/1) available for MIDI use - as long as you don't want to use the USB connection which is linked directly to those pins.

---
Tags: arduino-nano, display, midi
---


# Question
Title: Adafruit Motor Shield and Bridge Library for Yun Shield
I am using the Leonardo board with the Adafruit Motor Shield v2, 2 steppers and the Yun Shield. The yun shield and steppers all run harmoniously, however, as soon as I do Bridge.begin() and anything that accesses the Yun shield Bridge library to access the console, the steppers stop running. Is this to be expected and are there any solutions?

Thanks

# Answer
> 1 votes
Looking at Bridge.begin() description here you can see this is blocking function.

> begin() is a blocking function. Once you call Bridge.begin(), nothing else will happen in your sketch until it has completed. This process takes approximately three seconds.

---
Tags: arduino-yun, adafruit, stepper
---


title: Fade sketch stuck in mathematical loop

text:
# Question
Title: Fade sketch stuck in mathematical loop
I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!

It worked generally but **sometimes** while turning the potentiometer, the **LED would be stuck at a fixed level of brightness**. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.

I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?

\*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.

-----------------------------Fade sketch edited by me----------------------

```
/*
 Fade, edited with maximum intensity controlled by potentiometer reading
 */

int led = 11;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
int potPin = A0;    // set the pin that reads the potentiometer voltage
int potValue = 0;   // declare and initialize potValue
int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  //read the voltage at the pot
  potValue = analogRead(potPin);

  //convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
  potValueConverted = round(potValue/4);

  // set the brightness of pin 11:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

Serial.println(brightness);

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= potValueConverted) {
    fadeAmount = -fadeAmount;
  }

  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

```

---

# Answer
It seems like the problem occurs when brightness is a lot higher than potValueConverted.

For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.

> brightness \>= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95). This results in the LED getting stuck at the same level of brightness.

a quick hack fixes this problem (as far as I can tell)

```
 if (brightness <= 0 ) {
    fadeAmount = 5;
  }
 if (brightness >= potValueConverted +5 ) {
    fadeAmount = -5;
  }

```

\**note the +5 for the second if statement is to ensure that the brightness value does not become negative.
> 3 votes

# Answer
> the LED would be stuck at a fixed level of brightness.

that's by design: think about what happens when potValueConverted is very small.

edit:

to change the brighness, I would do this:

```
  brightness += fading; //change brightness;
  if ((brightness < BRIGHTNESS_MIN) || (brightness > BRIGHTNESS_MAX)) {fading = -fading; brightness += fading;} //bound brightness to _MIN and _MAX

```
> 0 votes

---
Tags: arduino-uno, serial, led, arduino-nano
---


# Question
Title: Board recommendations for GPRS/GSM for 'on the go'
I have been tasked to find a way of communicating to a webservice from my microcontroller - yay!

With little-no real grasp on sms/etc (due to not ever 'using' it before), it appears that my knowledge of GPRS is, well, none existent.

So, I've come here in hope that someone could tell me if there is such a way for a microcontroller to 'send data out' though, well, a 'sim card' via an sms message.

---

This has left me a little lost If i'm honest.

My project involves 'tracking' a vehicle (still working on finding a GPS module for that), and then sending the coordinates back to HQ at hourly intervals (via text message).

So, My obvious question is this: *What GPRS sim card module will allow me to do this?*

I read here, although the accepted answer there for a chip requires external power, and so is of no 'true' use to me as the whole unit needs to be powered and left 'unattended' for long hours at a time.

seeing as I also need to 'monitor current location' of the board, I am also in need to obtain a GPS location.

I was thinking that mobile phones have both of these cababilitys - is this done with a 'sim card module', or is there a way of 'one module does both - send an sms AND can also gain current GPS location'?

---

Sorry if this is too broad, but I'm certainly not 'gifted' in knowing too much about these technologies (esp. when all these acronyms use similar letters).

Any advice / input here would be very helpful.

# Answer
> 1 votes
I have a project that have the same idea that yours.

I used Ublox NEO-6M GPS Module for GPS tracking, the module cost in a range from $6 to $13 USD(it depends from where the seller ships, china o USA) in EBAY. You can connect it via UART.

For the internet I used a SIM800L V2.0 5V Wireless GSM GPRS MODULE, you can buy it from EBAY too, it cost no more than $10.00 USD, and you can connect to internet or send SMS using AT commands.

I used a combination of arduino and Raspberry pi zero, also I send the GPS data to a webserver (I pay 5dllr/month for a VPS) and then I can track using google maps.

Thats the basic information, you can use it to start working.

---
Tags: shields, gsm, gps
---


title: Record a duration of time as data

text:
# Question
Title: Record a duration of time as data
I have very little experience with the Arduino and am hoping that you may provide me with some helpful info.

I would like to build a device that records time spent on a project. I envision the main Uno with a switch, microSD breakout, and an LED to indicate its tracking your time. When setup the user could simply press the switch/button (light up the LED to show you're "working") and while you plug away on your day job the Uno will track the time between switch on and switch off. Then at the time the switch is turned off, have the Uno write a simple data file containing the total time spent on that activity.

I have a basic idea of what I need hardware wise, but am hoping to find insight to the backbone of software programming to make something like this begin to take shape.

# Answer
> 1 votes
There are two ways of doing this:

1. Using a Real Time Clock (RTC) chip, which you connect to your Arduino.
2. Using the `millis()` function of the Arduino.

Needless to say, they aren't completely the same in efficiency. An RTC is a dedicated chip for measuring time and is incredibly accurate. The `millis()` is not as accurate, but still pretty accurate.

So, it really depends on how accurate you want it to be. You can make `millis()` more accurate through code, which isn't something difficult. But an RTC always works fine and is always more accurate, if only by milliseconds. In general: need to time long durations, an RCT is probably better.

Regardless of the method you will use, you can convert the data into the desired format so it can be read easily when looking at the files on the SD card. So, for example: you can write code that simply checks how many hours fit in the saved time data, and after that you can check the minutes and even after that you can check for the last seconds. For this you're going to need modulo.

Here are some resources you might want to check out:

# Answer
> 0 votes
> An RTC is a dedicated chip for measuring time and is incredibly accurate.

its accuracy will depend on the crystals used. a temperature controlled one will be very accurate. But a regular one will just be as accurate as the crystal used, like a mcu.

> The millis() is not as accurate, but still pretty accurate.

stock millis() undercounts. however, that undercounting can be mitigated via code. for long durations, the undercounting can be practically (but not completely) eliminated.

---
Tags: time, software
---


# Question
Title: Can you use an input pin instead of ground in Arduino circuitry?
Beginner here: Would the circuit in the picture work or do input pins not absorb the energy as ground does? I know setting the pin as an input makes the direct 5V connection safe but maybe I'm mistaken. I'm trying to understand the nature of how these connections are made. Thank you in advance!

# Answer
> 4 votes
An input pin can only sense the voltage that is applied to it - whether it is above or below a pair of thresholds.

In your existing circuit when the button is not pressed the voltage sensed by the pin is 0V because it is connected to 0V (also known as Ground) through the resistor. When you press the button the input pin is connected directly to +5V, so the pin senses 5V.

If you remove the resistor or the connection to ground the pin can still sense 5V on it when the button connects it to 5V, but when you release the button the input pin then isn't connected to anything at all. It's not connected to 0V, so it can't sense what voltage is there - there simply isn't any voltage connected to it (no voltage isn't the same as 0V).

In this case the pin is said to be "floating". It's neither HIGH (5V) nor LOW (0V), it's just dangling around not knowing what it's doing.

If you want to get more technical and look at the mechanics of it, it's helpful to know that the gate of a MOSFET (which is what the input pin actually is) looks to all intents and purposes like a small capacitor. When you connect the input pin to +5V the capacitor is charged up (current flows into it from 5V to charge it). When you connect the input pin to 0V it discharges (current flows out of the capacitor down to 0V). When charged you have a HIGH and when discharged you have a LOW.

However when a charged capacitor has no connection it (for a certain amount of time, due to *self discharge*) keeps hold of its charge. So if you charge it with +5V and then disconnect it you will still get +5V on the capacitor. That is until it discharges through internal leakage currents.

Those leakage currents though are so small and the capacitor is so sensitive that the input pin acts like a radio antenna. It picks up *noise* from the surrounding area (electromagnetic waves) which can charge and discharge the capacitor pretty much at random. So at times you may see the input as HIGH and at other times as LOW, purely depending on chance. And the longer your wires the more noise it will pick up.

The worst source of noise is the 50/60Hz mains hum that is all around you. You can see this in reality if you graph the voltage on a disconnected ADC pin and bring your hand close to it - you act like a capacitively coupled antenna and you can see the mains waveform on your graph.

It's the same on a digital input pin, except that it converts it to a square wave as it passes the thresholds (you might like to look at *schmitt triggers* for more detail about how it does that).

So adding the pull down (or pull up if you prefer) resistor is critical to making the input pin see what you want it to see, and not just random noise.

Since the input is like a capacitor selecting the right value of resistor can be quite important in some situations. For a simple button like this there's nothing to worry about, but for something like a rotary encoder where the input signal may change more rapidly the resistor value does become more of a concern. Have too high a value and the gate will take too long to discharge (or charge if it's a pull up resistor). Too low and too much current could be wasted through the resistor when the button (or encoder) is active (potentially damaging the button if it's a low current sensitive device).

# Answer
> 1 votes
If you remove the ground wire, digital pin 2 will be left "floating" until the button is pressed, and this is not a good thing to do:

https://electronics.stackexchange.com/questions/83133/arduino-digitalread-reading-wrong

There is a way to eliminate the pull-down resistor and simplify the wiring by using pinMode(BUTTON\_PIN, INPUT\_PULLUP); in setup(). You would connect one "leg" of the N.O. momentary push button switch to ground and the other "leg" to Pin 2. You will still need to "debounce" the switch, and for that I recommend a library.

There is a link to a good library here: https://playground.arduino.cc/Code/Bounce.

The example sketch called bounce.ino is a good place to start.

---
Tags: arduino-uno, electronics, electricity
---


title: LCD is not showing any text

text:
# Question
Title: LCD is not showing any text
I'm using LCD QC1602A with a 10k potentiometer and changing contrast. It works well but the problem is that no text is appearing.

I'm using the LCD hello world examples and a few other examples. I tried reconnecting wires at least 5 times but every time it's the same problem. I connected it like this but the screen is not displaying any text at any contrast.

PS: It was showing white squares only in the top row, and now it's in both rows.

# Answer
> 2 votes
Two rows of white squares means that the driver chip has been successfully initialised to run in a 2x16 mode (it defaults to 1x16 which was the 1 row of squares you had originally).

So that means that you are configuring the display at least partially correctly.

You should adjust the pot so that you can just about see the squares. The squares are the background and the text would appear over them. If they are too bright you won't see the text. So adjust the contrast until you can just see that there are squares there.

If the wiring is correct and the code is correct then you should be able to see the text.

# Answer
> 0 votes
> It works well but the problem is that no text is appearing.

it works well and yet no text is appearing?

so there is or there isn't a problem?

> PS: It was showing white squares only in the top row, and now it's in both rows.

when correctly initialized, it should one row of blocks in the first row.

if it shows two rows of blocks, either it is not correctly initialized or the contrast is too much.

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