title: How to run servo 180 degrees and stop?

text:
# Question
Title: How to run servo 180 degrees and stop?
I'm creating a PIR motion sensor doggy door.

The problem I'm having with it is, it runs 3 times, I've figured out how to pause when reaches 180° but not how to stop.

I was thinking I could use detach my servo and attach after a delay of 30,000 and then re-attach return to 0 degrees, then wait for next PIR high.

But I don't know how to code it into what I have or even if it would work.

My code:

```
/* This code sweeps a servo from 0 degrees to 180 when the PIR sensor detects motion.
   Special thanks goes to the author of the PIR sensor code, whose code helped tremendously
   in the making of this code and Instructable.
   author of PIR sensor code: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at
**/

#include <Servo.h>

Servo myservo; //creates a servo object
//a maximum of eight servo objects can be created
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;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pirPin = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

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);
  //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");
  //while making this Instructable, I had some issues with the PIR's output
  //going HIGH immediately after calibrating
  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pirPin) == HIGH) {
    delay(500);
    Serial.print(".");
  }
  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pirPin) == HIGH) {
    //if the PIR output is HIGH, turn servo
    /*turns servo from 0 to 180 degrees and back
      it does this by increasing the variable "pos" by 1 every 5 milliseconds until it hits 180
      and setting the servo's position in degrees to "pos" every 5 milliseconds
      it then does it in reverse to have it go back
      to learn more about this, google "for loops"
      to change the amount of degrees the servo turns, change the number 180 to the number of degrees you want it to turn
    **/
    for (pos = 0; pos < 180; pos += 1) {
      //goes from 0 to 180 degrees
      myservo.write(180);
      delay(8000); ////stops motor for 8 seconds
      for (pos = 180; pos >= 90; pos -= 1) {
        // goes from 180 degrees to 0 degrees
        myservo.write(pos); // tell servo to go to position in variable 'pos'
        delay(15); // waits 15ms for the servo to reach the position
      }
      myservo.write(90);
      delay(4000); //stops motor for 4 seconds
      for (pos = 90; pos <= 180; pos += 1) {
        // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos); // tell servo to go to position in variable 'pos'
        delay(15); // waits 15ms for the servo to reach the position
      }
      //to make it go slower, increase the number.
      if (lockLow) {
        //makes sure we wait for a transition to LOW before further output is made
        lockLow = false;
        Serial.println("---");
        Serial.print("motion detected at ");
        Serial.print(millis() / 1000);
        Serial.println(" sec");
        delay(50);
      }
      takeLowTime = true;
    }

    if (digitalRead(pirPin) == LOW) {
      if (takeLowTime) {
        lowIn = millis(); //save the time of the transition from HIGH to LOW
        takeLowTime = false; //make sure this is only done at the start of a LOW phase
      }
      //if the sensor is low for more than the given pause,
      //we can assume the motion has stopped
      if (!lockLow && millis() - lowIn > pause) {
        //makes sure this block of code is only executed again after
        //a new motion sequence has been detected
        lockLow = true;
        Serial.print("motion ended at "); //output
        Serial.print((millis() - pause) / 1000);
        Serial.println(" sec");
        delay(50);
      }
    }
  }
}

```

Could I also just change the jumper pin on the PIR hardware for a retriggering set high to keep the door open when the dog is there so it won't just close on them?

I'm using this PIR:

# Answer
I haven't been able to compile or test this but I think it should do what you are asking for, or at the very least steer you in the right direction.

```
// This code waits for a signal from the PIR sensor.
// When the signal is recieved it rotates the servo 180 degrees and waits 30 seconds
// it then rotates the servo back to 0 (to close the door)

#include <Servo.h>

const int ServoIntraStepDelay   =  15;      // Delay between servo steps (ms)
const int ServoAngleStep        =   1;      // The angle by which the servo position is changed every step (degree)
const int ServoAngleMinimum     =   0;      // The min angle of the servo (degrees)
const int ServoAngleMaximum     = 180;      // The max angle of the servo (degree)
const int DoorOpenPeriod        = 30 * 1000;// The time the door will remain open for (ms)
const int DoorClearPoll         = 100;      // The interval betwen polls to the sensor when checking to see if the door is clear(ms)
const int DoorClearPeriod       = 5000;     // The interval that the PIR sensor must report low before closing the door (ms)

const int PIRCalibrationTime    = 30;       //amount of time we give the sensor to calibrate(10-60 secs according to the datasheet) (s)

const int PinPIRData            = 12;       //digital pin connected to the PIR's output
const int PinPIRPower           = 13;       //connects to the PIR's 5V pin
const int PinServoPower         = 4;        // The pin that controls the servo.

Servo myservo;                              //creates a servo object

void setupCalibratePIR()
{
        //give the sensor time to calibrate
    Serial.println("Calibrating sensor ");
    for(int i = 0; i < PIRCalibrationTime; i++)
    {
        Serial.print(PIRCalibrationTime - i);
        Serial.print("-");
        delay(1000);
    }
    Serial.println();
    Serial.println("done");
    //while making this Instructable, I had some issues with the PIR's output
    //going HIGH immediately after calibrating
    //this waits until the PIR's output is low before ending setup
    Serial.print("Waiting for PIR sensor to report low");
    while (digitalRead(PinPIRData) == HIGH)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.print("SENSOR ACTIVE");
}

void turnServo (const int& from, const int& to, const int& step)
{
    for(int pos = from; pos <= to; pos += step)
    {
        myservo.write(pos);
        delay(ServoIntraStepDelay);
    } //to make it go slower, increase the number.
}

// Test the PIR sensor and ensure that it reports low for a specific time
void waitForDoorClear ()
{
    bool doorIsNotClear = true;
    while (doorIsNotClear)
    {
        doorIsNotClear = false;
        for (int doorClear = 0; !doorIsNotClear && (doorClear * DoorClearPoll) < DoorClearPeriod; ++doorClear)
        {   // Poll every few ms and check that the sensor in LOW
            // As soon as it is high this loop will exit which restarts the time that the low signal must been seen for.
            delay (DoorClearPoll);
            doorIsNotClear = (digitalRead(PinPIRData) == HIGH);
        }
    }   // This is potentially an infinite loop.
}

void setup()
{
    Serial.begin(9600);                     // Begins serial communication
    myservo.attach(PinServoPower);          // Connect to the servo object
    pinMode(PinPIRData, INPUT);             // Connect the PIR data
    pinMode(PinPIRPower, OUTPUT);           // Connect the PIR power
    digitalWrite(PinPIRPower, HIGH);        // Turn on the PIR power

    setupCalibratePIR();                    // Calibrate the PIR sensor
}
// attach
void loop()
{

    if(digitalRead(PinPIRData) == HIGH)
    { //if the PIR output is HIGH, turn servo

        turnServo (ServoAngleMinimum, ServoAngleMaximum, ServoAngleStep);
        delay (DoorOpenPeriod - DoorClearPeriod);
        waitForDoorClear ();
        turnServo (ServoAngleMaximum, ServoAngleMinimum, -ServoAngleStep);
    }
}

```

You weren't that far off.
> 1 votes

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


title: Arduino UNO HTTPS

text:
# Question
Title: Arduino UNO HTTPS
Is it possible to call a HTTPS web service on arduino UNO? I am trying to connect it through client.connect(ip,port). It said connected but never respond, ended up in TIMEOUT.

# Answer
No, it is not possible. The Arduino UNO is not powerful enough to encrypt the data for an SSL connection. On top of that the W5100 chip used on the Ethernet shield has its own IP stack built into it, and that stack doesn't support SSL either.

If you require SSL then it is recommended that you use one of the "dual" boards, like the Yun, and have the Linux portion of the board make the SSL connection for you using cURL.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Read and write on the same node (central) using an RF24 network on Arduino
I want to send and receive on the same node using the RF24Network library, but I'm unable to do so even when I use `radio.StopListening()`.

Here is the code:

```
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 0);
}

void loop(){
  network.update();
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
    // I WANT HERE TO SEND BACK TO THE TRANSMITTER but I'm unable to do that
    radio.stopListening();
    payload_t payload = { 2000, 15444452 };
    RF24NetworkHeader header(2);
    network.write(header, &payload, sizeof(payload));
  }
}

```

Second Node:

```
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};
firstExec = 1;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 2);
}

void loop() {
  network.update();
  if(firstExec) {
    radio.stopListening();
    payload_t payload = { 2000, 5555555 };
    RF24NetworkHeader header(0);
    network.write(header, &payload, sizeof(payload));
    radio.startListening();
    firstExec = 0;
  }
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
  }
}

```

# Answer
> 1 votes
The library says you must include `network.update()` in `loop()` for the nodes to be in sync. Place that call at the top of `loop()` in both nodes.

---
Tags: arduino-uno
---


# Question
Title: Trying to figure out how to use an extension board with Pi
I am trying to make the following board work with Raspberry Pi. Board Name: `L293D Motor Drive Shield Expansion Board for Arduino Mega Raspberry Pi`

All I need to know is which pins do the following:

1. Enable the motor
2. Disable the motor
3. Rotate forward
4. Rotate backward

More information about the board:

1. https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors
2. https://www.raspberrypi.org/forums/viewtopic.php?f=45&t=16118

Can someone please help me find this information?

# Answer
> The following pins are in use only if the DC/Stepper noted is in use:
>
> * Digital pin 11: DC Motor #1 / Stepper #1 (activation/speed control)
> * Digital pin 3: DC Motor #2 / Stepper #1 (activation/speed control)
> * Digital pin 5: DC Motor #3 / Stepper #2 (activation/speed control)
> * Digital pin 6: DC Motor #4 / Stepper #2 (activation/speed control)
>
> The following pins are in use if any DC/steppers are used
>
> * Digital pin 4, 7, 8 and 12 are used to drive the DC/Stepper motors via the 74HC595 serial-to-parallel latch
>
> The following pins are used only if that particular servo is in use:
>
> * Digitals pin 9: Servo #1 control
> * Digital pin 10: Servo #2 control

(source)
> 1 votes

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


# Question
Title: Can multiple xbees send data to one xbee
I am new to xbees. I want to have multiple xbees (up to 400 xbees) send data constantly to one xbee (receiver).This is just simple data like lets say 0 or 1 . Is this possible? Are there any limitations?

# Answer
> 0 votes
Yes, you can send data from 400 XBees to a single xbee. I would like to clarify one thing. XBees are connecting to a network, not to a particular xbee. And the devices connected in a network can communicate each other.

---
Tags: arduino-uno, xbee
---


