# Question
Title: Why does HC-SR04 return 0s in this sketch
I am building a robot with multiple sensors, abilities etc. Since I had a bug with a HC-SR04 rotated by a servo, I experimented in a different sketch. If the distance is less than 30cm, the servo turns left and right. Since I need continuous readings of other sensors, I cannot use delays so I used millis in order to keep time. The sensor worked correctly in a different sketch, but something in the full one conflicts with it.

```
#include <LiquidCrystal.h>
#include <Wire.h>
#include <RTClib.h>
#include <Servo.h>
#include <IRremote.h>

RTC_DS1307 rtc;

/*const int blue2 = 12;
const int blue1 = 11;
const int red1 = 10;
const int red2 = 9;
*/
Servo servo;

byte leds[4] = {8, 7, 6, 9};

const int STBY1=45;
const int ain11=47;
const int ain12=43;
const int aPWM1=2;
const int bin11=41;
const int bin12=40;
const int bPWM1=4;
const int STBY2 = 39;
const int ain21=33;
const int ain22=31;
const int aPWM2=5;
const int bin21=35;
const int bin22=37;
const int bPWM2=3;

const int piezo = 32;

const int flamePin = A7;

int flameState;

const int photoResistor = A1;

int photoState;

const int temp = A2;

float temperature;

int ledAnalog;

const int irGnd = 52;

const int irVcc = 50;

const int irSignal = 48;

decode_results results;

IRrecv irrecv(irSignal);

boolean manualLeds = false;

boolean ledsOn = false;

unsigned long counter;

unsigned long prevMillis = 0;

int piezoInterval = 200;

int drivingMode = 0;

boolean playPiezo=false;

#define trig 22
#define echo 24
long duration;
boolean turned150 = false;
int cm30, cm, cm150;
bool checkLeft = false;
boolean checkRight = false;
boolean mainPing = true;
unsigned long servoTimer = millis();

void setup(){
  Wire.begin();
  rtc.begin();
  pinMode(piezo, OUTPUT);
pinMode(STBY1, OUTPUT);
  pinMode(aPWM1, OUTPUT);
  pinMode(ain11, OUTPUT);
  pinMode(ain12, OUTPUT);
  pinMode(bPWM1, OUTPUT);
  pinMode(bin11, OUTPUT);
  pinMode(bin12, OUTPUT);

  pinMode(STBY2, OUTPUT);
  pinMode(aPWM2, OUTPUT);
  pinMode(ain21, OUTPUT);
  pinMode(ain22, OUTPUT);
  pinMode(bPWM2, OUTPUT);
  pinMode(bin21, OUTPUT);
  pinMode(bin22, OUTPUT);

 servo.attach(12);
 for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
    pinMode(leds[i], OUTPUT);
 }

  pinMode(flamePin, INPUT);
  pinMode(photoResistor, INPUT);
  pinMode(temp, INPUT);
  pinMode(irGnd, OUTPUT);
  digitalWrite(irGnd, LOW);
  pinMode(irVcc, OUTPUT);
  digitalWrite(irVcc, HIGH);
  pinMode(irSignal, INPUT);
 Serial.begin(9600);
  irrecv.enableIRIn();
  digitalWrite(STBY1, LOW);
    digitalWrite(STBY2, LOW);
servo.write(90);
delay(200);
}

void loop(){

 counter=millis();
 //Serial.print("Millis1: ");
 //Serial.println(millis());
 if(irrecv.decode(&results)){
    translateIR();
    irrecv.resume();
  }
 // Serial.print("Millis2: ");
 //Serial.println(millis());
if(drivingMode == 1){
   if(((counter-servoTimer) >= 150) && mainPing){
    ping();
    cm=duration/29.1/2;
    Serial.println(cm);
    counter=millis();
    servoTimer=counter;
  }
  if((cm<30) && mainPing){

    mainPing=false;
    checkRight = true;
    counter=millis();
    servoTimer=millis();
    servo.write(150);
    cm=30;

  }
  if(checkRight && !checkLeft && ((counter-servoTimer) >= 170)){

    ping();
    checkLeft=true;
    cm150 = duration/29.1/2;
    counter=millis();
    servoTimer=millis();
    servo.write(50);
  }
  if(checkRight && checkLeft && ((counter-servoTimer) >= 340)){
  checkRight=false;
  checkLeft=false;
  mainPing=true;
  ping();
  cm30 = duration/29.1/2;
  counter=millis();
  servoTimer=millis();
  servo.write(90);

  }

 }

//getTime();
//existsFire();
/*if(!manualLeds){
readPhoto();
}*/

}

void readPhoto(){

  photoState = analogRead(photoResistor);
  if(photoState>600){
    ledAnalog=0;
  }
  else if(photoState<300){
    ledAnalog=255;
  }
  else{
    ledAnalog = 150 - photoState/4;
  }
  for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
  analogWrite(leds[x], ledAnalog);
  }

}

void existsFire(){
flameState = analogRead(flamePin);
Serial.println(flameState);
if(flameState <= 50){
  static boolean playingBuzzer = true;
  if(counter - prevMillis > piezoInterval){

     prevMillis = counter;
     playingBuzzer=!playingBuzzer;

  }
  if(playingBuzzer){

    digitalWrite(piezo, HIGH);

  }
  else{
    digitalWrite(piezo, LOW);
  }

}
else if(!playPiezo){
  digitalWrite(piezo, LOW);
}
else if(playPiezo){
  digitalWrite(piezo, HIGH);
}

}

void checkTemp(){

  temperature = ((analogRead(temp) / 1024.0 * 5.0) - .5) * 100;
  Serial.println(temperature);

}
void ping(){

    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration = pulseIn(echo, HIGH);

}
void getTime(){

  DateTime now = rtc.now();

  Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
}
void forward(){
digitalWrite(STBY1, HIGH);
digitalWrite(ain11, HIGH);
digitalWrite(ain12, LOW);
analogWrite(aPWM1, 255);

digitalWrite(bin11, LOW);
digitalWrite(bin12, HIGH);
analogWrite(bPWM1, 234);

digitalWrite(STBY2, HIGH);
digitalWrite(ain21, LOW);
digitalWrite(ain22, HIGH);
analogWrite(aPWM2, 255);

digitalWrite(bin21, LOW);
digitalWrite(bin22, HIGH);
analogWrite(bPWM2, 234);
}
void backward(){

digitalWrite(STBY1, HIGH);
digitalWrite(ain11, LOW);
digitalWrite(ain12, HIGH);
analogWrite(aPWM1, 255);

digitalWrite(bin11, HIGH);
digitalWrite(bin12, LOW);
analogWrite(bPWM1, 235);

digitalWrite(STBY2, HIGH);
digitalWrite(ain21, HIGH);
digitalWrite(ain22, LOW);
analogWrite(aPWM2, 255);

digitalWrite(bin21, HIGH);
digitalWrite(bin22, LOW);
analogWrite(bPWM2, 235);

}
void left(){

digitalWrite(STBY1, HIGH);
digitalWrite(ain11, HIGH);
digitalWrite(ain12, LOW);
analogWrite(aPWM1, 255);

digitalWrite(bin11, HIGH);
digitalWrite(bin12, LOW);
analogWrite(bPWM1, 255);

digitalWrite(STBY2, HIGH);
digitalWrite(ain21, LOW);
digitalWrite(ain22, HIGH);
analogWrite(aPWM2, 255);

digitalWrite(bin21, HIGH);
digitalWrite(bin22, LOW);
analogWrite(bPWM2, 255);

}
void right(){
digitalWrite(STBY1, HIGH);
digitalWrite(ain11, LOW);
digitalWrite(ain12, HIGH);
analogWrite(aPWM1, 255);

digitalWrite(bin11, LOW);
digitalWrite(bin12, HIGH);
analogWrite(bPWM1, 255);

digitalWrite(STBY2, HIGH);
digitalWrite(ain21, HIGH);
digitalWrite(ain22, LOW);
analogWrite(aPWM2, 255);

digitalWrite(bin21, LOW);
digitalWrite(bin22, HIGH);
analogWrite(bPWM2, 255);

}
void brake(){

digitalWrite(STBY1, LOW);
digitalWrite(ain11, LOW);
digitalWrite(ain12, LOW);
analogWrite(aPWM1, 0);

digitalWrite(bin11, LOW);
digitalWrite(bin12, LOW);
analogWrite(bPWM1, 0);

digitalWrite(STBY2, LOW);
digitalWrite(ain21, LOW);
digitalWrite(ain22, LOW);
analogWrite(aPWM2, 0);

digitalWrite(bin21, LOW);
digitalWrite(bin22, LOW);
analogWrite(bPWM2, 0);

}
void translateIR(){
//Serial.println(results.value, HEX);
switch(results.value){
case 0xFF02FD:
case 0x20DF22DD:
//stop(ok)
if(drivingMode==0){
brake();
//Serial.println("brake");

}
break;
case 0xFF629D:
case 0x20DF02FD:
//forward
if(drivingMode==0){
forward();
//Serial.println("forward");
}
break;
case 0x20DF827D:
case 0xFFA857:
//back
if(drivingMode==0){
backward();
//Serial.println("back");

}
break;
case 0xFF22DD:
case 0x20DFE01F:
//left
if(drivingMode==0){
left();
//Serial.println("left");
}
break;
case 0x20DF609F:
case 0xFFC23D:
//right
if(drivingMode==0){
right();
//Serial.println("right");

}
break;
case 0xFF6897:
case 0x20DF8877:
if(drivingMode==0){
  brake();
  drivingMode=1;
}
else{
  brake();
  servo.write(90);
  drivingMode=0;
}
//1(switch driving mode)
break;
case 0xFF9867:
case 0x20DF48B7:
//2(switch led mode)
if(!manualLeds){
manualLeds=true;
    for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
  digitalWrite(leds[x], LOW);
  }
}
else{
manualLeds=false;
}

break;
case 0xFFB04F:
case 0x20DFC837:
if(manualLeds){
  if(!ledsOn){
    for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
  digitalWrite(leds[x], HIGH);
  }

  ledsOn=true;
  }
  else{
       for(int x = 0;x<sizeof(leds)/sizeof(leds[0]);x++){
  digitalWrite(leds[x], LOW);
  }
  ledsOn=false;
  }
}
//3(toggle leds if mode is on)
break;
case 0xFF30CF:
case 0x20DF28D7:
//4(play sound)
playPiezo = !playPiezo;

}

}

```