# Question
Title: Is it possible for ThingSpeak to show a simple table of all data collected?
I just recently found the ThingSpeak platform for the IoT. I have been playing around with its features a bit, but I have not found a way for it to show a simple table of all the data collected. For example, the table might have humidity, temperature, and timestamp columns, and then every time data is written to ThingSpeak, a new row would be added with the latest readings. I would be surprised if this is not possible with all of its complex graphing tools. Has anybody found a feature like this?

# Answer
> 0 votes
Since ThingSpeak has an extensive API, you can build a tool to read in data and display it as a table. I have created a GitHub repo called, "IoT Debugger" that allows you to see data as a table as the it comes into a ThingSpeak Channel.

To use the demo, enter your channel number and the read API key.

If you want to modify the project, fork the project on GitHub.

---
Tags: datalogging
---


# Question
Title: Connecting multiple TFT panels to Arduino Uno via SPI?
Is it possible to connect more than one TFT screen (like this one or similar: https://www.adafruit.com/products/1651) to an Arduino Uno?

I'm wanting to connect and control two color screens at once; note the touch functionality of the one linked above isn't really necessary, I just like the size and overall build. They have a version that works like a shield and sits on top of the Arduino, which would work I suppose if I bought another unit for the other screen. The breakout board version is more flexible but I don't know of a way to control two screens that require that many pins.

Any suggestions? Thanks

# Answer
Yes, you can. All the SPI pins (MISO, MOSI and SCK) are all shared between the panels. You can even share the D/C and RST signals. The only signal that *needs* to be separate is the CS pin since this is the pin that identifies which panel is actively receiving commands and data at any one time. Also you don't need to connect up the MISO pin at all, since that is only connected to the SD card slot, not the TFT screen.

So each screen that you add just requires one more pin to be used. One screen uses 5 pins. Two screens use 6 pins. Three screens use 7 pins, etc.

And yes, for this the breakout version would be easier to work with than the shield version.
> 1 votes

---
Tags: arduino-uno, lcd, multiplexer, tft
---


title: Is possible to concatenate integers?

text:
# Question
Title: Is possible to concatenate integers?
It's a basic one: I have two values from two different analogRead pins:

```
int val1;
int val2;

```

For example, val1 = 10 and val2 = 10. How could I put these two values into a variable val3 = val1 + val2 that will give the answer 1010, instead 20 ?

# Answer
If you are reading from the analog pins then the values are 10 bits (not 8 as suggested above). Are you looking at concatenating 2 10 bit numbers or 2 16 bit numbers or are you using a zero or duo in which case they could be 12 bit numbers.

In any case:

```
const int BITMASK = 0x3FF;  // 10 bits = 0x3FF, 12 = 0xFFF, 16 = 0xFFFF
const int BITWIDTH = 10;
long result = ((value1 & BITMASK) << BITWIDTH) | (value2 & BITMASK);

```

I suspect it won't give you the answer you want, but...
> 1 votes

# Answer
It sounds to me, from your comments, that what you want to do is turn this:

```
myRadio.transmit(val1);
myRadio.transmit(val2);

```

into something more like this:

```
myVal = join(val1, val2);
myRadio.transmit(myVal);

```

That's all pseudocode of course, and those functions are in themselves nonsense, but it serves to illustrate.

So you want to turn two values into one single block of data for sending thus reducing the overall transmission overhead of the packet (one large packet instead of two smaller packets).

What you are actually looking for is called a *struct* and looks something like this:

```
struct MyData {
    int val1;
    int val2;
};

```

That creates a new variable type which contains two sub-variables in it. You then use it like any other variable:

```
struct MyData data;

```

You can then get at the values inside it with:

```
data.val1 = analogRead(A1);
data.val2 = analogRead(A2);

```

And the whole thing can be transmitted in one block with whatever functions your RF library provides:

```
myRadio.transmit(&data, sizeof(struct MyData));

```

Receiving at the other end is just the same - as long as the receiving end has the same structure. Receive into a MyData structure variable and you can get at the individual sub-variables:

```
struct MyData data;
myRadio.receive(&data, sizeof(struct MyData));
Serial.print(data.val1);
Serial.print(",");
Serial.println(data.val2);

```

Of course, you need to read up on whatever library it is you're using to do your transmitting and receiving to find the actual correct functions to call to transmit and receive a block of data like that...
> 1 votes

# Answer
This is not even remotely related to Arduino but mathematics. As Mikael Patel pointed out this can be done fairly easy. You might tell us your intent. If you are seeking for a way to pack values tightly you may consider Integer Sequence Enconding. But without more detailed information this will be just a guess.
> 0 votes

# Answer
You want to send a string of data that represents the data from a number of sensors. For example let's say you have 2 10 bit analog readings and 4 Boolean readings, high or low from the digital pins. You can compress this into 24 bits of data, or 3 bytes.

If your transmission library supports binary writing and reading then you can send it as 3 unsigned chars.

If your transmission library doesn't support binary then you can either base64 encode it as 4 bytes. (The numbers are converted into printable characters that represent their value). Or a more light weight solution would be to write each byte as two hexadecimal digits.

You pack the data into three bytes by using bit masking and shifting (as per my other answer).

```
int sensor1data = 512;
int sensor2data = 64;
bool digital1 = true;
bool digital2 = false;
bool digital3 = false;
bool digital4 = true;

unsigned char data[3]{ 0, 0, 0 };

// Take the top 8 bits of the 10 bit data on sensor1data
// 0x300 takes the 2 lowest bits of the upper byte
// 0x0FC takes the 6 highest bits of the lower byte.
// Shift the result 2 places right so the what was bit 2
// of the upper byte becomes the most significant bit (MSb)
// in the result byte.
data[0] = (sensor1data & 0x3FC) >> 2;

// Take the 2 lowest bits of the lower byte (0x03)
// Shift the 6  places left to make them the MSb of the
// result byte.
data[1] = ((sensor1data & 0x3) << 6);
// Take the 6 MSbs of the sensor2data and left shift them
// so that they become the LSbs of the result byte.
// The result is ORed onto what is already in the result
// to retain the previous instruction.
data[1] |= ((sensor2data & 0x3F0) >> 4);

// Take the 4 LSbs of sensor2data and shift them right
// for places to ocupy the 4 MSbs of the result.
data[2] = ((sensor2data & 0xF) << 4);
// OR each of the flags into the result, shifting by
// a different amount each time.
data[2] |= (digital1 ? 1 : 0) << 3; // I explicitly convert the bool to an int
data[2] |= (digital2 ? 1 : 0) << 2; // because some older compilers don't always
data[2] |= (digital3 ? 1 : 0) << 1; // use 1 for true.
data[2] |= (digital4 ? 1 : 0);

```
> 0 votes

# Answer
If you know in advance how many variables' values you want to transmit:

```
char output[100+1];
....
snprintf(output, sizeof(buffer), "%d,%d,$d\n", val, val2, val3);

```

If not and you need to build the string "as you go":

```
char output[100+1] = "";
char oneVal[12+1];
...
snprintf(oneVal, sizeof(buf), "%d,", value);
strcat(output, oneVal);

// more of the above, possibly in a loop.
...
strcat(output, "\n");      // if you need a newline at the end

```
> 0 votes

---
Tags: string
---


# Question
Title: Can anyone help me figure out why this buffer is overflowing? (Updated)
This should be fairly straightforward, but there must be something I'm not understanding about buffers.

I have serial data coming in to my Mega via Zigbee. I'm sending a string just like this: `~-0.6016800`, where `~` is my unique starting delimiter and my end delimiter is a carriage return `\n`. I'm sure it's coming through the zigbee correctly, because I can see my string show up looking good in XCTU when I plug the zigbee into the PC. Here is my code:

```
const int numChars = 15;
char incoming[numChars];

static boolean Receiving = false;
static byte ndx = 0;
char startMarker = '~';
char endMarker = '\n';
byte K;
bool allreceived = false;

void Get() {
    memset(incoming, NULL, strlen(incoming));
    while (allreceived == false) {
        if (Serial.available() > 0) {
            K = Serial.read();
            if (Receiving == true) {
                if (K != endMarker) {
                    incoming[ndx] = K;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars-1;
                    }
                }
                else {
                    incoming[ndx] = '\0'; // terminate the string
                    Receiving = false;
                    ndx = 0;
                    allreceived = true;
                }
            }
            else if (K == startMarker) {
                Receiving = true;
                ndx = 0;
            }
        }
    }
}

```

So somehow my buffer is overflowing or something, no matter how big I make it. I see the array start off as I expect it for the first few characters, then it turns into unintelligible characters. I think part of the problem might be that the serial data is coming through at a different rate or something, because I can see my starting delimiter `~` on my LCD screen in the middle of my array. The way it's set up, I should never be able to see my start delimiter unless I miss my end delimiter without ending the array. (Note- I've tried different unique end delimiters too, but this seems to work just the same)

Any ideas on what might be causing this??

EDIT: NOW TRYING THIS CODE- I'm still having the buffer overflow, and I'd be really grateful if someone could take a look.

**Sending code:**

```
void PayloadSendit(void) {

Payload[0] = '~';  //1 char unique start

if (outFormat == 0) {
    Payload[1] = '0';
    Payload[2] = '$';  //spacer
    strcat(Payload, stringval); //5 char for hashmarks
}
else {
    Payload[1] = '1';
    strcat(Payload, stringvalin);  //6 char for inch
}
if (dotpos <= 99) {
    Payload[8] = '@';  //spacer
    char dotpos2[2];
    sprintf(dotpos2, "%i", dotpos);
    strcat(Payload, dotpos2);    //2 char
}
else {
    char dotpos3[3];
    sprintf(dotpos3, "%i", dotpos);
    strcat(Payload, dotpos3);   //3 char ///////////////////////////
}

Payload[11] = '0';  //1 char for "no errors" code
Payload[12] = '*';  //1 char end delimiter
Serial.println(Payload);
Serial.flush();
memset(Payload, '\0', 13);

```

}

**Receiving code:**

```
  void Get2() {
    memset(Payload, '\0', bufsize);
    while (allreceived == false) {
        int K = Serial.read();
        switch (K) {
        case -1: // Nothing to read
            break;

        case '~': // Starting a new string
            Receiving = true;
            break;

        default: // Any other characters.
            break;

        }
        if (Receiving) {
            for (int i = 0; i <= 10; i++) {
                Payload[i] = Serial.read();
            }
            if (Serial.read() == '*') {
                Receiving = false;
                allreceived = true;
            }
            else { memset(Payload, '\0', bufsize); }  //destroy array if end delimiter not where it should be
        }

    }
}

```