EDIT 2:

I decided to see what will happen if I start removing code. I removed most of the code that I did not need for this experiment. After the removal, the issue persisted. The sensor is still giving me 0s. This is all the code that was left after I removed stuff:

```
#include <Servo.h>

//RTC_DS1307 rtc;

/*const int blue2 = 12;
const int blue1 = 11;
const int red1 = 10;
const int red2 = 9;
*/
Servo servo;

unsigned long counter;

unsigned long prevMillis = 0;

int piezoInterval = 200;

int drivingMode = 0;

boolean playPiezo=false;

#define trig 22
#define echo 24
long duration;
boolean turned150 = false;
int cm30, cm, cm150;
bool checkLeft = false;
boolean checkRight = false;
boolean mainPing = true;
unsigned long servoTimer = millis();

void setup(){

 servo.attach(12);
/* for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
    pinMode(leds[i], OUTPUT);
 }
*/
 Serial.begin(9600);

servo.write(90);
delay(200);
}

void loop(){

 counter=millis();
 //Serial.print("Millis1: ");
 //Serial.println(millis());
/* if(irrecv.decode(&results)){
    translateIR();
    irrecv.resume();
  }*/
//  Serial.print("Millis2: ");

if(drivingMode == 0){
   if(((counter-servoTimer) >= 150) && mainPing){
    ping();
    cm=duration/29.1/2;
    Serial.println(cm);
    counter=millis();
    servoTimer=counter;
  }
  if((cm<30) && mainPing){

    mainPing=false;
    checkRight = true;
    counter=millis();
    servoTimer=millis();
    servo.write(150);
    cm=30;

  }
  if(checkRight && !checkLeft && ((counter-servoTimer) >= 170)){

    ping();
    checkLeft=true;
    cm150 = duration/29.1/2;
    counter=millis();
    servoTimer=millis();
    servo.write(50);
  }
  if(checkRight && checkLeft && ((counter-servoTimer) >= 340)){
  checkRight=false;
  checkLeft=false;
  mainPing=true;
  ping();
  cm30 = duration/29.1/2;
  counter=millis();
  servoTimer=millis();
  servo.write(90);

  }

 }

//getTime();
//existsFire();
/*if(!manualLeds){
readPhoto();
}*/

delay(2);
}

//}
void ping(){

    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration = pulseIn(echo, HIGH, 24000L);

}

```

Maybe this means that the issue is within this remaining code. Of course I will need all of the code that I removed for the final project, but I was just trying to debug.

I made my code a lot more concise since the posted code draft, but the ultrasonic sensor still gives me 0s. I do not understand what can affect its performance as it works fine in my other sketch.

I tried connecting the sensor to an external 5 volt power source and the same thing happened. The reason for the issue is not because if my power source.

I used to have a small delay at the end of my code and I removed that in order to make it run faster. Since pulseIn is blocking for 24ms, the delays do not affect it and it should work normally. But it does not.

Also, the sensor is giving 0s not because the target is too far away. Even if I put my hand close, it still gives 0s. If I make the cm equal 400 if the duration equals 0, the cm are always 400 regardless of the distance from the sensor.

# Answer
In the `setup()` function add a `setPin(echo, INPUT)` statement.

**UPDATE**

Have you checked the wiring? A loose connection of either the `trig` or `echo` pins would cause this behavior.

I know it might seem obvious, but double checking continuity between the Arduino pins and the HC-SR04 module with a basic multimeter (while your board is not powered) is not going to hurt, right?
> 1 votes

# Answer
`pulseIn()` may block up to **1 second** (by default), which would happen everytime the **HC-SR04** receives no echo, which might be the case if ultrasounds do not get properly reflected on a flat surface or if the nearest echoing surface is over ~4 meters away from it.

In this situation, not only would `pulseIn` block for one second, but it would also return `0` to indicate the pin never changed level during that time (which can explain the **0cm distance** you calculated).

Since the **HC-SR04** range is maximum 4 meters, the max ultrasound distance echoed should be then less than 8 meters. Under normal atmospheric conditions, sound propagates at **~340m/s**, that means in the worst case, i.e. an obstacle found 4 meters away, the sound roundtrip should take less than **8/340s**, i.e. **~24ms** rounded up.

This shows it is pointless to have `pulseIn` wait for 1 second, where 24ms would be enough. To tell `pulseIn` to use a shorter timeout, just pass it an extra argument:

```
duration = pulseIn(echo, HIGH, 24000L);

```

Note that timeout must be expressed in **us**.

Then, in other parts of your code, before using `duration`, you should check that it is not `0` (which means no obstacle found less than 4 meters away), for example you might consider in this case the distance is 4 meters (or anything larger).

E.g. you could replace:

```
cm150 = duration/29.1/2;

```

with:

```
cm150 = duration == 0 ? 400 : duration/29.1/2;

```

Since this calculation is found several times you should probably create a function for it, that would improve code maintainability and maybe code size as well.
> 3 votes

# Answer
> Why does the same block of code act differently in different sketches?

There are different interrupt sources in the sketches that may affect pulseIn(). Try using a more advanced method to measure the pulse width such as Timer Capture.

Cheers!
> 2 votes

---
Tags: arduino-mega, servo, sketch, sketch-size, hc-sr04
---


# Question
Title: AnalogRead(0) always returns 0 on RFduino
I'm using RFduino to do analogRead at pin 2 and pin 0. Pin 2 works perfectly, and I got the result. However, for pin 0 it returns all zero.

```
#include <RFduinoBLE.h>

static const int topPin = 2;
static const int bottomPin = 1;

int top;
int bottom;

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

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

    bottom = analogRead(bottomPin);
    top = analogRead(topPin);

    Serial.print(top);
    Serial.print(" ");
    Serial.print(bottom);
    Serial.print("\n");
}

```

I double checked the wires and it's OK. I measured the voltage across pin 0 and it's 3.3V. How do I fix this problem? There's no shortage between pin 0 and 3.3V.

# Answer
Without RFDuino specs handy, I'm guessing - but I think it's likely - that the A/D converter gets shut down in an ultra low power sleep and requires some amount of time to wake up. The mis-reading pin, pin 0, is the one your sketch reads immediately on waking. That read call probably takes long enough that the A/D wakes up by the time your read pin 2 so it gives a better reading.

Try switching the order in which you read the pins and see if pin 2 mis-reads if you try to read it immediately after waking. If it does, the cure may be as simple as a 10-100 uSec delay between waking and trying to read any analog data. I just pulled that number out of the air; you might start with a couple of milliseconds and see how low you can make it before you start to see errors, then double that amount.
> 1 votes

# Answer
I couldn't find an usable datasheet for the RFduino, seems like a very poorly documented board. But I found an enlightening comment in the source code of the RFduino library:

> Only pins 1-6 is avaliable \[sic\] for using as ADC inputs

If you read the source, it is clear that calling `analogRead()` on an inappropriate pin is supposed to return 0.
> 0 votes

---
Tags: analogread
---


title: Calibrate motors using arduino

text:
# Question
Title: Calibrate motors using arduino
I'm trying to create a car that's being controlled by an Arduino. I'm using the following chasis: http://www.aliexpress.com/item-img/New-2WD-car-chassis-DC-gear-motor-wheels-easy-assembly-and-expansion-car-toys-robot-toys/32310649967.html

And L298N motor driver.

The problem is it's hard to make the car go straight. Giving the same PWM value to the motors still makes them spin in different speeds, trying to calibrate the value is hard and every time I recharge my batteries the value changes.

What are my options on making the car go straight when I want (well, sometimes I'll want to turn it around of course)?

I've thought about using an encoder but I wish to avoid that since it will complicate the whole project, is there any other viable option? and even when using an encoder, Does it means I will need to keep track all the time and always adjust the motors value continuously? is there some built-in library for that?

Thanks in advance!

# Answer
I used a simple optical encoder and the little disks that came with my kit. The encoders cost \< £1 for 2 of them.

Failing that use an accelerometer and measure the lateral motion, should also cost about £1.
> 1 votes

# Answer
Modern tiny $20 toy quadcopters use a magnetometer to maintain a steady heading. Duplicating that effect could be cheaper and more reliable than dual encoders. On certain surfaces, like carpet, even perfect encoding with perfect voltage and wheels can't guarantee maintaining the heading.

One viable option might be to drive one wheel with your control system, drive the other wheel to maintain the magnetometer heading, and then steer by adjusting the target heading.
> 0 votes

---
Tags: motor, arduino-motor-shield
---


title: code for automatic door

text:
# Question
Title: code for automatic door
I want it running as a normal automatic door so both sensors work as a separate activate. The only problem I've seen is that the servo remains active waiting for another high read and you can hear the buzz of it trying to keep position.

It didn't used to do this before the code change. While its open, if it reads another high it will remember and rerun the open wait close after it closes.

Eg. The door activates and while open 3 people walk thru so when the door closes it will then run 3 more times with out anyone being there.

Edit: Code changed

```
    #include <Servo.h>

  Servo myservo;

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

  //amount of time we give the sensor to calibrate(10-60 secs according to       the datasheet)

  int calibrationTime = 30;

  int pirPin = 12; //digital pin connected to the PIR's output
  int pirPos = 13; //connects to the PIR's 5V pin
  int pirPin2 = 6; //digital pin connected to the PIR's output
  int pirPos2 = 10; //connects to the PIR's 5V pin
  const int position_closed = 0;      // door closed position [deg]
  const int position_open = 90;      // door open position [deg]
  const uint32_t delay_step = 15;     // delay between servo steps [ms]
  const uint32_t delay_open = 60000;  // how long the door stays open [ms]

  void setup()

  {
      myservo.attach(4); //attaches servo to pin 4
Serial.begin(9600); //begins serial communication
pinMode(pirPin, INPUT);
pinMode(pirPos, OUTPUT);
digitalWrite(pirPos, HIGH);
pinMode(pirPin2, INPUT);
pinMode(pirPos2, OUTPUT);
digitalWrite(pirPos2, HIGH);

//give the sensor time to calibrate
Serial.println("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++)
{
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
}
Serial.println();
Serial.println("done");
  }

  void loop()
  {
static enum { CLOSED, OPENING, OPEN, CLOSING } state;
static int position;          // door position
static uint32_t last_change;  // last time state or position changed
uint32_t now = millis();

// When presence is detected, switch to the OPENING state.
if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
        && state != OPENING) {
    state = OPENING;
    last_change = now;
}
else switch (state) {
    case CLOSED:
        break;
    case OPENING:
        if (position == position_open) {
            state = OPEN;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(++position);
            last_change = now;
        }
        break;
    case OPEN:
        if (now - last_change >= delay_open) {
            state = CLOSING;
            last_change = now;
        }
        break;
    case CLOSING:
        if (position == position_closed) {
            state = CLOSED;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(--position);
            last_change = now;
        }
        break;
      }
  }

```

# Answer
KennetRunner already explained what is wrong with your code. Here I will try to give advice on the proper way to implement the automatic door.

First thing is to get rid of `delay()`. While your program is inside a call to `delay()`, it can do *nothing* but wait until the delay is over. This is acceptable if the program has only one single task to perform, like blinking an LED. As soon as you have two tasks, `delay()` is a nuisance because it blocks *all* the tasks.

Case in hand: after keeping the door open for one minute, your program would close it, irrespective of whether there is someone in the way. It could not see the person come because it was busy delaying the closing of the door.

The standard way to get rid of `delay()` is to never wait inside `loop()`. Instead, if there is something to do *right now*, do it; if not, just don't do it, but do not wait. Pseudo-code:

```
void loop()
{
    if (it_is_time_to_do_foo()) {
        do_foo();
    }
    if (it_is_time_to_do_bar()) {
        do_bar();
    }
    /// etc...
}

```

You would use the millis() function to know when the time has come to do some task, as explained in the Blink Without Delay Arduino tutorial. This is really the second tutorial every Arduino user should read, right after learning how to blink an LED.

Next, you have to learn how to implement a finite state machine. I recommend the Finite State Machine tutorial by Majenko, a regular contributor to this site.

Your problem can be very naturally mapped into a machine with four states: CLOSED, OPENING, OPEN and CLOSING. You then write the rules about what to do in each state, and when to transition to another state. For example:

* when the door is CLOSED
    + if the sensors detect someone, transition to the OPENING state
* when the door is OPENING
    + if it's time to move the servo by one step, do it
    + if we have already moved all the way to the open position, we can say the door is OPEN now
* when the door is OPEN
    + if it's time to close it, transition to the CLOSING state
    + if the sensors detect someone, reset the timer \<\<\<\< note this!
* when the door is CLOSING
    + if the sensors detect someone, transition to the OPENING state
    + if it's time to move the servo by one step, do it
    + if we have already moved all the way to the closed position, we say the door is now CLOSED

A few things to note here:

* See the line marked by “\<\<\<\<”: this will prevent the aforementioned problem of the door closing into someone.
* The first rule for the CLOSING state follows from a similar rationale.
* I made up some of these rules, as the job of your program was not completely specified in your question. Feel free to change those rules to your taste.

And here is my proposed implementation. **Warning**: not tested. As usual with FSMs, it is based on a big `switch`/`case` statement going through all the possible states. However, to avoid repeating rules, I factored the “if there is someone, start OPENING” rule out of the `switch`. I also folded “if there is someone, reset the timer” into the same rule.

```
const int position_closed = 0;      // door closed position [deg]
const int position_open = 180;      // door open position [deg]
const uint32_t delay_step = 15;     // delay between servo steps [ms]
const uint32_t delay_open = 60000;  // how long the door stays open [ms]

void loop()
{
    static enum { CLOSED, OPENING, OPEN, CLOSING } state;
    static int position;          // door position
    static uint32_t last_change;  // last time state or position changed
    uint32_t now = millis();

    // When presence is detected, switch to the OPENING state.
    if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
            && state != OPENING) {
        state = OPENING;
        last_change = now;
    }
    else switch (state) {
        case CLOSED:
            break;
        case OPENING:
            if (position == position_open) {
                state = OPEN;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(++position);
                last_change = now;
            }
            break;
        case OPEN:
            if (now - last_change >= delay_open) {
                state = CLOSING;
                last_change = now;
            }
            break;
        case CLOSING:
            if (position == position_closed) {
                state = CLOSED;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(--position);
                last_change = now;
            }
            break;
    }
}

```
> 2 votes

# Answer
Your code is looping 180 times, **EACH TIME** it :

* Sets the servo to 180
* Delays for 2 seconds
* Sweeps the servo from 180 to 90 in single steps
* Sets the servo to 90
* Delays for 60 seconds
* Sweeps the servo from 90 to 180 in single steps

**So you code will take *more than 3 hours* to complete.**

I think you would be better pulling the code that moves the servo out into its own function: Something like:

```
void moveServo(servoStart, servoEnd, servoStep, servoInterval)
{
  for(int servoPos = servoStart; servoStart < servoEnd; servoStep)
  {
     myservo.write(servoPos);
     delay(servoInterval);
  }
}

```

then simply call it from your main loop, like this:

```
void loop()
{

    if((digitalRead(pirPin) == HIGH) && (digitalRead(pirPin2) == HIGH))
    {
      moveServo(0, 180, 1, 15);
      delay(2000);
      moveServo(180, 90, -1, 15);
      delay(60000);
      moveServo(90, 0, -1, 15);
    }
}

```
> 1 votes

---
Tags: sensors, c++, servo, home-automation
---


# Question
Title: Arduino is freezing during Serial.Print() while passing a char array
This problem is on an Arduino Due. I am trying to populate a char array buffer that is receiving information over a serial port. I am reading the information off of the serial port and storing it into a buffer array and passing it back to the original function call.

First is the code that initializes the buffer and writes the data that the Serial requires in order to issue a response. This function compares many types of expected responses (`uint32_t expect`) and returns a confirmation as an `int`.

```
//Receive a cmd to send over serial and expect a certain response
int SendCommand(char * cmd, uint32_t expect){
  int cmdSuccess = 0, j=0;
  char buffer[500];
  memset(&buffer,0,sizeof(buffer)); //0 out the buffer
  Serial3.print(F(cmd));
  delay(500);

  Response(buffer);

  if (expect == EXPECT_OK){
    for(int i=0;i<sizeof(RESP_OK);i++){
      if(buffer[i]==RESP_OK[i]){ //RESP_OK is an example of a response of length 6
        j++;
    }
  }
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }
  else{return 0;}
  delete [] buffer;
}

void Response(char buffer[500])
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Data will be coming across serial3
  {
    char data = Serial3.read();
    buffer[index]=data;
    index++;
  }
    count++;
    delay(100);
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
  }

}

```

Edit: fixed the braces.

Right now, this code is hanging at the last part of `Response` right before `break;`. Am I having memory issues by the time it reaches the `println` at the end? That last `println` was actually working until I began passing the buffer as a pointer and not returning it a `char*` and declaring `void Response` as `char* Response`. But the problem with this approach was that the `buffer` would reduce to `sizeof(buffer) = 4` and would strip off the rest of the information when returned.

**Edit:** As Matt suggested down below, I declared a `static const size_t bufferSize` and pass it into the `Response()` call as well as passing in `buffer` as `char*`. Then I reset the buffer size by `buffer = (char*)malloc(bufferSize)`.

What I still don't understand curious is the `sizeof(buffer)` after `Response` which is returning 4. However, 6 characters are stored into the array during `Response`. I've changed the pointer call to `Response(char* buffer, const int size)` with the following:

```
  if(index<size){
  buffer[index]=data;
  index++;
  }
  else{Serial.print(F("Buffer length exceeded!"));}

```

Thanks so much for your time!

# Answer
Sorry, but there are quite a few issues with your code any of which may be contributing to your problem.

1. `memset(&buffer,0,sizeof(buffer)); //0 out the buffer` you are taking the address of a pointer and passing it to memset(). `buffer` is already a pointer of type `char*`. Its working, because address of the pointer is the same address as buffer\[0\], but it is wrong and won't always work.
2. `Serial3.print(F(cmd));` I have never used the F macro, but my understanding is it tells the compiler to store the string in flash memory. cmd is a variable on the stack, a parameter to the function, so my guess would be the compiler is ignoring the F macro.
3. `500` using a literal value in more than one place is opening you up to problems. I think you should declare `static const size_t BufferSize = 500;`
4. `void Response(char buffer[500])` It would be better to pass in a pointer to a char and the size as the parameter, `(const char* pBuffer, const int& size)` you can treat it the same within your function or you could pass a pointer to the next available item and then return the updated pointer.
5. 1for(int i=0;i strlen(buffer))\` then buffer can't contain RESP\_OK (its quicker too).

Also the Response function won't compile, because you have too many closing braces (I assume its a copy and paste error). This is the cause of you code hanging `if(Serial3.available())` is inside a while(1) and there is no way of breaking out. So if you just fix that you code will run.
> 1 votes

# Answer
I am having difficulties to follow your code due to indentation and additional braces which don't pair up correctly, but to me you are breaking out of the `if(count == 50)` statement through to the whole function as the `while(1)` statement was already closed.
> 0 votes

# Answer
Ok, thanks to the responses in this thread, I believe I have the solved the problem. There is a problem using `sizeof(char*)` when passing through arrays, so I used `strlen(char*)` instead. This code properly stores the messages of various sizes coming off of `Serial3` and correctly compares them to the expected responses. The F() macro in Arduino is very useful in keeping the buffer free and, in general, I use it to print constants during debugging.

```
int SendCommand(char * cmd, bool resp_type, uint32_t expect){
delay(500);
  int cmdSuccess = 0, j=0, msgSize = 0;
  char * buffer;
  Serial3.print(F(cmd));
  Serial.print(F(cmd)); //Print to serial for debug purposes only
  delay(500);
  buffer = (char *)malloc(bufferSize);
  msgSize = Response(buffer, bufferSize);

  Serial.println("Buffer is: ");
  if (expect == EXPECT_OK){
    for(int i=0;i<msgSize;i++){
      if(buffer[i]==RESP_OK[i]){
        Serial.print(buffer[i],HEX);
        j++;
      }
    }
    Serial.print("\n");
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }

  return cmdSuccess;
}

int Response(char* buffer, const int size)
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Message will be coming across serial3
  {
    char data = Serial3.read();
      if(index<size){
        buffer[index]=data;
        index++;
      }
      else{Serial.print(F("Buffer length exceeded!"));}
  }
    count++;
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
    }
  } return index;
}