# Answer
My guess is this line:

```
memset(incoming, NULL, strlen(incoming));

```

When "incoming" hasn't yet been cleared, what is the length of it? It's whatever it counts up until the first '\0' character - and where is that character on the first run through? Who knows.

Instead you should memset the size of the buffer, not the number of non-NULL characters in the buffer:

```
memset(incoming, NULL, numChars);

```

**However**, that is a pointless operation, since you are storing a C string and (should be) properly terminating it, so it really doesn't matter what is in the array to begin with since you are just overwriting it anyway. So you can completely lose that whole function call.

You might like to re-write your receiving routine to use a `switch/case` construct instead of ifs and elses - it'll be much easier to follow:

```
#define EVER ;;

const int numChars = 15;
char buffer[numChars];

void Get() {
    int pos = 0;
    bool receiving = false;

    for (EVER) {
        int K = Serial.read();
        switch(K) {
            case -1: // Nothing to read
                break;

            case '\n': // Got the end of the string.
                if (receiving) return; // We have a valid string.
                pos = 0; // Reset pointer to start of buffer
                break;

            case '~': // Starting a new string
                pos = 0;
                receiving = true;
                break;

            default: // Any other characters.
                if (receiving) {
                    if (pos < numChars-2) {
                        buffer[pos++] = K;
                        buffer[pos] = 0;
                    }
                }
                break;
        }
    }
}

```
> 1 votes

---
Tags: serial
---


title: Generating an 8V PWM signal

text:
# Question
Title: Generating an 8V PWM signal
I have a control module that accepts 8V PWM signals. My goal is to send a 500Hz PWM signal from an Arduino to an 8V PWM input on the control module. Looks like everything generated from the Arduino is 5V. Is there a way to generate an 8V PWM output or method of manipulating that signal to reach 8V?

# Answer
I'd suggest you use a power-source that delivers you 8V. Your Arduino takes anything from 7-12V to power it and it regulates it down to 5V. But you still can access the 8V from the RAW pins. Use a MOSFET like D1703L to control the 8V with an 5V Arduino digital pin.