```
> 0 votes

---
Tags: arduino-due, array
---


# Question
Title: Trying to Serial.write RAW code properly
I have a SIM800L Module connected to my arduino Nano. I want to open a TCP connection from the sim800l module to my own server and send a text string. The connection is working however I am not able to send text, because there is an issue with the arduino write() function I think... Below is the code I am trying to execute. Right after the message is sent, I need to send the stop value 0x1A (byte 26) to tell the sim800l module that the message end is reached and to send out the message. My problem is, that it is not working in the arduino IDE and I don't know why.

My arduino code:

```
#include <SoftwareSerial.h>

#define SIM800_TX_PIN 8
#define SIM800_RX_PIN 7

SoftwareSerial serialSIM800(SIM800_TX_PIN, SIM800_RX_PIN);

void setup() {

serialSIM800.println("AT");
delay(500);

serialSIM800.println("AT+CIPSTART=\"TCP\",\"IP-ADRESS-HERE\",\"9999\""); //connection works
delay(500);

serialSIM800.println("AT+CIPSEND");
delay(500);

serialSIM800.print("TEXT MESSAGE HERE");
delay(500);

serialSIM800.write(26);
delay(500);

serialSIM800.println("AT+CIPCLOSE");
delay(500);
}

void loop() {
  //Empty
}

```

On my server I am running this python script that opens a socket:

```
import socket
import sys

HOST = ''   # all available interfaces
PORT = 9999 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
  s.bind((HOST, PORT))
except socket.error as msg:
  print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
  sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#now keep talking with the client
while 1:
  #wait to accept a connection - blocking call
  conn, addr = s.accept()
  print 'Connected with ' + addr[0] + ':' + str(addr[1])
  data = conn.recv(1024)
  print len(data)
  print data
s.close()

```

Once I execute this, I see the connection is working because "Connected with IP:PORT" is printed on my console. However right after that "len(data)" is printed (0) and "data" is an empty string. I even upped the delay from 500 to 5000, still same result.

However, if I leave the arduino IDE and send the message using the program "HTerm", it is working! In HTerm I typed in the text message and hit enter. After that I switched from ascii to hex mode (there is a checkbox) and I just typed 1A and sent it. That way it worked. Anybody can help me? Why is it not working @arduino?

# Answer
Replace `serialSIM800.write(26);` with `serialSIM800.write(0x1A);`, also change `serialSIM800.print("TEXT MESSAGE HERE");` with a `println` or add a carriage return `\n`.
> 0 votes

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


# Question
Title: Performance tuning PORTB manipulation - mask
I have the following snippet that seems to be taking a total of 6 CPU cycles per invocation.

Can I speed this up somehow? `x` is a byte with the 3 lowest bits set.

```
#define SET_COLOR(x) PORTB = (PORTB & ~(7)) | x

```

# Answer
4 cycles:

```
IN Rd,PORTB
CBR Rd,7
ORI Rd,x
OUT PORTB,Rd

```

Translation into proper GCC inline assembly syntax is left as an exercise for the reader.
> 2 votes

---
Tags: arduino-uno, port-mapping, performance
---


# Question
Title: Voltage increasing when charging a battery using arduino
I am making a solar charge controller using Arduino. So for starting, I thought I should calibrate the voltage so that I am able to read the exact voltage of battery and solar charger. For testing purposes, I do not have any solar panel, so I used a 12V power supply and set its output voltage to 13.56. I used the following calculations for getting exact voltage:

```
float solarData = 0;
float batData = 0;
float batScale = 0;
float solarScale = 0;
float batPinVolt = 0;
float solPinVolt = 0;
float batVolt = 0;
float solVolt = 0;

Vcc = readVcc()/1000.00;    //getting the exact voltage of arduino
Serial.print(Vcc);
solarScale = analogRead(A0);  //reading solar analog data
batScale = analogRead(A1);    //reading battery analog data
solPinVolt = (solarScale/1024.0) * Vcc;
solVolt = solPinVolt * (9.80 + 2.168)/2.168;    //I used 10k & 2.2k so entered their exact value
batPinVolt = (batScale/1024.0) * Vcc;
batVolt = batPinVolt * (9.80 + 2.168)/2.168;

```

Initially, I faced few problem regarding the exact voltage of the Arduino which I used as a reference voltage to calculate voltage. But then I found a solution here. So below is the code which calculate the voltage of Arduino

```
long readVcc()
{
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
 }

```

Now when I uploaded the code, I got the exact values of the voltages.

Now I wrote a logic where if the battery voltage is less than 12V then start charging until it is above 13V. Following is the code:

```
if((solVolt > batVolt)&& ( batVolt <= 12.00 ))
{
digitalWrite(chargePin,HIGH);  //enable charging
digitalWrite(loadPin,LOW);     //load off
}
else if((solVolt > batVolt)&&(batVolt > 12.00)&& (batVolt <= 13.00 ))
{
 digitalWrite(chargePin,HIGH);   //enable chargin
 digitalWrite(loadPin,LOW);      //load off
}
// // shut down when battery is fully charged or when sunlight is not enough
else if ((batVolt > 13.00) or (solVolt < batVolt))
{
 digitalWrite(chargePin,LOW);    //disable charging
 digitalWrite(loadPin,HIGH);     //load on
}

```

But when I uploaded the code, the Arduino started showing wrong values of the voltages. Power supply was set to 13.5, but it showed 13.15 and battery voltage was 11.8, but it showed 12.7.

Now due to this what exactly happened was it started charging so the value of battery voltage 12.7 (which is wrong) started increasing. When it was above 13V, Arduino turned off the `chargePin`. So when the `chargePin` is low, it shows the exact battery voltage which is low so it again started charging it and this loop keeps on going. This is all because of the wrong values of voltages. Following is the schematic:

I am following the article I found on Instructables. (cannot post more links due to reputation). I want to know why there is change in voltage. Can anyone please help me on what I am doing wrong.

# Answer
In order to charge a battery you have to apply a voltage to the battery terminals that is higher than the batteries own internal voltage. That's pretty much the definition of charging a battery.

Basically you're trying to do the impossible, you can't measure the batteries off charge voltage while charging it because as soon as you start charging the voltage at that point changes.

When charging your supply is 3.5V and your supply measurement is 13.15. That means you're loosing 0.35V in battery cables and F1. The battery voltage is 12.7V so that's 0.45V loss in D1 and Q1.

That first loss seems too high and the second one too low, D1 should drop typically drop 0.58V, so you may have some resistor tolerance or noisy reading issues. The total voltage drop seems reasonable but the split looks wrong.

The best solution to what your are trying to do is to measure the charge current.

Move D1 to the other side of R1 so there is no diode drop between your two voltage measurements and add a small resistor in series where D1 used to be. The difference between the two measured voltages and the resistance between those points now tells you the charge current. Stop charging when the current drops below a certain threshold. Larger resistors make it easier to measure accurately but have an obvious efficiency hit, make sure you check the resistors power rating.

You may be able to avoid adding the resistor and simply use the on resistance of Q1 as your resistor. This will be a little variable between devices so it's not suitable for mass production but for a one off it should be good enough as long as it's not too small for you to measure the current accurately.

One further note: With a supply of 13.5V you will never get the battery to 13V. You have a diode in there with a 0.6V drop so the highest you could get is 12.9V. On the plus side this means you can keep charging until the current drops to 0 with no risk of overcharging. Or alternatively switch D1 for a schottky diode with a drop of around 0.2V
> 0 votes

---
Tags: arduino-uno, voltage-level
---


title: Coin Acceptor CH-925 Pulse

text:
# Question
Title: Coin Acceptor CH-925 Pulse
I got a problem where pulse voltage from acceptor is about 20mV. How can I solve my problem? and I can't detect the pulse using arduino uno. please any one can help ?

# Answer
From this Amazon review:

> There are 'live' (12V), 'ground' and 'signal' wires coming out of the back. Live and ground are pretty self-explanatory, and need to be connected to a 12V supply - I bought a simple 1A DC one. The final wire says 'signal', and needs to be connected to your circuit as input into a GPIO pin in the case of a raspberry pi. It produces a pulsing 5V signal (Why not tell us it will be 5V somewhere in the documentation? Luckily I have a multimeter) as a way of encoding which type of coin it has encountered. However, raspberry pi's only want 3.3V signals as inputs, so you'll be wanting to make a voltage divider (With a couple of resistors - I used 33k and 18k) to safely bring that 5V pulse down to 3.3V. (http://en.wikipedia.org/wiki/Voltage\_divider) You'll also want to connect the ground from the device to a ground on your Raspberry Pi, or the signal won't work. I did this by splicing the ground cable from the power supply so that it has 2 ends - 1 for the power supply to the unit, and one for the unit to the Raspberry Pi Circuit.

It seems that a 5v pulse is the expected output. How are you measuring the output? You'll need a 'scope rather than a multimeter measuring voltage...

Anyway, I would not try to 'amplify' the signal, I would look to check the connections are correct and if that's not the issue, I would return the unit as defective.
> 1 votes

---
Tags: arduino-uno
---


title: 7-segment display code

text:
# Question
Title: 7-segment display code
What is the meaning of `BitSet = bitRead(numeral[number], segment);`?

```
const byte numeral[10] = {
  //ABCDEFG /dp
  B11111100,  // 0
  B01100000,  // 1
  B11011010,  // 2
  B11110010,  // 3
  B01100110,  // 4
  B10110110,  // 5
  B00111110,  // 6
  B11100000,  // 7
  B11111110,  // 8
  B11100110,  // 9
};

// pins for decimal point and each segment
//                          dp,G,F,E,D,C,B,A
const int segmentPins[8] = { 5,9,8,7,6,4,3,2};

void setup()
{
  for(int i=0; i < 8; i++)
  {
    pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
  }
}

void loop()
{
  for(int i=0; i <= 10; i++)
  {
    showDigit(i);
    delay(1000);
  }
  // the last value if i is 10 and this will turn the display off
  delay(2000);  // pause two seconds with the display off
}

// Displays a number from 0 through 9 on a 7-segment display
// any value not within the range of 0-9 turns the display off
void showDigit( int number)
{
  boolean isBitSet;

  for(int segment = 1; segment < 8; segment++)
  {
    if( number < 0 || number > 9){
      isBitSet = 0;   // turn off all segments
    }
    else{
      // isBitSet will be true if given bit is 1
      isBitSet = bitRead(numeral[number], segment);
    }
    isBitSet = ! isBitSet; // remove this line if common cathode display
    digitalWrite( segmentPins[segment], isBitSet);
  }
}

```

# Answer
`bitRead(x, y)` takes a value `x`, and looks at *bit number* `y`.

So, if:

* `y` is the number `2`;
* `x` is `53` (binary number `0` `0` `1` `1` `0` ***`1`*** `0` `1`)
```
                                       ^