You just connect Drain (D) to GND and Source (S) to your RAW 8V (don't forget to put your device between the Source and RAW 8V). Your Arduino digital pin goes to Gate (G), but to not draw to much current from the pin you might want to use a resistor of roughly 1kΩ.

This is the safest way that also allows for much higher voltage and also current for up to a few amps.

## EDIT

You should not connect the PWM pin to Ground on your Arduino. But you have to connect both grounds together. I'm not sure where your 8V comes from so I made a sketch where the 8V is an external source and powers your device along with the MOSFET.
> 1 votes

---
Tags: pwm
---


title: OTA Update Esp8266 without IDE

text:
# Question
Title: OTA Update Esp8266 without IDE
I was wondering if its possible to program the esp8266 to receive firmware updates without the use of an IDE to program.

Use Case: This device should be setup to the WiFi network scan an IP for a firmware update and update itself if needed.

Any help is greatly appreciated. Thank you

# Answer
> 1 votes
This: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino is a Arduino based firmware with support for OTA. It's written for Sonoff, but that is just a ESP8266 with a relay attached, you can easily adapt it to any ESP8266.

It uses a 'hard coded' address of a web server where it downloads the firmware, and updates are triggered by MQTT messages, but all of that should not be too hard to change to something else.

# Answer
> 0 votes
The firmware host will need a loader application that can talk to the bootloader in the ESP. You'll probably need to build a bit of hardware on the client to sequence grounding of the appropriate GPIO & Reset pins.

The application on the ESP would probably need to do something like:

* Discover the availability of an update;
* Tell the host to start its loader application;
* Begin the local I/O-pin sequencer to start the local bootloader.

The final step should cause the chip to reset and the bootloader to take control. Both the loader on the host and the bootloader will nned to be somewhat tolerant of the potential network delays.

---
Tags: arduino-ide, esp8266
---


# Question
Title: Is possible to process analogue inputs with variation frequencies in MHz?
Is it possible for Arduino boards to accurately process analog inputs that vary at MHz frequencies?

If possible, which Arduino board would be most appropriate for such application?

What adjustments would be required for it to handle such rapid analog input variations?

# Answer
Your typical ATMega-base Arduino cannot sample anywhere near that kind of speed.

It takes 13 clock cycles to sample an analog value on an ATMega chip, and the maximum clock frequency for the ADC is 1MHz. That gives you an absolute maximum sampling speed of 76923 samples per second. That means the highest frequency you can sample is 38461Hz.

There are better chips on the market with higher sampling speeds, but they aren't Arduino. Some can sample at the tens of millions of samples per second allowing you to sample frequencies in the low MHz. Other specialised ADC chips are available that can sample in the Gsps range which are what are used in oscilloscopes and high speed communication (fibre optic) systems etc. Working with these kind of chips needs quite a lot of skill though as the analog signal paths requires special design and consideration.

Also when sampling at those kind of frequencies you need a *lot* of high-speed memory, which no Arduino can ever even consider the possibility of having.
> 1 votes

---
Tags: analog-sampling
---


title: How do I convert a float into char*?

text:
# Question
Title: How do I convert a float into char*?
Asked this question on Electrical Engineering Stack Exchange and was directed here:

Pretty self explanatory; how would I go about converting a float into a char\*? I have code in which the float 'resistance' is constantly being updated. I would like to be able to update the variable 'result' to take the value of 'resistance'. Here is some of the code, in case it helps:

```
const char * result = "";
float resistance = 2.5;

result = resistance; //This bit (obviously) doesn't work

```

Thanks for your help!

# Answer
There is a function in the standard Arduino library called `dtostrf()`. I think of it as "Decimal to String Float". You pass in the float, how wide you want the whole number to be (if it will fit), the number of decimals of precision - and the buffer you want it to fill.

Note that! You need to provide the buffer, and you need to be careful to provide more than enough! Don't forget to add 1, too (to store the NUL character at the end):

```
char result[8]; // Buffer big enough for 7-character float
dtostrf(resistance, 6, 2, result); // Leave room for too large numbers!

```

This will give `result` values like `" 1.23"` and `" -1.23"` and `"123456789"` (without the quotes). Note the last example - it won't truncate the number if it's too large, and that ***10-*** character `result` (don't forget the final `NUL`) just overflowed your buffer...

Incidentally, if you specify a negative width, it won't right-justify the answer, it'll left-justify it (put any spaces on the end instead of the beginning).
> 25 votes

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


# Question
Title: Sending a text/notification with Arduino + ESP8266 Wifi shield
Is it possible to send a text message using an Arduino and the Sparkfun ESP8266 Wifi Shield using Temboo? I noticed that the ESP8266 might not be supported by Temboo and I was wondering if there is a workaround.

Thanks.

# Answer
> 3 votes
I work at Temboo.

While we don't officially support the ESP8266, we've found a couple of forum posts in which people have been able to get Temboo to work with the ESP8266. Here you go:

http://www.esp8266.com/viewtopic.php?p=24019

https://forum.arduino.cc/index.php?topic=337186.0

If that doesn't help, feel free to contact Temboo Support and we'll do our best to help figure out what's going wrong for you.

The key piece of info you need to be aware of is that you need to modify following Temboo library files:

```
\Arduino\libraries\Temboo\src\Temboo.cpp

\Arduino\libraries\Temboo\src\utility\
--ChoreoInputFormatter
--ChoreoOutputFormatter
--ChoreoPresetFormatter
--TembooSession
--tmbhmac
--tmbmd5

```

You need to modify all occurrences of `"avr/pgmspace.h"` in these files, changing it to `"pgmspace.h"`.

# Answer
> 0 votes
Yes, apparently you can.

I did a quick search on Google and found a GitHub library for the ESP8266 https://github.com/sabas1080/TembooForESP8266 and a post on the Arduino Forum https://forum.arduino.cc/index.php?topic=337186.0 that says you can download a skeleton program and hack that.

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


title: Answer power IN from two sources

text:
# Question
Title: Answer power IN from two sources
**Items:**

* Arduino Uno
* Laptop
* 7.4V 2s LiPo Battery
* Neewer 30A ESC

**Scenario:**

The LiPo powers the ESC while the Laptop USB powers the Arduino. If I unplug the USB from Arduino is loses power (obviously) and when I plug in the ESC to the arduino I get power again to the Arduino. I need the USB plugged in to receive `Serial` information from the laptop and I need pow+gnd plugged into the Arduino or else I get a lot of PWM noise rendering my ESC useless.

* ESC is 5V
* USB is 5V

**Question:**

This is my due diligence to not blowing anything up. What is the safest way to plug in power from both USB and the ESC? Same voltage, difference sources. Or can I just connect the grounds and call it good?

# Answer
> 2 votes
Connecting the grounds would work.

You could also connect the 7.2V lipo to the Vin pin on the UNO. The UNO will automatically switch from USB to Vin, if it's present.

---
Tags: power, usb
---


title: Interfacing to scale over RS-232

text:
# Question
Title: Interfacing to scale over RS-232
**Objective:** interface and Arduino MEGA to a Mettler Toledo SB32001 using the RS-232 communication protocol described in the manual.

**Equipment Used:**

**Background:**

I am using the `SoftwareSerial` library to try to communicate with the scale through MEGA pins 52 and 53. I have the level shifter connected to the scale using a through cable.

So far, I have tried to send the most basic command to the scale, and the command is both not executing, and not causing a status code to be send back (i.e. failure OR success). My Tx light on the level shifter flashes, but the Rx light never does.

Write string to screen:

`D "String"`

Because I have a through cable, I have tried switching the Tx and Rx pins in code. Neither has worked.

The from the scale has the following options I can set:

* **Baud Rate:** 150, 300, 600, 1200, 2400, 4800, **9600**
* **Parity:** 7b-E, 7b-no, **8b-no**, 7b-odd

Here is a minimal (non)working example of my code:

```
#include <SoftwareSerial.h>

const int pinTX = 53;
const int pinRX = 52;

scale = SoftwareSerial(53, 52);

void setup(){
    Serial.begin(9600);
    scale.begin(9600);
    delay(100);
}

void loop(){
    scale.println("D \"Hello!?\"");
    delay(100);

    while (scale.available()){
        Serial.print(scale.read());
    }
    Serial.println()
    delay(100);
}

```

**What I need:**

I need help figuring out where I should look next to solve this issue. I have tried switching the transmit and receive pins in software. I have tried using jumpers to switch the Tx and Rx pins in hardware. I have tried 7 and 8-bit settings with no parity. Nothing give me a signal back. Totally perplexed?

Is it my converter chip? Does anyone know of problems with this shifter? I know that it does not contain the industry standard MAX232

# Answer
> 2 votes
The solution turned out to be a couple of things, some of which mentioned by others in the comments.

Problems that needed to be fixed:

1. My level-shifter was a huge part of the problem. I switched to a MAX232-based chip and then I was a least able to get responses shorted lines 2 and 3 (Tx and Rx).
2. I needed a cross-over cable. I had tried this while troubleshooting, but because that alone didn't fix the problem, I had not idea whether or not that was the problem, or just one of the problems.
3. I needed to use the onboard UART (Serial1) rather than SoftwareSerial. The problem was that I needed to be able to set the protocol to 8 bits with no parity. This configuration parameter cannot be changed on SoftwareSerial, but is as simple as `Serial1.begin(9600, SERIAL_8N2)`.

Thank you for the help, and hopefully my mistakes make the process easier for others.

---
Tags: arduino-mega, communication, softwareserial, datalogging, rs232
---


title: 433mhz range optimization

text:
# Question
Title: 433mhz range optimization
I would like to get the **best range possible** from my **433MHz modules**. After A LOT of searching and reading, I'm convinced I should be able to cover **10m indoors with free line of sight**.

**\[update\]**
After some tips in the comments I changed a few things. It looks like with an Arduino receiving in stead of a Pi, I get an extra meter, 1,5m now so still terrible. And 'as a bang on the fire arrow' as we say in Dutch, I now use two whip antenna's parallel to each other.
Before moving to fix the reception on my Pi, I now first try to maximize the reception on the receiving Arduino. This makes it much more simple to investigate.

**\[update 2\]**
After some more tests I got to about 6 meters range. When the transmitter is behind 1cm of wood, this goes back to 30cm.
My current 433MHz modules are going into the garbage bin, I thank you all for your time. I will look for a more stable alternative and maybe try some other/better433MHz modules like these: http://www.ebay.com/itm/433MHz-Superheterodyne-RF-Link-kits-3400-ARM-MCU-Transmitter-and-Reveiver-/281169560721?hash=item4177030491:g:SUcAAOxyaTxTRKJn

**\[update 3\]**
The new modules made an enormous change. I can now send my data from across my house with no problems at all. No ground plane (will try that TwoD!) yet. Still on 5V transmitter voltage!

I've asked a question before about my 433MHz setup so for full disclosure:
433MHz sending not receiving

My current range is about 40/50cm, this is not much since I use a straight antenna ~17cm at the receiver and a coil antenna at the transmitter:
http://www.instructables.com/id/433-MHz-Coil-loaded-antenna/

These are the modules I use:
http://www.ebay.com/itm/-/221524421949?roken=cUgayN&soutkn=xKBBUo

And just FYI, I use these awesome working pumps:
http://www.ebay.com/itm/-/321779742264?roken=cUgayN&soutkn=hk1lrB

I have tried many antenna combinations and also upping the transmitter voltage to 12V but it doesn't help much. My aim is to reach 10m line of sight at the least.

* I notice that my Pi outputs 4.77V to the receiver.
* The 4 penlites now output around 5V so transmitter power is low.
* What I also like to test is adding 10uF caps to the V and GND of the transmitter but I have to wait for them to get delivered.
* I have the 10mw version of the transmitter, they may be just useless.
* The receiver stands in front of a speaker and a subwoofer, I turn those off when I test.
* The 433MHz modules came in pairs. I did not respect this and use any receiver with any transmitter, wonder if this is a problem. My end-goal is 3 transmitters on one receiver.
* Since I have multiple Tx/Rx modules, I swapped them to exclude DOA modules.
* Also tried these Helical antenna's, only made range worse; http://www.ebay.com/itm/-/171271811976?roken=cUgayN&soutkn=TmOnpH

My Arduino usses VirtualWire to send with 1000 baud to my Raspberry Pi, on the Pi side I use PIGPIO and the following code:

```
if __name__ == "__main__":

   import time
   import datetime
   import pigpio
   import vw
   import json
   import requests
   from requests.auth import HTTPDigestAuth

   # Setup receiving 433MHz port
   RX=27

   # Setup Baud rate 433MHz
   BPS=1000

   # Connect to local Pi.
   pi = pigpio.pi()

   # Specify Pi, rx gpio, and baud.
   rx = vw.rx(pi, RX, BPS)

   # Empty message
   msg = 0

   # Save the time
   start = time.time()

   # Run for 3 seconds
   while (time.time()-start) < 36000:

      # Count msg per cycle
      msg += 1

      # Sleep for .4 second
      time.sleep(0.4)

      # Run while receiver is ready
      while rx.ready():

         # String join received characters into message
         message = ("".join(chr (c) for c in rx.get()))

         # Print the received message to screen
         print(message)

         # Create data dictionary
         data = {}
         data['meting']    = message[8:11]
         data['bericht']   = message[4:7]
         data['plant']     = message[1:3]
         data['timestamp'] = str(datetime.datetime.utcnow().isoformat())

         # Print the data to the screen
         print(data)

         # Setup filename for local data backup
         filename = str('data/' + data['plant'] + data['bericht'] + data['meting'] + '.json')

         # Write JSON data file to disk
         with open(filename, 'w') as outfile:
            json.dump(data, outfile)

         # Sending data
         url = 'http://server:8000/v1/documents?database=plantjes&extension=json'

         # Setup headers
         headers = {
            'Content-Type': 'application/json'
         }

         # Execute request
         r = requests.post(url, json = data, auth=HTTPDigestAuth('plantje', 'password'))

         # Print request response
         print r

   # Cancel the receiving of data
   rx.cancel()

   # Stop PIGPIO listening on pins
   pi.stop()

```

This script sends the measurement of the Hygro sensor to a database in JSON. This works like a charm.

The Arduino uses this code:

```
#include <VirtualWire.h>
#include <Sleep_n0m1.h>

String pid = "p02";
const int led_pin = 11;
const int transmit_pin = 12;
const int hygroSensor = 0;
int hygroPower = 8;
const int pump_pin = 5;
int watering_level = 900;

int count = 0;
Sleep sleep;
unsigned long sleepTime;

void setup()
{
  // serial console setup
  Serial.begin(9600);
  Serial.println("setting up");

  // cycle sleep time in ms
  sleepTime = 10000;

  // virtualwire setup
  vw_set_tx_pin(transmit_pin);

  // setting of pin modes
  pinMode(hygroPower, OUTPUT);
  pinMode(led_pin, OUTPUT);
  pinMode(pump_pin, OUTPUT);

  // Bits per sec
  vw_setup(1000);
}

void loop()
{
  // delay to allow serial output to be ready after wake up
  delay(100);

  // cycle counter
  count++;

  // turn on hygro sensor module
  digitalWrite(hygroPower, HIGH);

  // wait a bit for hygro sensor to start
  delay(1000);

  // read the input on analog pin 0:
  int measure = analogRead(hygroSensor);

  // Start light to show transmitting
  digitalWrite(led_pin, HIGH);

  // log moment of sending
  Serial.println("Sending: " + String(measure));

  // create & send random message id
  String mid = "m" + String(random(100, 999));

  // Sending data
  String hygrodata = "d" + String(measure);
  dataSend(pid + mid + hygrodata);

  // Stop light to show transmitting
  digitalWrite(led_pin, LOW);

  // Wait a second
  delay(1000);

  // sleep code
  if(count >= 3)
  {
    // reset counter
    count = 0;

    // run pump routine
    //waterpump(measure, mid, pid);

    // log sleeping to serial console
    Serial.print("Going to sleep now..");

    // set sleep mode
    sleep.pwrDownMode();

    // turn off hygro module power
    digitalWrite(hygroPower, LOW);

    // sleep for: sleepTime
    sleep.sleepDelay(sleepTime);
  }
}

// Data sending funtion
int dataSend(String data) {
  // declare int for length of message
  int msglen;

  // set length of message +1
  msglen = data.length() + 1;

  // declare array of characters
  char envelope[msglen];

  // put string in array
  data.toCharArray(envelope, msglen);

  // log data to serial monitor
  Serial.println(data);

  // send data
  vw_send((uint8_t *)envelope, sizeof(envelope));

  // wait for sending to finish
  vw_wait_tx();

  // return 1 for succes
  return 1;
}

// Pump function
int waterpump(int measure, String mid, String pid) {
    // Log measure
    Serial.println(measure);

    // Water when needed
    if (measure > watering_level) {
      // Turn on pump 2 seconds
      digitalWrite(pump_pin, HIGH);
      delay(3000);
      digitalWrite(pump_pin, LOW);
      // Send pump data
      dataSend(pid + mid + "pump");
    }
}

```

This controls the sensing of the messages and also the water pump I use to water my plant automagically when needed. This also works like a charm.

# Answer
> 5 votes
I've had the same problem, couldn't get past 2 meters range. Until i noticed that the TX-Frequency was off by about 150kHz. I adjusted the RX Frequency (the module has a trimmer) and now 40-50m is possible with a wall in between.

# Answer
> 4 votes
On the transmitting side (with cheap AC switches as receiver), I've actually had good results with the cheap green squares, and the equally cheap 5 for a dollar 'Helical antenna 433MHz' you find everywhere on ebay :) I can reach all three levels of our house with that, and that's with only 5v supply on the green square, and it just sitting on a breadboard.

On request, picture of the antenna, soldered onto one of the cheap green transmitters, this one works well for me on 5V:

This antenna was bought as a set of 5 from: http://www.ebay.com/itm/171271811976

There's about 21 windings, with 5mm diameter, so that makes roughly 5mm * 3.14(=Pi) * 21 = 33 cm of wire in the coil.

# Answer
> 3 votes
The 433mhz modules can be sensible on the power lines, place a cap on the power input. Also a straight antenna works most of the times, but if you want some more distance, look into making a dipole antenna, there is a coil loaded diy antenna you can make that helps a little bit up from straight wire.

# Answer
> 2 votes
Have you ever tried the Nordic nRF24L01 based modules? They are available on eBay for very low cost, and operate in the 2.4 GHz band. They should offer a range of at least tens of meters indoors. I have had good success with these, and they are very easy to interface to Arduino.

# Answer
> 2 votes
I have the same TX/RX modules and two Arduinos and can get pretty good transmission reliability all throughout my house but it took some experimenting to figure out the largest factors in play (for me).

Module pairs should not matter, I got my 5 pairs jumbled up in a plastic bag, think only one was DOA. I use them together with Nexa wireless electric outlets and remotes since they operate on the same frequency and give me a decent reference point.

One thing I've noticed about the \[receiver\] modules is that they tend to auto-adjust to the signal strength. Blast at them with a transmitter at close range for a while and they will become worse at picking out the signs, from the noise at long range for some time. This appears to be true of the 433Mhz Nexa devices too. When starting to transmit from further away, it may take longer before the receiver figures out it's found a signal. Remember, these modules output only 1 or 0, not an analog signal, so they have to decide which level of noise to accept as 0 and when there is a 1.

My first mistake was not using a well attached antenna. A simple piece of strong wire is good enough in itself, but only if it makes good contact with the module. Good soldering skills always recommended.

My second mistake was not giving the transmitter enough power. It can handle 12V, so give it 12V (not on the data pin!). Only go lower after you got it to work at the needed distance.

Try with a large ground plane for both transmitter and receiver (no contact with the device itself!). I got a very good range with my receiver on my computer case and the transmitter on my fridge!

I could even get a reliable reading from a temp sensor from inside the garage 10m away from the house when getting about 2m off the ground, using 17cm plain straight wires as antennas with good ground planes. (Monopoles antennas need ground planes to bounce the signal off.)

Try visualizing the signal on the receiving side with an oscilloscope. If you gave an analog receiver it's probably easier to tell apart noise and real data. But if all you got is the RX module, hooking up the data pin to some kind of logged visualization will at least let you see how difficult it is to spot the data patterns.

Try increasing the length of your preamble before the actual data. It'll let the receiver adjust before it gets to the interesting bits.

Repeat your transmitted data. Include a piece of id data which changes with each message, but not with each repetition, and store the last received id for comparison before relaying it to wherever.

---
Tags: rf, virtualwire
---


# Question
Title: Basic WiFly server returning unexpected output within web client
Currently trying to implement a lightweight webserver using the WiFly shield and an Arduino UNO, this is the code I have so far:

```
#include <SPI.h>
#include <WiFly.h>
WiFlyServer server(80);

/* Function defs */
void cmd(void)  { SpiSerial.print("$$$"); }
void dhcp(void) { SpiSerial.println("SET IP DHCP 0"); }
void pass(void) { SpiSerial.println("SET WLAN PHRASE 22222222"); }
void ssid(void) { SpiSerial.println("JOIN BTHOMEHUB"); }
void port(void) { SpiSerial.println("SET IP LOCAL 80"); }
void ip(void)   { SpiSerial.println("SET IP ADDRESS 192.168.1.123"); }
void tcp(void)  { SpiSerial.println("SET IP PROTOCOL 2"); }
void boot(void) { SpiSerial.println("REBOOT"); }

/* Pointer to a handler function */
typedef void (*Handler)(void);
Handler table[8] = { cmd, dhcp, pass, ssid, port, ip, tcp, boot };

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

  for(short x = 0; x < 7; x++) {
    table[x]();
    delay(100);
  }
}

void loop() {
  WiFlyClient client = server.available();

  if(client){
    while(client.connected()) {
      if(client.available()) {
        client.println("<HTML><BODY><H1>Hi</H1><P>This is text.</P></BODY></HTML>");
      }
    }
    delay(100);
    client.flush();
    client.stop();
  }
}

```

This compiles well, but when hitting `192.168.1.123` in my web browser I get an ever-increasing output like:

```
*HELLO*<
<
<
<
<
<
<
<
<
<
<
< (cont.)

```

Definitely not the expected html. I have been playing with this code for hours now and this is the most positive output I can get. If I do a `Serial.write(client.read())` within `if(client.available()) {` I am able to print all the request information to the serial monitor, it just seems I am perhaps sending the data in an incorrect format? Any suggestions? Cheers

**Edit**

I have updated the codebase to include the http headers,

```
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println("");
client.println("<!DOCTYPE html>");
client.println("<HTML><BODY><H1>Hi.....

```

now I get I different (similar) output, seems like it is printing the first character of each new line

```
*HELLO*H
C
C

<
<
H
C
C

```

# Answer
Your browser sent a HTTP GET request. You need to send a HTTP response in kind, in accordance with the protocol, for your browser to correctly interpret the data. Something like this should do:

```
  #define TIMEOUT 100
  char response[] = "<HTML><BODY><H1>Hi</H1><P>This is text.</P></BODY></HTML>";
  unsigned long lastRead;
  ...

  while (client.connected()){
    if (client.available()){
      lastRead = millis();
      while (millis() - lastRead < TIMEOUT){
        while (client.available()){
          Serial.write(client.read());
          lastRead = millis();
        }
      }
      client.println("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: closed\r\n\r\n");
      client.print(response);
      break;
    }
  }
  delay(1000);
  client.stop();

```

EDIT:

It turns out that the Wifly shield sends a response status as well as "HELLO" by default. You have to disable that with a few commands:

```
set comm remote 0
set comm open 0
set comm close 0

```

This will ensure that "*HELLO*" isnt sent each time a client connection is made, though I'm not sure if this affects the default `HTTP/0.9 200 OK` response status that is always sent. You can try the sketch above with and without the response header to see what you get.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Cannot open file with underscores using the SD library
So I'm trying to create a new file that has underscores in its name. However, when I try this, no file is created.

**This works**

```
String fileName = "NMEA.txt";
mySensorData = SD.open(fileName.c_str(), FILE_WRITE);

```

**This does not work**

```
String fileName = "NMEA__23_33_3__16_7_29.txt";
mySensorData = SD.open(fileName.c_str(), FILE_WRITE);

```

Does anyone know why?

# Answer
> 3 votes
> \[The SD library\] uses short 8.3 names for files.

source

---
Tags: arduino-mega, sd-card
---


title: Blocking Serial Data

text:
# Question
Title: Blocking Serial Data
I am driving two stepper motor using serial data from Raspberry Pi to Arduino. Motors work fine when i am passing serial data but once i stop sending serial data, it doesn't accept serial data again unless I burn the program again in arduino. Here is code for that:

```
 #include <Driver.h>

//////////////////////////////////////////////////////////////////////////////////////////
/*
   Hardware pins defined in this section as connected from arduino to Pan DRV8834
   controller and tilt DRV8834 controller.M0 and M1 pins are common for both controllers
   ,hence declared only once(This is done to save number of pins, connecting it to
   additional pins , provide no special advantage since both both motors should be set
   to same level of microstepping).SLP pin is not currently used.

*/
//////////////////////////////////////////////////////////////////////////////////////////

#define PAN_DIRECTION_PIN 8
#define TILT_DIRECTION_PIN 7

#define PAN_STEP_PIN 10
#define TILT_STEP_PIN 9

#define M0 6
#define M1 5

#define MOTOR_SPEED 200

#define SLP 0
///////////////////////////////////////////////////////////////////////////////////////////

#define BAUD_RATE 230400      //Baud Rate for serial communication

///////////////////////////////////////////////////////////////////////////////////////////

/*
   field data for receiving buffer on arduino side , important for serial communication
*/
#define NUMBER_OF_FIELDS 2 // how many comma separated fields we expect
int fieldIndex = 0;           // the current field being received
int values[NUMBER_OF_FIELDS];  // array holding angles for both motors

const char startChar = '<'; //beginning character of a valid command
const char endchar   = '>'; //this will be ending character to ensure a valid command has ended
boolean storeString = false; //This will be our flag to put the data in our buffer

#define zeroCharacter 'z'

bool zeroCommand = false;

#define DATABUFFERSIZE 50
char dataBuffer[DATABUFFERSIZE + 1]; //Add 1 for NULL terminator
int dataBufferIndex = 0;

int procBufCounter;         //iterate through whole string to obtain the commands

float panAngle, tiltAngle;

int sign = 1;

    Driver stepper_pan(M0, M1, PAN_STEP_PIN, SLP, PAN_DIRECTION_PIN);
    Driver stepper_tilt(M0, M1, TILT_STEP_PIN, SLP, TILT_DIRECTION_PIN);

    void processCommand(char *buffer) {

        procBufCounter = 0;
        bool startprocessing = false;
        bool endprocessing = false;

        values[0] = 0;
        values[1] = 0;

        while ((procBufCounter < DATABUFFERSIZE) && (!endprocessing)) {

            char ch = buffer[procBufCounter];           //read the character while simulatneously increasing the buffer cursor

            if (ch == '<') {
                startprocessing = true;
            }
            else if (ch == '>') {
                values[fieldIndex] = values[fieldIndex] * sign ;
                fieldIndex = 0;
                endprocessing = true;
            }

            if (startprocessing)
            {
                if (ch == ',') {
                    values[fieldIndex] = values[fieldIndex] * sign ; // set value to the accumulated value
                    sign = 1;
                    fieldIndex++;
                }
                else if ('0' <= ch && ch <= '9' ) {
                    values[fieldIndex] = (values[fieldIndex] * 10) + (ch - '0');
                }
                else if (ch == '-') {
                    sign = -1;
                }
                else if(ch == 'z'){
                  zeroCommand = true;
                }
            }
            procBufCounter++;
        }
        panAngle = ((float)(values[0]))/100;
        tiltAngle = ((float)(values[1]))/100;

       bool panMoved = true, tiltMoved = true;
        stepper_pan.moveTo(panAngle);
        stepper_tilt.moveTo(tiltAngle);
      while (panMoved || tiltMoved) {
        panMoved = stepper_pan.run();
        tiltMoved = stepper_tilt.run();
      }

      if(zeroCommand){
        stepper_pan.reset_positions();
        stepper_tilt.reset_positions();
        zeroCommand = false;
      }

    }

    //////////////////////////////////////////////////////////////////////////////////////

    void setup() {
      stepper_pan.setStepMode(STEP_THIRTYTWO);
      stepper_pan.setSpeed(MOTOR_SPEED);
      stepper_tilt.setStepMode(STEP_THIRTYTWO);
      stepper_tilt.setSpeed(MOTOR_SPEED);
      Serial.begin (BAUD_RATE);
      Serial.flush();
    }

    void loop() {
      if (processString) {
        processCommand(dataBuffer);
        processString = false;
    //     dataBuffer = "";

      }
    }

    void serialEvent() {
      static int dataBufferIndex = 0;
      while (Serial.available() > 0) {
        char incomingbyte = Serial.read();
        if (incomingbyte == startChar) {
          dataBufferIndex = 0;  //Initialize our dataBufferIndex variable
          storeString = true;
        }
        if (storeString) {
          //Let's check our index here, and abort if we're outside our buffer size
          //We use our define here so our buffer size can be easily modified
          if (dataBufferIndex == DATABUFFERSIZE) {
            //Oops, our index is pointing to an array element outside our buffer.
            dataBufferIndex = 0;
            break;
          }
          if (incomingbyte == endchar) {
            dataBuffer[dataBufferIndex] = endchar; //null terminate the C string
            dataBuffer[dataBufferIndex + 1] = '\0';
            //Our data string is complete.  return true
            storeString = false;
            processString = true;
            dataBufferIndex = 0;
          }
          else {
            dataBuffer[dataBufferIndex++] = incomingbyte;
            dataBuffer[dataBufferIndex] = 0; //null terminate the C string
          }
        }

      }

    }

```

# Answer
I finally figured it out. It is due to reset whenever I open a port for serial communication. Attaching a 10uF capacitor between ground and reset fixed everything.
> 1 votes

---
Tags: serial
---


# Question
Title: Listen for USB "TX signal received" response on RX
Is there a usb signal I can send on TX that will generate a response from the computer on the RX only if the computer is active/not a wall usb power supply? I'm trying to use the Remote library when a button is pressed and sometimes it won't work because the computer is off/asleep/etc and in those instances I would like the arduino to behave differently but because I have no way of knowing if the USB power is coming from the wall or passively from a computer that's off or actively from a computer that's on, I can't know what behavior to take.

To be clear about the application in mind: Right now I have a device that sends keyboard signals to my computer using a modified version of Stefan Jones' modified USBAPI.h and HID.cpp files. It works fine but if you restart the computer you have to manually unplug and replug in the arduino to get it to work again. This is necessary every restart, is rather annoying, and adds unnecessary wear to the connector. This is also necessary if the arduino is connected before the OS has loaded. Additionally there are some LEDs on the device (not talking about the diagnostic lights on the arduino itself) that stay lit up at night even when the computer is off. If I could detect when the computer is off/unconnected it would be trivial to fix this.

# Answer
If an MCU which has a built in USB interface (such as the ATmega32u4 on a Leondardo) is properly configured and connected to an operating USB host, it will receive a "Start of Frame" packet every millisecond. I'm not very familiar with the details of the USB engine on that particular chip, but generally you can detect this as an interrupt, or as a change in a peripheral status register bit.

Going a step further, in the Arduino API an `if (Serial)` test will determine if the board is connected to a host which is in an active CDC-ACM "serial" session with it, ie, one that has a serial terminal or other program talking to it. Again, this only applies to those that implement USB within the chip on which the sketch is running.

**Chances are your problems can be fixed by enabling the AVR watchdog timer at one of its longer limits and resetting it in the USB ISR found in `USBCore.cpp`** Then if the the USB goes down (ie, the usual every millisecond SoF interrupt fails to happen for several seconds) your Arduino will reset. In the simple case, it will keep resetting as long as it has power and the USB is down, but you can put some startup logic to wait for the USB while resetting the watchdog if that bothers you. See for comparative example the implementation details behind the `if (serial)` and create something similar for your chosen USB mode.
> 2 votes

# Answer
As I understand, you are trying to implement some peripheral device based on AtMega 8-bit micro-controller that uses USB1.1 interface (FS or LS) to connect to USB host. Your problem seems to be that your host computer (unspecified) puts the port into SUSPEND (sleep), and does not wake up when you try to activate your device (button or something).

First, the USB2.0/1.1 interface does not have any "Tx" or "Rx", it is a half-duplex bi-directional bus. It has D+ and D-, and VBUS. But it is true that a USB peripheral device can generate a bus event called RESUME.

You have two choices. (1) either you make your host computer to never sleep or put USB ports into SUSPEND, or (2) make your device to support RESUME (aka "remote wake-up") function in full compliance with USB specifications.

In case (2) the driver for your device (on host computer) must support remote wake-up function, and this function must be enabled. Then when the host computer is planning to go into one of various sleep modes and decides to SUSPEND your device, it must send special control command to your device which should arm it for wake-up, and the host will be expecting it. In this case the host will never remove VBUS ("passively from computer"), so the device will be able to wake the bus up.

Is this your question about?
> 0 votes

# Answer
Upon having a clarification on what the problem essentially is, the answer is as follows:

(1) There is no way of knowing if the port is a wall charger or inactive computer port, initially. Therefore the initial device behavior must be identical in both cases – asserting pull-up on D+ (assuming it is USB 1.1 FS interface);

(2) However, if the port belongs to a computer, the connect event will awake the host, and the host will issue USB\_reset, and perform device enumeration. There is no need to “send any Tx signal” or else, the host will perform this activity by itself. The Arduino software must remember this.

(3) If the host decides to suspend the port (fell asleep), the device must transition into SUSPEND state, and Arduino software must remember this.

(4) If the port was initially in a state with USB totally disabled and does not wake up upon cable attach, see scenario (1);

(5) When/if the host computer is awaken, it will see USB attach status (D+ is up), and will start scenario (2).

In summary, the device (upstream facing port) must implement port functionality in full accord with port state machine described in USB2.0 specifications, Section 9 (Figure 9-1) and Appendix C.2 , Figures C-2 and C-3. As one can see, contrary to the assumption of OP, the port can be in more than two states, and Adruino software must have several different behaviors. Any half-baked implementation of the port state diagram is unacceptable and will cause some functional problem sooner or later.
> 0 votes

---
Tags: usb, arduino-micro, atmega32u4
---


# Question
Title: Limited to 1MP still captures with OV5642 ArduCam Mini + Arduino Uno
I have an Arducam-Mini-5MP with Arduino UNO R3. I am running the unaltered example ArduCAM\_Mini\_OV5642\_Video\_Streaming to the arduino and am running ArduCAM\_host\_v1.0.exe on my PC with huge successes.

In this state, I can reliably take photos at low resolution (up to 1280x720) in all tested settings. However, when I go to higher resolutions (2592x1944, 2048x1563, and 1920x1080), certain situations result in consistently corrupt images all with the exact size of 524288 bytes.

The images are corrupted whenever I point the camera outside my window, and images are fine when taking photos inside my house. At 1280x720, a typical photo inside my house is 80kb and a typical photo out the window is 190kb (more than double in size). I suppose some content of the photo is impacting the jpg compression?

Unfortunately, images are corrupt 100% of the time for the actual subject I want to take; but the camera works perfectly when I'm testing it indoors. In my scenario I can only capture 0.8MP before images become corrupt.

The frame buffer limit for Arducam is 512kb, so am I just running up against the constraints of the hardware? I feel a bit fooled because I bought a 5MP camera and can only take 0.8MP photos with it.

Is my understanding of this failure correct -- is this the frame buffer size being hit by conditions impacting jpg compression? Are there Arducam shields available with higher frame buffers? Can I avoid this situation somehow?

# Answer
> 0 votes
The Arducam Mini Shield is limited to 512kb frame buffer, so photos of larger resolution easily overflow the buffer. You can fit higher resolution photos onto the frame buffer by increasing the compression or adjusting other settings on the camera that reduce the file size of the resulting image (reduce saturation, windowing, etc).

To change the compression, adjust register 0x4407. The higher the number the more compression there is. The camera's default is 0x0C and the Arducam sample code sets it to 0x04. `myCAM.wrSensorReg16_8(0x4407,0x09);`

To adjust other settings on the camera (including the ones listed above) check out the detailed list of camera registers at http://www.dragonwake.com/download/camera/ov5642/OV5642-DS.pdf

Also, Arducam is releasing the Arducam Mini Plus which has an 8 MByte frame buffer and is available on advanced order for $35 USD by contacting Arducam directly.

---
Tags: arduino-uno
---


# Question
Title: Telit GPRS Module never returning and never timing out for command AT#FTPOPEN
Howdie! I trying to run a GPRS modem on an Arduino. My full stack is Nimbelink's NL-SW-GPRS Modem (containing Telit GE910-QUAD GPRS module) with the Nimbelink Arduino Development Shield on an Arduino UNO R3.

My goal is to connect to an FTP server and upload a file. I am following this guide from Nimbelink and section 3.3 from Telit's user guide.

I am stuck because the AT#FTPOPEN command doesn't seem to ever timeout nor does it return any result (ERROR or OKAY).

Here is the AT commands I am running:

```
AT
> OK

AT+CGREG?
> +CGREG: 0,1
> OK

AT#SIMDET=1
> OK

AT+CGDCONT=1,"IP","internet.com","0.0.0.0",0,0
> OK

AT#SCFG=1,1,300,90,600,200
> OK

AT#SGACTAUTH=0
> OK

AT#SGACT=1,1
> <My IP Address>
> OK

AT#FTPTO=100
> OK

AT#FTPOPEN="209.86.62.76","anonymous","anonymous",0

```

Where 209.86.62.76 is the IP address of ftp.earthlink.net which I am just using for testing purposes, but I have tried several others. I have tried with FTP mode 0 (active) and 1 (passive) with no change in behavior.

The AT#FTPOPEN just never returns anything (no ERROR and no OK). I've waited up to 5 minutes. The command does returns "ERROR" if I deliberately mess up the syntax of the command (eg. AT#FTPOPEN="") but for any valid format it just seems to hang.

Is this a known problem or something I can easy work around? Am I doing something crazy with my timeout values? Is there an easy way to test the context that I activated with the SGACT?

This is more of a question for an M2M forum, but I'm on an Arduino and it seems like there are many people using GSM modules on Arduino - so I thought I'd post here because I am a bit desperate. Thanks :)

# Answer
> 0 votes
The issues were:

1. Pin 9 MSM\_nRESET should be explicitly set to HIGH.
2. Pin 10 (DTR) and pin 11 (RTS) should be explicitly set to LOW.
3. The Nimbelink device requires 5V external power. With USB power, the modem can intermittently reset during period of high activity. If the modem resets, then the command can appear to run forever when nothing is actually running.
4. Must use FTPOPEN with connection type 1 (passive).

---
Tags: arduino-uno, gsm
---


title: Arduino UNO with Sparkfun MP3 Trigger

text:
# Question
Title: Arduino UNO with Sparkfun MP3 Trigger
I have a basic mp3 trigger with arduino uno setup:

Trigger - https://www.sparkfun.com/products/11029

Arduino Uno code:

```
#include <MP3Trigger.h>

//  Script Function:  RobertSonics mp3trigger (v2) paired with an Arduino UNO
//
//  Jumper Connections:   UNO  ------  mp3trigger (v2)
//             (UNO RX)     0  ------  TX
//             (UNO TX)     1  ------  RX
//             (Ground)   GND  ------  GND
//           (+5 volts)    5v  ------  USBVCC

#include <SoftwareSerial.h>
void setup(){
    Serial.begin(38400);    // Standard for mp3trigger
    Serial.print("t");
    Serial.write(1);
    delay(50000);
}

void loop()
{

}

```

I can't get it to play any tracks. The response in the Serial monitor just says tt

# Answer
So, from the beginning:

1. Have you got data on you SD card and is it is FT16 or FAT32 format?
2. Is the MP3 status light giving any indication of life?
3. Does the MP3 card detect when you start it up without the SD card in (One long flash).
4. Do you have a data file named "001SomethingOrOther.MP3"?
5. Have you tried the command "v" 0x00?
6. Have you tried the commands "S0" and "S1"?
7. Have you looked at the sample data on http://robertsonics.com/mp3-trigger-support/?

Hope that helps, an please post your finding, because mine arrives next week :)
> 1 votes