```

it looks at bit #2. Bits are counted from the *right* starting at ***`0`*** \- I have indicated the bit in question above.

So, `bitRead(53, 2)` would return `1`, since bit #2 in 53 is a `1`.

In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit `8` has all seven of its LEDs lit up, so you'd expect the encoding for `8` to have lots of binary `1`s in it - and sure enough, it does (`B11111110`)! And the digit `7` has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, `B11100000`.

The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...
> 3 votes

---
Tags: display, 7-segment
---


# Question
Title: Are all the pins on Arduino shields available for use?
Basically, if I put a shield on my Arduino (mine is Uno, but I'm asking generally), can I freely use **all** the pins that are there on the shield?

I have an Ethernet shield and almost all of the pins that the original Uno has, are available on the Ethernet too.

The best results that I could get from googling are this and this which describe that if a shield uses a certain pin, putting **another shield** that uses the same pin causes conflict.

But what about using them myself? Can I use all the pins on a shield as Input/Output?

If some pins are unusable, then why are they available on the board? For example why doesn't the Ethernet have pins 10-13 blocked so you can't put any jumper wires in them?

Additional info:

* There was also this article which didn't seem very credible to me.
* Also I've tried using pins 10-13 to light an LED while the Ethernet was busy transferring data. The result was the LED connected to pin 10 was very dim, 11 was less dim and so on. So my guess is yes, they are unavailable. But the fact that this was so rarely mentioned on the internet and that the pins aren't physically blocked made me doubtful.

# Answer
Short answer: **NO**.

Each shield adds some feature to the base Arduino Uno board and to do that it's more than probably going to use some of the PINs. I say *more than probably* because Arduino do have support for certain protocols which can share the same pins (I2C and OneWire just from the top of my mind), but they are not the most commonly used approaches for shields.

The only reason the shields expose the same set of pins is for *stackability*, but not every shield is compatible with any other: it depends on the used PINs.

Some shields provide some level of configuration, usually via jumpers, in order to make them usable in more contexts they would usually be.

Documentation regarding the pins used by each shield is generally available along with the shield, but if you buy cheap clones it's no surprise you might have difficulties finding documentation...

The article you were pointing is somewhat creditable because most of what the author says is actually true and real, including the risk of short circuits.

As an example, the test you run with LEDs connected to the Arduino SPI interface (pins from 10 to 13 are used by `SPI`) could have damaged your board if you didn't use current limiting resistors.
> 1 votes

---
Tags: shields, pins
---


# Question
Title: Nano resets or freezes on calling a function
I'm controlling a light bulb with my Arduino Nano from serial or RF (via nRF24L01+) and I'm passing the commands as a string. After I get all the variables (3 ints) I try calling the function `execOrder` but no matter what I put in there, the Arduino just hangs or resets. Code is as follows:

```
#define SSR 3
#define SW 4
#define nanoID 1
bool isPWM = false;
int value;

// Módulo RF
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
#define PayLoad 20

#include <MemoryFree.h>

void setup() {
  pinMode(SSR, OUTPUT);
  pinMode(SW, INPUT_PULLUP);
  digitalWrite(SSR, LOW);
  value = 0;
  Serial.begin(9600);
  Serial.println("------ CEACI SAS -- Controller Module ------");
  Serial.println("Module No: " + String(nanoID));
  // Inicializar RF
  Serial.println("Inicializando RF");
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_250KBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);
  radio.startListening();
  //radio.printDetails(); //RF Debug
  Serial.println("RF listo!");
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void loop() {
  if (Serial.available()) {
    Serial.println("Rcvd Serial!");
    String msgRcvd = Serial.readString();
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    String msgRcvd(msgBuff);
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else {
    chkSwitch();
  }
}

void execOrder(int ID, int CMD, int VAL){
  if (ID == nanoID || ID == 0){
    switch(CMD){
      case 0:
        State();
        break;
      case 1:
        value = VAL;
        OnOff();
        break;
      case 2:
        value = VAL;
        PWM();
        break;
    }
  }
}

```

I wanted to process the incoming string in a function, but it resets as well.

By the way, I'm using `MemoryFree` library to check if I'm out of memory, and there's plenty of it, so I don't really know where's the problem. Any help would be greatly appreciated!

EDIT:

For the serial part I can do the following (my original code):

```
if (Serial.find("MOD=")) {
  int ID = Serial.parseInt();
  if (ID == nanoID || ID == 0) {
    Serial.find("CMD=");
    int command = Serial.parseInt();
    int cmdVal = 0;
    if (command != 0){
      Serial.find("VAL=");
      cmdVal = Serial.parseInt();
    }
    Serial.println("MOD: "+String(ID)+", CMD: "+String(command) + ", VAL: " + String(value));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    execOrder(ID,command,cmdVal);
  }
}

```

And it works flawlessly. But I don't know how to achieve the same results with the RF input. The problem seems to be with using so many strings.

# Answer
> 1 votes
Your problem is not due to memory shortage, but because you are erroneously using pointers.

Even with your *fix* you are doing the same mistake, you are just not incurring into the same problem by luck as you are not addressing anything new after the bad definition of your variable `msgBuff`.

Putting all that into simple terms, you should change your code and probably read some articles on C pointers as it looks like you have a Java background (like me).

Your issue is in the `char msgBuff[]="";` statement which should be moved after the the call to obtain the payload size and turned into `char msgBuff[RFlen];`:

```
int RFlen=radio.getDynamicPayloadSize();
char msgBuff[RFlen];
delay(10);
radio.read(&msgBuff, RFlen);

```

# Answer
> 0 votes
Ok, I solved it like this:

```
if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    int ID = msgBuff[4] - '0';
    int cmdCode = msgBuff[10] - '0';
    int cmdVal = msgBuff[16] - '0';
    if (cmdCode == 2){
      cmdVal *= 100;
      cmdVal += 10*(msgBuff[17]-'0');
      cmdVal += (msgBuff[18]-'0');
    }
    execOrder(ID,cmdCode,cmdVal);
}