# Answer
Finally I got it working yesterday, and by accident!!!! Sorry it was not sooner, hope you had better luck with it. In any case if anyone wants to know what I did, you can read about it here. https://forum.sparkfun.com/viewtopic.php?f=14&t=44292
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Connect USB cable to GPIO pins on an Arduino Uno
**Electronics Newbie!!**

I want to connect a USB cable to my Uno's GPIO pins (and then connect it to a USB port on my computer). I have chopped off a USB cable from a keyboard, I read this and I'm hoping that the wires will be in the correct order (the keyboard was made by Dell). I'm a little confused about which wires go where.

# Answer
> 1 votes
The reason you are confused about which wires go where is simply because the Uno has no connection on it for a USB cable's wires.

You cannot directly interface an Uno to a USB port without extra hardware. What hardware you require depends on exactly what it is you think you are trying to achieve.

(There have been some attempts to create a USB device interface purely in software, but personally I wouldn't touch it with a barge pole - the GPIO of the Arduino is not electrically compatible with USB.)

---
Tags: arduino-uno, usb
---


title: Arduino crashing and rebooting

text:
# Question
Title: Arduino crashing and rebooting
I have recently written a program which is supposed to change the duty-cycle to keep the feedback voltage measured on A0, A1 constant. The problem is that the Arduino will start crashing at pretty constant intervals if it approaches it's target current. Once it crashes I have confirmed that it restarts the program (but crashes again in a moment).

Here's a sample of the serial output during the crash:

```
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 236.00
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.96
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.92
Current A: 64   Current B: 67   PWM A: 175.00   PWM B: 235.88
Current A: 64   Current B: 66   PWM A: 250.00   PWM B: 285114740000000000000000000.00
Current A: 0    Current B: 0    PWM A: 1.30     PWM B: 0.00
Current A: 0    Current B: 0    PWM A: 2.60     PWM B: 1.30
Current A: 0    Current B: 0    PWM A: 3.90     PWM B: 2.60
Current A: 0    Current B: 0    PWM A: 5.20     PWM B: 3.90

```

And here is **all** of my code:

```
#include <MemoryFree.h>

//Program to run on the Vegetarium
//Written by Leon Teichroeb on 12/6/2016

//Hardware description:
//-Oscillator 2A and 2B for the two onboard driver circuits
//-Pin 13 is attached to the "heartbeat" LED
//-Channel A (3) and B (11) current measurements on A0 and A1

//Functionality:
//-Drive Channels at set current

float PWMA = 0;
float PWMB = 0;

int TARGETA = 65;
int TARGETB = 65;

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

  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS20);
  OCR2A = (int)PWMA;
  OCR2B = (int)PWMB;
  digitalWrite(3, LOW);
  digitalWrite(11, LOW);

  delay(5000);
}

void loop() {
  int CURRENTA = analogRead(A0) / 4;

  if(CURRENTA < TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA > 250) {
      PWMA = 250;
    }
  }
  if(CURRENTA > TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA < 5) {
      PWMA = 5;
    }
  }

  int CURRENTB = analogRead(A1) / 4;

  Serial.println("Current A: " + (String)CURRENTA + "\t" + "Current B: " + (String)CURRENTB + "\t" + "PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.println("PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.print("freeMemory()=");
  //Serial.println(freeMemory());

  if(CURRENTB < TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB > 250) {
      PWMB = 250;
    }
  }
  if(CURRENTB > TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB < 5) {
      PWMB = 5;
    }
  }

  if(PWMA < 10) {
    digitalWrite(3, LOW);
  } else {
    analogWrite(3, (int)PWMA);
  }
  if(PWMB < 10) {
    digitalWrite(11, LOW);
  } else {
    analogWrite(11, (int)PWMB);
  }

  delay(40);
}

```

My circuit also provides power for the Arduino through a simple 7815 voltage regulator. The analog input does not exceed a few volts, and the PWM outputs are driving two logic level MOSFETs. If more information on the circuit is necessary please let me know!

EDIT: I have found out that it isn't a bug in the two feedback loops, because both work on their own. It crashes as soon as I use both feedback loops together. As far as I'm aware, there are no shared variables or data between them

# Answer
I finally figured it out, the Arduino was entering a current protection mode causing it to reset. The pins driving the MOSFETs were pulling too much current once the regulation started because of the BUZ11's input capacitance.

To fix the problem I just had to add 120 ohm resistors in series with the gate. This made the activation and deactation slower resulting in less current flow.
> 1 votes

---
Tags: programming, pwm, atmega328
---


# Question
Title: can teensy 3.0 or above run fingerprint scanner fps gt-511c1r?
I have an fps gt-511c1r fingerprint sensor module. I want to know whether i can run it using teensy 3.0 or above? I have tried it successfully using arduino uno.

EDIT: I have uploaded the fps blink sketch on the teensy 3.2 successfully, but the fingerprint scanner is not responding. Here is the code:-
#include "FPS\_GT511C3.h"
#include "SoftwareSerial.h"

```
     // Hardware setup - FPS connected to:
     //   digital pin 0(arduino rx, fps tx)
     //   digital pin 1(arduino tx, fps rx)

     FPS_GT511C3 fps(0, 1);

     void setup()
     {
         Serial.begin(9600);
         fps.UseSerialDebug = true;
         fps.Open();
     }

     void loop()
     {
        // FPS Blink LED Test
        fps.SetLED(true);
         delay(1000);
         fps.SetLED(false);
         delay(1000);
     }

```

connected fps tx to teensy rx(pin 0),
fps rx to teensy tx(pin 1),
fps vcc to 3.3v teensy,
fps gnd to teensy gnd.

# Answer
> 1 votes
The GT-511C1R is a 5V device. The Teensy 3.0 is a 3.3V device. You will require some level shifting as you would with any 3.3V Arduino connecting to a 5V device.

Besides that, yes, the Teensy 3.0 is more than capable of working with the fingerprint scanner. Will the software work? Most likely, but only trying it will confirm that.

---
Tags: teensy
---


# Question
Title: do i need an I/O shield for quadcopter motors
I would like to know if I need an I/O shield for the 4 ESC's on a Quadcopter I am building using Arduino Mega2560. The current to the ESC's should come from the battery itself and the data from the board so my first thought is that it is not needed however I wanted to be sure.

# Answer
> 1 votes
If the ESC accepts a signal that the Arduino can generate (i.e., 5V PWM) then no interfacing is required.

If the ESC is running from 3.7V (or similar) then some level shifting may be required to reduce the 5V signal to 3.7V, depending on the ESC. That may be built on a shield of some form or just with discrete resistors wired in manually to the leads.

---
Tags: arduino-mega
---


# Question
Title: Why does my servo execute an action in the beginning when the odds are almost 0?
I made a servo motor turn if the result of random(0, 10000) is less than or equal to 1. If that is the case, the motor turns to 130 degrees, to 50 degrees, and then to default position(90 degrees). It works well except whenever I turn on the Arduino, it automatically executes the turning maneuver. It usually takes dozens of seconds for the randomNum to be 1 or 0. However, the servo always turns right away at the beginning. Here is my code. I will make comments to help you understand what I was thinking. I used no delays.

```
#include <Servo.h>
Servo servo;
unsigned long timer=millis();//counter
unsigned long servoTimer;
boolean turned130 = false;
int randomNum;//will hold value 0-9999
bool backCheck = false;//variables to keep track which code block to call
bool checkingAllowed = false;
bool turned50 = false;
bool startChecking = false;

void setup() {
servo.attach(12);
servo.write(90);//set default position
servoTimer=millis();
}

void loop() {
timer=millis();//update counter each time
if(checkingAllowed==false){
randomNum = random(0, 10000);//random number generator
if(randomNum<=1){//small odds
  checkingAllowed = true;//makes this codeblock unable to run
  servoTimer=millis();
  servo.write(130);
  turned130=true;/sets variables to allow other if statements to run
  turned50=false;
}
}
if(timer-servoTimer>=1000 && turned130==true && checkingAllowed==true && turned50==false){//next codeblock that runs if random <= 1 after 1 second
turn50();
}
if(timer-servoTimer>=1000 && turned130==false && checkingAllowed==true && turned50==true){
turnBack(); one second later this runs
}
if(timer-servoTimer>=1000 && checkingAllowed==true && backCheck==true){
  backCheck=false;//servo turns back to 90
  checkingAllowed = false;//allows the main code block to be called
}

delay(2);//small delay
}

void turnBack(){
random50 = random(0, 160);
servoTimer=millis();
servo.write(90);
backCheck = true;
turned50=false;
}
void turn50(){
turned130 = false;
random130  = random(0, 160);
servoTimer = millis();
servo.write(50);
turned50=true;
}

```

It takes a while for the random number to be 1 or 0. I do not understand how 100% of the time, the servo executes the maneuver in the beginning. I will give any more information if you need it to aid me. The random() will soon be replaced by ping() of ultrasonic sensor. Then, the problem will probably disappear. I just want to be clear on what is happening here.

# Answer
Recognise that, despite the name, `random()` does not produce a *truly* random number. Because a computer is basically determinate, every time `random()` is called it produces results in a fixed sequence - it is possible that this sequence includes `0` or `1` straight away.

If you want it to start at a different point, you need to "seed" the random number generator by calling `randomSeed()` and passing in an integer. Note that it can't be the *same* integer every time - that would just move the sequence to the same point every time. The Arduino reference for `random()` suggests reading an unconnected analog input with `analogRead()` (which would produce different numbers at different instances in time) to "seed" the random number generator with a new starting position.

```
randomSeed(analogRead(A0)); // Seed random() with random starting point

```
> 3 votes

---
Tags: arduino-mega, programming, c++, servo, millis
---


title: Using interrupts for two MCP23017

text:
# Question
Title: Using interrupts for two MCP23017
I am creating a simple shield with two i2c `MCP23017` chips. Each `MCP23017` has two interrupt pins, but the Arduino Uno only has two interrupt pins (`pin 2` and `pin 3`).

The way I understand it, interrupts are there to tell the Arduino something has changed, so it can then poll the `MCP23017` for the latest pin reads.

How can I connect the 4 interrupt pins to my Arduinos 2 pins?

# Answer
> 4 votes
The MCP23017 (and it's sister the SPI-based MCP23S17) can have their interrupt pins set to "mirror" mode. In this mode both pins are internally joined so when an interrupt occurs on any port both pins activate. This is done using the `MIRROR` bit of the `IOCON` register. Using this will turn your 4 interrupt pins into just 2, one for each Arduino INT pin.

Should you want to add more in the future, or if you find you want to use one of the interrupt pins on the Arduino for something else, there is also the `ODR` bit in the `IOCON` register. This sets the interrupt pins to be *open drain*, which means that all of them can be wired together into just one INT pin on the Arduino. Add a pullup (or enable the internal pullup) and you have have many IO expanders on one INT pin. Of course, that then means that you have to poll all the expanders to find which of them triggered the interrupt, so could slow things down somewhat depending on how you are using it.

---
Tags: arduino-uno
---


# Question
Title: WebSocket client for ArduinoHttpClient conditional if with readString() incoming data buffer
I'm having issues implementing a web socket on the Arduino/Genuino to procress a string received and do something respectively.

I'm using SimpleWebSocket example, edited for my purpose, from the ArduinoHttpClient...

don't seam to get the hangs of it. don't know what i'm doing wrong, cannot store the received string object on a string variable or use the readString() method on and if statement to compare with a string to decide what flow path to get in to

This is the code im trying:

```
/*
  Simple WebSocket client for ArduinoHttpClient library
  Connects to the WebSocket server, and sends a hello
  message every 5 seconds

  note: WiFi SSID and password are stored in config.h file.
  If it is not present, add a new tab, call it "config.h"
  and add the following variables:
  char ssid[] = "ssid";     //  your network SSID (name)
  char pass[] = "password"; // your network password

  created 28 Jun 2016
  by Sandeep Mistry

  this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "config.h"

char serverAddress[] = "192.168.1.140";  // server address
int port = 8000;

WiFiClient wifi;
WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
int count = 0;

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

  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void loop() {
  Serial.println("starting WebSocket client");
  client.begin();

  while (client.connected()) {
    int messageSize = client.parseMessage();

    if (messageSize > 0) {
      String test = client.readString();
      Serial.println(client.readString());
      Serial.println(test);
      if (client.readString() == "off") {
        Serial.println("low");
        digitalWrite(6, LOW);
      }
      else {
        Serial.println("high");
        digitalWrite(6, HIGH);
      }
    }
  }

  Serial.println("disconnected");
}

```

On the example above, you can see in the void loop, after I check there's incoming data with messsageSize I store the incoming data using readString on a variable test, which I then println, this shows and empty line, although when I directly via println readString it shows some data, so the data is coming in... subsequently when I try to use the data from the incoming buffer on and if statement to compare with a string is wont work.

I've tried everything I can think off, puting the string to compare in to a variable and compare them, using Compare method from the object and I cannot even remember what else.

does anyone have any advice on how to do this, maybe the library is buggie, maybe I'm doing it wrong, any other libraries that anyone can recommend, I've looked around and this is the only one that looked simple enough to get started with and had the most examples.

# Answer
this workes:

```
if (messageSize > 0) {
      //Serial.println(client.readString());
      String input = client.readString();
      Serial.println(input);

```

looks like reading from the method readString() empties the buffer hence cant use it again, what I did is store it on a String object variable "input" and use that.

It worked.
> 1 votes

---
Tags: string, mkr1000
---


title: HM-10 discovery issue

text:
# Question
Title: HM-10 discovery issue
i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue thanks in advance

# Answer
The HM-10 is a BLE-only device.

Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.

The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.

Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on *both* devices.
> 1 votes

# Answer
Detecting the physical Bluetooth layer is likely different from detecting the underlying protocol. So it might be that the Arduino code is waiting until it sees a specific Bluetooth protocol. I am guessing that it wants to use a serial Bluetooth protocol (as oppose to music or some other protocol). You have not given enough details to determine if this is the problem. However, I would next test your devices / hardware by loading up what is assumed to be working code on both your Android and your Arduino to test the connection. The code in this project looks promising:
> -1 votes

---
Tags: bluetooth
---


title: Arduino Driver can I use only PNP?

text:
# Question
Title: Arduino Driver can I use only PNP?
is it possible to use a normal PNP transistor to drive a motor? I'm kinda new to this stuff so I want to be on the safe side, so I don't damage my Arduino Uno because of the motor.

I have made a motor driver? https://circuits.io/circuits/2493784-test-1 But I'm not sure if i have done right and I wont break any components.

So does this work without any problems and have I done it right?

I'm not trying to make a H-bridge because I need both PNP and NPN?

EDIT:Picture

# Answer
You need an NPN transistor to run a motor like that off of an arduino. Take a look at this article: https://learn.sparkfun.com/tutorials/transistors

> Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
>
> This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because Vb would always be less than Ve.

Using an NPN transistor is the way to go here. Keep in mind that you can't control the direction of a motor with just one transistor, however.
> 1 votes

# Answer
Despite the fact that the circuit you have is completely wrong, there is one fundamental thing that is stopping you using a PNP transistor.

With an NPN transistor you have to raise the voltage on the base *above* the ground voltage (this voltage is called *V\_BE*, the *V*oltage between *B*ase and *E*mitter). Typically that voltage is around 0.7V.

With an PNP, because the emitter is wired to your 9V rail, *V\_BE* must therefore be relative to 9V, not ground, so the voltage on the base must be less than 0.7V *below* 9V to turn on. Which in itself is fine - a LOW will be around 0V, which is about 9V less than 9V. So it will turn on. The problem comes when you want to turn it off. You need to get the base voltage *above* 8.3V (9V - 0.7V), and that is impossible for an Arduino to do.

So normally a PNP transistor is switched by using an NPN transistor to switch the base of the PNP between 9V (pulled up through a resistor) and 0V (switched through the NPN).

And that then becomes pretty much pointless, since you are then adding a second, NPN, transistor, and you could just as well use the NPN alone to switch the motor, making the PNP completely redundant.
> 1 votes

# Answer
When connecting together several circuits that have different supply voltages, common practice is to make them all have a common negative supply rail. This is called “*common ground*”. As explained in Majenko’s answer, you would need an NPN transistor for that.

If you want to use a PNP instead, then you could forget the common practice and do everything “backwads”: if you connect together the positive ends of the power supplies, you will have a “common VCC” instead of a common ground. Relative to the Arduino ground, your 9 V battery will have one pole at +5 V and the other at −4 V.

The wiring is the following:

* connect the emitter to +5 V (Arduino +5 and battery +)
* connect the base to an Arduino output through a resistor
* connect the collector to the motor
* connect the other end of the motor to the battery −
* put a free wheeling diode in parallel with the motor.

**Edit**: Below is an ASCII art rendering of the circuit. Beware that the motor is ON when the Arduino output is LOW.

```
+-----------+
|         5V|-----------------+-------------------+
|           |                 |                   |
|  Arduino  |                 |                   |
|           |    ,-----.  B |< E                 ___ +
|        D13|----|     |----|    PNP              _
+-----------+    `-----'    |\                   ___
                              |C                  _
                              |                  ___
                              +---------+         _
                              |         |        ___ 9 V batt.
                              |         |         _
                             ---        |        ___
                              ^       motor       _
                             / \        |        ___
                             ---        |         _  −
                              |         |         |
                              |         |         |
                              +---------+---------+

```
> 1 votes

# Answer
I don't know what you are trying to do, because the link fails to display in my browser.

In general there is no reason why you can not use a PNP transistor, providing you use appropriate polarities, and assuming common-emitter mode, reference to the +5V rail rather than Gnd.

Having said that, you would need some specific reason. In general NPN devices are cheaper and/or outperform PNP, all other things being equal.
> 0 votes

---
Tags: motor, transistor, h-bridge
---


# Question
Title: How to handle low temperatures using Arduino Uno?
I want to create a simple electronic temperature sensor using the Arduino Uno.

The environments I want it to handle is inside a fridge and near a heater.

Although I am sure the Arduino can easily handle a heater; my issue is that the Arduino may not be able to handle a fridge.

A fridge also has the added problem of causing water vapor (and we all know water + electronics is never a good idea).

So my question is:

* How would I create a temperature sensor using my Arduino Uno, that I can put in my fridge?
* Are there any other problems I have not considered and how do I solve them?
* Will I need a special type of casing? If so, which type?
* Is an Arduino Uno even the best tool for this task?

# Answer
Your Arduino does not have to be in the fridge, just the sensor. You can always choose waterproof sensor like this one to use with the arduino. Then you can always store your arduino outside the fridge. Same goes for the heater. Try to keep the arduino at room temperatures to avoid decreasing its life unnecessarily.

As for an actual answer to the temperature ranges, here is a good answer
> 1 votes

# Answer
Humidity would be your biggest enemy. The fridge is a very moist environment for two reasons:

* The colder the air temperature, the less moisture it can hold overall, thus saturating more quickly and reaching a higher relative humidity.
* Lots of moist foodstuffs in an enclosed space.

You should be OK as long as the enclosure you choose has plenty of ventilation to avoid a temperature differential or trapping moisture. Either of those two conditions could cause and even larger increase in humidity or, worse, condensate to form.
> 1 votes

---
Tags: arduino-uno, temperature-sensor, safety
---


title: Confusion about PNP transistors

text:
# Question
Title: Confusion about PNP transistors
I was reading through SparkFun's article on transistors when I came across something that confused me. The article showed this circuit:

With this description:

> Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
>
> This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. **For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor.** In that case it’d be impossible to turn the switch off because VB would always be less than VE.

I am confused because the part about the Arduino not being able to turn off a PNP transistor makes sense, but doesn't the circuit shown feature exactly the situation described that the transistor wouldn't work in? Is this an oversight by me and is there something else going on here that I don't understand, or is this a mistake in the article?

# Answer
The article is saying that the **circuit wouldn't work**, thus it illustrates (correctly) something that won't work. What is the confusion?

To turn the PNP transistor off, the base voltage needs to be low *with reference to the emitter voltage*. Thus with an emitter voltage of 12V, and the most the Arduino can output is 5V, the transistor will never be off.
> 2 votes

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