```

The problem is with using strings, but I don't know why since there's plenty of memory. Anyway, I hope this helps anyone else with the same issue.

---
Tags: arduino-nano, string
---


title: Can't upload to Arduino UNO (kuman UNO)

text:
# Question
Title: Can't upload to Arduino UNO (kuman UNO)
I am trying to upload my code to my new Arduino (Just got one today, so im very new).

I can compile my code with no problems, but uploading it gives me:

```
[Arduino: 1.6.11 (Mac OS X), Board: "Arduino/Genuino Uno"

Sketch uses 1,186 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
chmod: Unable to change file mode on /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Read-only file system
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Permission denied
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

It doesn't matter what i upload (tried to upload some of the examples).

As said i am very new, so if you need any more information to help me just ask.

Thanks in advance!

# Answer
> 0 votes
Drag Arduino.app out of your ~/Downloads folder to /Applications or anywhere else that isn't where you downloads it to. The app is being subjected to Gatekeeper Path Randomization which means it is running on a read-only file system. The app is trying to chmod something inside the app bundle and thats not possible on a read-only file system.

# Answer
> 0 votes
Check your port to which your arduino is connected. The port name can be checked from Arduino IDE. Click Tools -\> Port -\> There you can find the port name. Open Terminal and type the following command.

```
sudo chmod 777 /dev/port_name

```

After this try to Recompile/Upload the code again.

---
Tags: arduino-uno, uploading
---


# Question
Title: Changing the mode when pressing/holding down a buttton
And first of all sorry for my bad English.

I am trying to write code that allows the user to change between continuous or manual mode, but I am having some issues getting it to work. The goal is to be able to switch from manual SOS (user pressing the button to SOS) and automatic SOS (the led automatically blinking SOS morse).

Currently, when I press down the button it loops once the automatic SOS and returns back to its normal state with LED on.

How would I make it, for an example switch the mode to manual when holding down button and giving user some sort of indication when changing the mode (etc blinking the led for X amount of time?)

What I am looking to achieve is:

1. Turn LEDS on when pressing the button.
2. Start looping automatic SOS signal
3. Press or hold down the button to change mode.
    * Blink LEDS to indicate the mode change.
4. Switch to manual SOS signal (user pressing the button to signal)
5. Press or hold down the button to change mode.
    * Blink LEDS to indicate the mode change.
6. Switch back to an automatic loop.

The code so far:

```
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin =  13; // the number of the LED pin
int mode;

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  mode = digitalRead(buttonPin);

  // Manual SOS mode.
  buttonState = mode;

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    digitalWrite(ledPin, HIGH); // turn LED on:
  } else {
    digitalWrite(ledPin, LOW); // turn LED off:
  }

  // Automatic SOS mode.
  if (mode == HIGH) {
    // check if the pushbutton is pressed.
    // if it is, starts looping automatic SOS.
    int i = 0;
    for (i=0; i<3; i++) {
      digitalWrite(ledPin, HIGH);   // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(1200); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(1200); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }
    digitalWrite(ledPin, LOW);
    // waits 3 seconds before starting the loop again
    delay(3000);
  }
}

```

# Answer
> 1 votes
Ok, I'll try to split the code into multiple sections for clarity, but all this goes into one single sketch.

First we define the PINs: defines are pre-processor macros, even better than `const` in terms of performance and space consumption:

```
#define BTN_PIN 2
#define LED_PIN 13

```

Let's initialize the board as per our requirements:

```
void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

```

Now we define the code which emits and SOS signal in morse code using the standard timing:

1. a long pulse lasts 3 times a short one
2. a space lasts 6 times a short pulse

That boils down to the following definitions considering a standard unit of 300ms:

```
#define UNIT 300
#define SHORT (UNIT)
#define LONG (UNIT*3)
#define PAUSE (UNIT*3)
#define SPACE (UNIT*6)

```

I'm also going to define another macro to emit a generic light pulse, for simplicity I'll use the `delay(...)` function, but this will prevent detecting button presses while signalling:

```
#define PULSE(TYPE) digitalWrite(LED_PIN, HIGH);delay(TYPE); digitalWrite(LED_PIN, LOW);delay(UNIT)

```

With the above in place we can define a function to send an SOS which should be both very compact and also readable:

```
void sendSOS() {
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
  PULSE(PAUSE); // inter letter pause
  PULSE(LONG);PULSE(LONG);PULSE(LONG);
  PULSE(PAUSE); // inter letter pause
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
}

```

Now, let's describe what the mode changing should be notified to the user:

```
#define QUICK 100
bool autoMode = true;

void switchMode() {
  autoMode= !autoMode;
  for (unsigned int i = 0; i < 25; i++) {
    digitalWrite(LED_PIN, HIGH);
    delay(QUICK);
    digitalWrite(LED_PIN, LOW);
    delay(QUICK);
  }
}

```

Now our main loop will have to check the button and act accordingly, right?

```
#define LONGPRESS 500
unsigned long elapsed;
bool clicked = false;
unsigned long duration;

void loop() {
  if (autoMode) {
    sendSOS();
  }
  elapsed = millis();
  while(clicked || millis() - elapsed <= SPACE) {
    // keep waiting to emit a SPACE or until the button is released

    if (digitalRead(BTN_PIN)) {
      // button has been clicked: trace it and start counting time
      clicked = true;
      duration = millis();
    } else if (clicked) {
      // button has been released: stop tracing and verify click duration
      clicked = false;
      if (millis() - duration <= LONGPRESS) {
        // switch mode on long press
        switchMode();
      } else if (!autoMode) {
        // short press has a meaning only when not in auto mode
        sendSOS();
      }
    }
  }

```

The solution above has great space for improvement:

* there is no de-bouncing on the button
* the board is unresponsive while signalling
* keeping the button pressed forever will prevent any signalling to occur in any mode
* the code is afflicted by `millis()` rollover if you keep the button pressed for long periods (around 49 days)

**UPDATE**: I've added the inter-letter pause as suggested in the comments.

**UPDATE**: apparently `auto` is a reserved word, so I changed it to `autoMode`.

---
Tags: arduino-uno, c++
---


title: Thunderstorm triggering button press?

text:
# Question
Title: Thunderstorm triggering button press?
So I recently built a small IFTT powered button using an ESP8266 for my boys to play with. Tonight during an intense Thunderstorm, I kept getting alerts that it had been pressed. They weren't in the basement at all. Then I realized, giant crack of lightening === SMS message.

Now I don't think this has anything to do with the button mechanism itself, but the shoddy way I hooked it up, and stuffed it into an enclosure. I'm just curious - is this possible? Could some sort of static electricity from a few nearby lightening strikes do something that would send a 'high' signal to the GPIO Pin on my Espee? I had to use a pull up resistor, and I feel like there's probably a few bare-ish wires in there, but nothing touching, or even close enough to 'arc'. Am I crazy?

# Answer
> 2 votes
You aren't crazy. I had a similar thing happen when an external hot-water system turned on at midnight (someone was having a shower) and one of my systems detected input unexpectedly (and rang a bell right next to my ear while I was trying to sleep).

My solution was to have something like this:

The diodes clamp the input to acceptable ranges, and R1 is a current limit for the diodes. R2 and C1 are a filter that slows down the incoming signal (and thus eliminates sudden spikes). R3 is a pull-up resistor. In my case I had active-low. If you have active-high you could use a pull-down resistor instead.

Also see https://arduino.stackexchange.com/a/13128/10794

Further reference material:

---
Tags: pins, hardware
---


# Question
Title: What are the logical errors in this piece of code?
The client always reply with *"ThisCodeTurnsTheUnoOnn"* or *ThisCodeTurnsTheUnoOff"* based on some conditions.

This piece of code is inside arduino uno's *void loop()*.

**Expected behavior:**

The arduino read the reply and turn the digital pin 13 to HIGH if the onCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOnn" and the other way around:

The arduino read the reply and turn the digital pin 13 to LOW if the offCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOff".

and the digital pin 13 should always remain in the previous state if the new client's reply was the same as previous reply. (e.g. if client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state).

**Actual behavior:**

CASE : client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state but the arduino turns the digital pin 13 HIGH when entering the next loop(void loop()) then turns back to LOW after entered the loop(void loop()).

```
  // available() will return the number of characters
  // currently in the receive buffer.

  const int solenoidValve = 13;

  char onCode[23] = "ThisCodeTurnsTheUnoOnn";
  char offCode[23] = "ThisCodeTurnsTheUnoOff";

  int onCount = 0;
  int offCount = 0;

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

    if(c == onCode[onCount])
    {
      onCount++;

      if(onCount == 22)
      {
        digitalWrite(solenoidValve, HIGH);
        break;
      }
    }
    else
    {
      onCount = 0;
    }

    if(c == offCode[offCount])
    {
          offCount++;

          if(offCount == 22)
          {
            digitalWrite(solenoidValve, LOW);
            break;
          }
    }
    else
    {
      offCount = 0;
    }
    Serial.write(c);
  }

```

**The complete code, in case the logical errors is not within the above piece of code:**

```
#include <SoftwareSerial.h>
#include <SparkFunESP8266WiFi.h>

//////////////////////////////
// WiFi Network Definitions //
//////////////////////////////
// Replace these two character strings with the name and
// password of your WiFi network.
const char mySSID[] = "SSID";
const char myPSK[] = "PASSWORD";
const int solenoidValve = 13;
char onCode[23] = "ThisCodeTurnsTheUnoOnn";
char offCode[23] = "ThisCodeTurnsTheUnoOff";

//water flow calculation variables
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;

//////////////////
// HTTP Strings //
//////////////////
const char destServer[] = "192.168.0.101"; //private ip //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
const uint16_t port = 8080; // Code ID: 1126 [Kugan] added variable port
const String httpRequest = "GET /aquosdb/getStatus.php HTTP/1.1\n"
                           "Host: 192.168.0.101\n" //private ip [note for myself: dont forget to change IP]
                           "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132

// All functions called from setup() are defined below the
// loop() function. They modularized to make it easier to
// copy/paste into sketches of your own.
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;

  // Serial Monitor is used to control the demo and view
  // debug information.
  Serial.begin(9600);
  //serialTrigger(F("Press any key to begin.")); //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130

  // initializeESP8266() verifies communication with the WiFi
  // shield, and sets it up.
  initializeESP8266();

  // connectESP8266() connects to the defined WiFi network.
  connectESP8266();

  // displayConnectInfo prints the Shield's local IP
  // and the network it's connected to.
  displayConnectInfo();

  //serialTrigger(F("Press any key to connect client."));  //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130
  //valveControl();
}

void loop()
{
  setFlow();
  //delay(500); // [Kugan] 29/7/16 try3 : added delay to debug connection bug Code ID:1131
  valveControl();
}

void initializeESP8266()
{
  // esp8266.begin() verifies that the ESP8266 is operational
  // and sets it up for the rest of the sketch.
  // It returns either true or false -- indicating whether
  // communication was successul or not.
  // true
  int test = esp8266.begin();
  if (test != true)
  {
    Serial.println(F("Error talking to ESP8266."));
    errorLoop(test);
  }
  Serial.println(F("ESP8266 Shield Present"));
}

void connectESP8266()
{
  esp8266.disconnect(); // Code ID:1125 [Kugan] To disconnect from previously connected wifi AP
  delay(100);           // esp8266 has auto-reconnect function to connect previously connected AP

  // The ESP8266 can be set to one of three modes:
  //  1 - ESP8266_MODE_STA - Station only
  //  2 - ESP8266_MODE_AP - Access point only
  //  3 - ESP8266_MODE_STAAP - Station/AP combo
  // Use esp8266.getMode() to check which mode it's in:
  int retVal = esp8266.getMode();
  if (retVal != ESP8266_MODE_STA)
  { // If it's not in station mode.
    // Use esp8266.setMode([mode]) to set it to a specified
    // mode.
    retVal = esp8266.setMode(ESP8266_MODE_STA);
    if (retVal < 0)
    {
      Serial.println(F("Error setting mode."));
      errorLoop(retVal);
    }
  }
  Serial.println(F("Mode set to station"));

  // esp8266.status() indicates the ESP8266's WiFi connect
  // status.
  // A return value of 1 indicates the device is already
  // connected. 0 indicates disconnected. (Negative values
  // equate to communication errors.)
  retVal = esp8266.status();
  if (retVal <= 0)
  {
    Serial.print(F("Connecting to "));
    Serial.println(mySSID);
    // esp8266.connect([ssid], [psk]) connects the ESP8266
    // to a network.
    // On success the connect function returns a value >0
    // On fail, the function will either return:
    //  -1: TIMEOUT - The library has a set 30s timeout
    //  -3: FAIL - Couldn't connect to network.
    retVal = esp8266.connect(mySSID, myPSK);
    delay(60);
    if (retVal < 0)
    {
      Serial.println(F("Error connecting"));
      errorLoop(retVal);
    }
  }
}

void displayConnectInfo()
{
  char connectedSSID[20];
  memset(connectedSSID, 0, 20);
  // esp8266.getAP() can be used to check which AP the
  // ESP8266 is connected to. It returns an error code.
  // The connected AP is returned by reference as a parameter.
  int retVal = esp8266.getAP(connectedSSID);
  if (retVal > 0)
  {
    Serial.print(F("Connected to: "));
    Serial.println(connectedSSID);
  }

  // esp8266.localIP returns an IPAddress variable with the
  // ESP8266's current local IP address.
  IPAddress myIP = esp8266.localIP();
  Serial.print(F("My IP: ")); Serial.println(myIP);
}

void flow() // Interrupt function
{
   flow_frequency++;
}

void setFlow()
{
   // To use the ESP8266 as a TCP client, use the
  // ESP8266Client class. First, create an object:
  ESP8266Client client1;
  client1.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127

  // ESP8266Client connect([server], [port]) is used to
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client1.connect(destServer, port); //Code ID:1126 [Kugan] created variable port
  if (retVal <= 0)
  {
    Serial.println(retVal);  //[Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
    Serial.println("flow");
    Serial.println(F("Failed to connect to server."));

    initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
    connectESP8266();
    displayConnectInfo();

    return;
  }

   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
   }

  // print and write can be used to send data to a connected
  // client connection.
  String httpPostRequest = "GET /aquosdb/setFlow.php?data=" + String(l_hour) + " HTTP/1.1\n" //sets the water flow value
                           "Host: 192.168.0.101\n" //private ip
                           "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
  client1.print(httpPostRequest);

  while (client1.available()) // [Kugan] 28/7/16 Code ID: 1128  to clear the buffer
    Serial.write(client1.read()); // read() gets the FIFO char

  if (client1.connected())
    client1.stop(); // stop() closes a TCP connection.
}

void valveControl()
{
  // To use the ESP8266 as a TCP client, use the
  // ESP8266Client class. First, create an object:
  ESP8266Client client;
  client.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127 stop any existing connections

  // ESP8266Client connect([server], [port]) is used to
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client.connect(destServer, port); // Code ID:1126 [Kugan] created variable port
  if (retVal <= 0)
  {
    Serial.println(retVal);  // [Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
    Serial.println("valve");
    Serial.println(F("Failed to connect to server."));

    initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
    connectESP8266();
    displayConnectInfo();

    return;
  }

  // print and write can be used to send data to a connected
  // client connection.
  client.print(httpRequest);

  // available() will return the number of characters
  // currently in the receive buffer.
  int onCount = 0;
  int offCount = 0;

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

    if(c == onCode[onCount])
    {
      onCount++;

      if(onCount == 22)
      {
        digitalWrite(solenoidValve, HIGH);
        break;
      }
    }
    else
    {
      onCount = 0;
    }

    if(c == offCode[offCount])
    {
          offCount++;

          if(offCount == 22)
          {
            digitalWrite(solenoidValve, LOW);
            break;
          }
    }
    else
    {
      offCount = 0;
    }
    Serial.write(c);
  }

  // connected() is a boolean return value - 1 if the
  // connection is active, 0 if it's closed.
  if (client.connected())
    client.stop(); // stop() closes a TCP connection.
}

// errorLoop prints an error code, then loops forever.
void errorLoop(int error)
{
  Serial.print(F("Error: ")); Serial.println(error);
  Serial.println(F("Looping forever."));
  for (;;)
    ;
}

// serialTrigger prints a message, then waits for something
// to come in from the serial port.
void serialTrigger(String message)
{
  Serial.println();
  Serial.println(message);
  Serial.println();
  while (!Serial.available())
    ;
  while (Serial.available())
    Serial.read();
}

```

Thanks in advance for your efforts to answer my question.

# Answer
> 1 votes
The biggest obstacle to you getting this working is the somewhat bizarre way you are working out what has been sent to you, by counting characters that match and waiting until they reach 22.

Instead you should read the input character by character and place them into an array. Discard anything past the 22nd character so it doesn't overflow the array. Then you can compare what is in that array to strings stored in flash (using the `F()` macro) and the `strcmp_P()` function.

---
Tags: arduino-uno, sensors, esp8266, pins
---


title: check string for specific characters?

text:
# Question
Title: check string for specific characters?
I am just wondering if it is possible to check a string for specific characters. For example if my string is `String mystr = "test";` and I wanted to check for the letter ***t*** at the beginning and if it is NOT there do something how would I go about this?

I have read about `string.startsWith(string2);` however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that `string.contains` isn't a thing.

To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.

# Answer
> 0 votes
Have you tried the following?

```
if(!actualString.startsWith(expectedString)) {
  // do whatever you have to
}

```

BTW, that is what actually suggested in *@EdgarBonet*'s comment.

---
Tags: arduino-nano, string
---


# Question
Title: How I can use multi sensor in one code in Arduino?
How I can use multi smoke sensor in one code? I mean how can I use more than one sensor, where both sensors has the same purpose, like use smoke sensor in multi room. Similar to this code where one is used only. How I can more than one, in Arduino Uno R3,,

```
<per>
    int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
 pinMode(greenLed, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(smokeA0, INPUT);
Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

```

How I can add more than one sensor to get same purpose. check detect 1 and detect2 and detect 3 if one of this detection LED Red ON, Thanks\`

# Answer
just duplicate the parts of the code that handle the sensor.

```
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeSensor1 = A5;
int smokeSensor2 = A4;
int smokeSensor3 = A3;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeSensor1, INPUT);
  pinMode(smokeSensor2, INPUT);
  pinMode(smokeSensor3, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor1 = analogRead(smokeSensor1);
  int analogSensor2 = analogRead(smokeSensor2);
  int analogSensor3 = analogRead(smokeSensor3);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor1);
  // Checks if it has reached the threshold value
  if( (analogSensor1 > sensorThres) || (analogSensor2 > sensorThres) || (analogSensor3 > sensorThres) )
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

```
> 1 votes

# Answer
You haven't mentioned what sensor you are using, so I can't offer any help on how to interface with it. Though you can add 'multi-sensor code' by adding code that will get the state of the sensor at times when you can afford to wait a few ms before checking the state of the other sensors. With the code you provided, you could after the if/else block but before the delay.

Also, it is typically not a good idea to put sensors far away from each other but still connect them to the same controller. You should give each room its own Arduino.
> 0 votes

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


# Question
Title: Is it possible to power this 12V Wind Speed Sensor with a 5V battery?
I have a battery pack used to charge mobile phones. It's capacity is 13,000mAh and it has two output ports. Both are 5V but one is 1A and the other 2.1A It also has an Input port of 5V 1A. (To which I will connect a solar panel).

I want to be able to power this Adafruit Feather M0 as well as this Wind Speed Sensor Wind Speed Sensor Voltage Type(0-5V) SKU:SEN0170. Is it possible and if it is how?

# Answer
> 1 votes
1. If you have a circuit diagram for your 13,000mAh 5V battery, check whether there are internal connections at higher than 5V. Because 5V is not a common battery voltage, there probably are cells in a higher-voltage series connection, being converted to 5V output via a step-down (buck) circuit.
2. An item like a “5V DC to 9V DC Converter DC-DC Isolated Power Supply Module” as in picture below \[from ebay seller *bidcenter*\] might do the job. Also available are less-expensive not-potted adjustable boost regulators.

---
Tags: power, voltage-level
---