title: using millis() for a timer

text:
# Question
Title: using millis() for a timer
Basically the user presses a button and cycles thru 3 different modes. Mode 1 the LED is on, mode 2 the LED is off and mode 3 the LED is kept on for a certain amount of time. I'm using the millis() to keep track of the time. the LED in the third mode just stays on and never switches to off. I have the Serial.Writes in there to help me debug. I have the delay after the button read since if I didnt put it in it would register a lot of button presses.

```
int ledPin = 5;
int buttonApin = 9;
int ledMode = 0;

boolean lastButton = HIGH;
boolean currentAButton = HIGH;

// debounce button
boolean debounceFUNC(boolean last)
{
    boolean current = digitalRead(buttonApin);
    if (last != current)
    {
        delay(5);
        current = digitalRead(buttonApin);
    }
    return current;
}

void setMode(int ledMode)
{
    // turns on led
    if (ledMode == 1)
    {
        digitalWrite(ledPin, HIGH);
    }
    // turns off led
    if (ledMode == 2)
    {
    digitalWrite(ledPin, LOW);
    }
    // timer - turns off after 5000
    if (ledMode == 3)
    {
        long interval = 5000;
        unsigned long cMillis = millis();
        static unsigned long pMillis;

        if (cMillis - pMillis > interval)
        {
        pMillis = cMillis;
        digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
        }
        else
        {
        digitalWrite(ledPin, LOW);
        Serial.println("Off");
        }

        }
    }

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    pinMode(buttonApin, INPUT_PULLUP);
}

void loop()
{
    // sets led mode
    currentAButton = debounceFUNC(lastButton);
    delay(500);
    if (currentAButton == LOW)
    {
        ledMode++;
        Serial.println(ledMode);
    }
    else if (ledMode > 3)
    {
        ledMode = 0;
    }
    // ledMode function call
    setMode(ledMode);
}

```

screenshot of the serial monitor.

# Answer
The problem is in the logic, basically your statement:

```
    if (cMillis - pMillis > interval)
    {
       pMillis = cMillis;
       digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
    }
    else
    {
       digitalWrite(ledPin, LOW);
       Serial.println("Off");
    }

```

will always be true, this is as the difference in time, `cMillis - pMillis` is always greater than `interval`.

This means that it never enters the else statement to turn off the LED, and thus means the `else` statement is usually the first thing that rune at `ledMode = 3`.

What you need to do as the simplest fix is to change your comparison, change **`>` to `<`**, in the is statement:

```
if (cMillis - pMillis > interval)

```

to

```
if (cMillis - pMillis < interval)

```

this will ensure the LED is always on during the 5000 mS and then as soon as it is greater it will definitely go to the `else`
> 1 votes

# Answer
There is a problem with your debounce logic. You want to compare the current button state with the previous state, which is supposed to be stored in `lastButton`. But that variable is initialized to `true` and then *never* updated. Your program may work better if you issue `lastButton = currentAButton` somewhere.

You can find lots of tutorials on button debouncing, and there are several methods. The one you are using, which is based on `delay()`, is probably the worst: it should work in this simple case, but `delay()` is toxic as soon as your Arduino has more than one thing to do. A very common (and my preferred) method is to just ignore the button for some “debounce time” after you detect a state change. A debouncer function can be based on something like:

```
if (now - last_state_change < DEBOUNCE_TIME)
    return last_state;

```

Then you have to detect the button presses, which is not the same as the button being down: you don't want to interpret the down state as a continuous stream of very fast button presses. Instead, a button press is the button being down now whereas it was up on the previous read. A `button_press()` function could call the `debounce()` function and then have something like

```
bool press = last_state && !state;

```

This is effectively detecting falling edges of the debounced button. You can combine the debouncer and the falling-edge detector into a single function as follows:

```
bool button_press()
{
    static bool last_state;
    static uint32_t last_state_change;
    uint32_t now = millis();

    // Ignore the button during the debounce time.
    if (now - last_state_change < DEBOUNCE_TIME)
        return false;

    bool state = digitalRead(BUTTON_PIN);
    if (state != last_state) last_state_change = now;
    bool press = last_state && !state;
    last_state = state;
    return press;
}

```

Next there is the management of the LED states. What you are trying to implement is called a finite state machine, sometimes abbreviated “FSM”. If you search the Web for that term, you will find a few examples on how to implement it. It canonically revolves around a `switch` statement that enumerates all the possible states and tells what to do in each of those states. Something like

```
switch (state) {
    case STATE_FOO:
        if (some_condition()) {
            do_some_action();
            state = STATE_BAR;  // switch to the next state
        }
        break;
    case STATE_BAR:
        ...
}

```

Below is a FSM implementation of your LED logic. Note that you did not completely specify what should happen when the “timed” state times out: you could go to a forth “timed out” state, or you could just go back to the “off” state. In the code below I've taken that last option:

```
void loop()
{
    static enum { OFF, TIMED, ON } state;
    static uint32_t timed_started;
    uint32_t now = millis();

    // Switch state on button press.
    if (button_press()) switch(state) {
        case OFF:    // -> TIMED
            digitalWrite(LED_PIN, HIGH);
            state = TIMED;
            timed_started = now;
            break;
        case TIMED:  // -> ON
            // LED is lready on.
            state = ON;
            break;
        case ON:     // -> OFF
            digitalWrite(LED_PIN, LOW);
            state = OFF;
            break;
    }

    // Turn off after LED_ON_TIME.
    if (state == TIMED && now - timed_started >= LED_ON_TIME) {
        digitalWrite(LED_PIN, LOW);
        state = OFF;
    }
}

```

Note that it would have been more “canonical” to have the tests `if (button_press())` inside the `switch` rather than the other way around. Then the test for the timeout would also be inside the same big `switch`. It's just that it seemed easier to me to write it this way.

For the sake of testability, here are the pieces that would be missing for having a complete working program:

```
const int BUTTON_PIN = 9;
const int LED_PIN = LED_BUILTIN;
const uint32_t DEBOUNCE_TIME = 50;
const uint32_t LED_ON_TIME = 5000;

void setup()
{
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
}

// button_press() and loop() as above.

```
> 0 votes

---
Tags: time
---


# Question
Title: why am I losing data over serial communication between arduino and pc
I'm working on a project for school. I'm trying to rotate a servo by writing the letter that identify the servo and then the angle.

the problem is that sometimes the last number of the angle is lost or the whole angle all together. for example i want to rotate servo "a" 50 degrees. i enter a50 this works most of the time but sometimes i only get a 5 without the zero and sometimes i just get a zero. can anyone help, thanks.

please keep in mind i only did computer science in high school and intro to c++ in college. go easy on me please.

attached is the code and an image illustrating my problem.

```
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;

String angle1="";
String angle2="";

char serialbuffer[4];
int index=0;
int charcount=0;

int lastangle;
int dif;

void setup() {
  servo3.attach(3);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

  serialbuffer[0]='0';
  serialbuffer[1]='0';
  serialbuffer[2]='0';
  serialbuffer[3]='0';
}

void loop() {

       charcount=0;
       index=0;
       serialbuffer[0]=99;

   while (Serial.available() > 0) {

      char charbuffer = Serial.read();
       if(charbuffer=='\n'){
          index=0;
        }
        else{

           serialbuffer[index]=charbuffer;
           index++;
           charcount++;
          }

      }

  angle1="";
  if(serialbuffer[0]=='a'){

      for(int i=1;i<charcount;i++){
         angle1+=serialbuffer[i];
      }
      move_servo3(angle1);
      index=0;
      serialbuffer[0]=99;
    }
  delay(15);
}

void move_servo3(String angle2){

   Serial.println(angle2.toInt());
   servo3.write(angle2.toInt());

  }

```

# Answer
> 1 votes
Are you hand-typing the commands? It is pretty difficult to do that consistently. I ask because your code collects data from the serial buffer until the buffer is empty - i.e. when you pause even slightly in your typing - and tries to act on whatever it has collected so far. That may be (probably will be!) an incomplete command. Even if your terminal uses line-by-line entry, there is still the risk that your code could notice an empty buffer between characters within a line.

Try collecting characters until it sees a newline, instead. That is probably what you intended, and it will be immune to your typing speed. You'll still need to test for .available, but that should only allow the code to collect more characters. Keep collecting until it sees a newline.

What (I think) is happening now is called a race-condition. That means that the program's behavior is dependent on which of two (or more) events happens first, and the order of their occurrence is indeterminate. Race conditions are especially hard to find when the order of two events is almost always the one you expected. Notice the "gotcha" word in that sentence? :)

# Answer
> 0 votes
I don't understand why the problem is being caused, your code looks OK, but this is too big for a comment.

* I think it would be better if you initialised you serialbuffer with NULL rather than '0'. This way angle2.ToInt() will just read the number you have typed, rather than what was in there last time. Try entering a111 and then a2. You will get a211 second time. NULL is the end of a string.
* In loop() change your while loop to this:

```
char charBuffer = Serial.read();
while (charBuffer != '\n' && index < 4) // Index < 4 stops a buffer overflow.
{
  serialbuffer[index++] = charBuffer;
  charCount++;
  charBuffer = Serial.read();
}

```

This will keep reading until it sees a new line, which I think is what you want.

* You don't need the delay statement now, the speed is controlled by how fast you can type.
* The for statement could be changed to:

```
for (int i = 0; i < 4 && serialbuffer[i] != NULL; ++i)

```

If you make these changes I think it might help see the problem. Also printing the number that has been typed in before the for loop might help, it will print now because you have initialised it to NULL.

---
Tags: serial
---


# Question
Title: Relay switching problem with ATmega328P + 10 relays
I am trying to switch ON/OFF 10 relays connected to ATmega328P via Bluetooth HC-06 module. The problem I am facing is that when I try to Switch ON more than 3-4 relays, some of the previously ON relays switch OFF and the ATmega328 restarts.

I am using a 12V 2A power supply.

I have set up my circuit as shown below

My code

```
int r1 = 4, r2 = 5, r3 = 6, r4 = 7, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 12, r10 = 13;
char state;
String msg;
int r = 0;

void setup()
{

    pinMode(r1, OUTPUT);
    pinMode(r2, OUTPUT);
    pinMode(r3, OUTPUT);
    pinMode(r4, OUTPUT);
    pinMode(r5, OUTPUT);

    pinMode(r6, OUTPUT);
    pinMode(r7, OUTPUT);
    pinMode(r8, OUTPUT);
    pinMode(r9, OUTPUT);
    pinMode(r10, OUTPUT);

    Serial.begin(9600);
}

void loop()
{

    while (Serial.available())
    {
      state = Serial.read();

      if (state == '\n')
        break;

      msg += state;

    }

    if (msg.length() > 0)
    {
      /*Serial.print("Data: ");
      Serial.println(msg);*/

      if (msg == "on1")
      {
          digitalWrite(r1, HIGH);
          Serial.print("O1");
      }
      else if (msg == "on2")
      {
          digitalWrite(r2, HIGH);
          Serial.print("O2");
      }
      else if (msg == "on3")
      {
          digitalWrite(r3, HIGH);
          Serial.print("O3");
      }
      else if (msg == "on4")
      {
          digitalWrite(r4, HIGH);
          Serial.print("O4");
      }
      else if (msg == "on5")
      {
          digitalWrite(r5, HIGH);
          Serial.print("O5");
      }
      else if (msg == "on6")
      {
          digitalWrite(r6, HIGH);
          Serial.print("O6");
      }
      else if (msg == "on7")
      {
          digitalWrite(r7, HIGH);
          Serial.print("O7");
      }
      else if (msg == "on8")
      {
          digitalWrite(r8, HIGH);
          Serial.print("O8");
      }
      else if (msg == "on9")
      {
          digitalWrite(r9, HIGH);
          Serial.print("O9");
      }
      else if (msg == "on10")
      {
          digitalWrite(r10, HIGH);
          Serial.print("O10");
      }

      //off---------------------------------------------------------

      else if (msg == "off1")
      {
          digitalWrite(r1, LOW);
          Serial.print("F1");
      }
      else if (msg == "off2")
      {
          digitalWrite(r2, LOW);
          Serial.print("F2");
      }
      else if (msg == "off3")
      {
          digitalWrite(r3, LOW);
          Serial.print("F3");
      }
      else if (msg == "off4")
      {
          digitalWrite(r4, LOW);
          Serial.print("F4");
      }
      else if (msg == "off")
      {
          digitalWrite(r5, LOW);
          Serial.print("F5");
      }
      else if (msg == "off6")
      {
          digitalWrite(r6, LOW);
          Serial.print("F6");
      }
      else if (msg == "off7")
      {
          digitalWrite(r7, LOW);
          Serial.print("F7");
      }
      else if (msg == "off8")
      {
          digitalWrite(r8, LOW);
          Serial.print("F8");
      }
      else if (msg == "off9")
      {
          digitalWrite(r9, LOW);
          Serial.print("F9");
      }
      else if (msg == "off10")
      {
          digitalWrite(r10, LOW);
          Serial.print("F10");
      }
      else if (msg == "offall")
      {
          digitalWrite(r1, LOW);
          digitalWrite(r2, LOW);
          digitalWrite(r3, LOW);
          digitalWrite(r4, LOW);
          digitalWrite(r5, LOW);
          digitalWrite(r6, LOW);
          digitalWrite(r7, LOW);
          digitalWrite(r8, LOW);
          digitalWrite(r9, LOW);
          digitalWrite(r10, LOW);
      }

    }

    msg = "";

    delay(1000);
}

```

# Answer
I can see lot of problems.

* No decoupling capacitors on ATMega.
* Capacitors on both sides voltage regulators are usualy essential for regulator stability.
* Big voltage drop on regulator - if it's overheating, thermal shutdown might happen. For example 7V drop @ 350mA (about four relays) results into 2.45 Watts turned into heat.
* Bare HC06 doesn't like 5 Volts on its 3.3V logic level input
* Xtal oscilator usualy requies two capacitors (22pF) for better stability.
> 3 votes

# Answer
Where do the switching transistors get their +5v? The dropouts and shutdown suggest that the "+5v" is sagging as more relays try to draw off of it. Try supplying the relay current from a more capable supply, possibly a voltage regulator off the +12v supply - it will be wasteful but if it works, you'll know that was the problem.
> 1 votes

---
Tags: bluetooth, atmega328, relay
---


title: Motion Tracking Using Arduino?

text:
# Question
Title: Motion Tracking Using Arduino?
I'm trying to make a human following robot.Tried using ultrasonic sensors to follow a specific person by Having ultrasonic sensor with the person to send echo to the robot,But it didn't workout. Any way to track a specific person and follow ? Any sensors/algorithm to track fast moving object(a person but not specific)?

# Answer
> 0 votes
If you are clever with software you may be able to simplify your hardware requirements down to 1 IR ASK transmitter and 1 IR ASK IR receiver.

I mention IR ASK as the transmitter (simply a remote control with a button pushed down) and the receiver are COTS parts.

Consider your robot looking for an IR ASK signal by rotation until one is found. Then consider your robot traveling in a serpentine path adjusting its average vector along the angle where the IR ASK transmitter is detected.

You might need to create an variable aperture the IR ASK receiver will look through. This is because most IR ASK receivers have a built in AGC circuit which will abstract you from knowing how strong the signal is.

So, while searching, the aperture will be large allowing the IR ASK receiver a wide field of view. But once locked on, the aperture should be reduced so that the robot will know in which direction the IR ASK signal is from.

# Answer
> 1 votes
You need the person to emit a signal and the robot to receive it, sounds simple, but it isn't. What you are trying to do is position fix the transmitter, in the same way as an ATC locates a plane.

The robot will need at least two directional receivers positioned a certain distance apart (depends of frequency and accuracy) to allow the robot to triangulate the transmitter. The more receivers the more complex the triangulation. The frequency of the signal you transmit will affect the distance that the robot can be from the person, research Frequency spectrum and transmission distances. The longer the distance the signal can travel the stronger the signal will be at close range. You also have to counter reflections and side lobes which will give you inaccurate readings on the transmitter direction. Once you have dealt with all of that all you need to do is scan for the strongest signal on your frequency, triangulate it and then head towards it. Whatever sensor you use the theory is the pretty much the same.

Could you tag the person with a GPS receiver and WIFI/BT and get it to transmit its location. The robot could then consult its GPS and calculate the delta and move accordingly.

---
Tags: sensors
---


# Question
Title: Increase the resistance of a photoresistor with increase in light intensity
I'm building a laser tripwire of sorts and instead of shutting up when the laser points on it (which is essential for my project) it beeps louder.

Here's the code

```
int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
    pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
    if(analogRead(0) < 750){ // this number depends on calibration of the photocell
        digitalWrite(buzzPin, HIGH); // turns buzzer on
        delay(5000); // waits for 1 second
        digitalWrite(buzzPin, LOW); // turns buzzer off
    } else{
        digitalWrite(buzzPin, LOW);
    }
}

```

# Answer
Arduino can not measure resistance. It can measure voltage.
To measure resistance you can convert resistance to voltage using a voltage divider.

In Arduino world a voltage divider consists out of 2 resistors in series between 5V and gnd. The connection to the 2 resistors is connected to a analogue pin. Depending whether your LDR is connected to gnd or 5V the measured value on the analogue pin will go up or down with the resistance of the LDR.

In other words swap the resistor and your LDR from position.
> 1 votes

# Answer
Just invert it in software. Instead of `analogRead(0)` use `(1023-analogRead(0))`.
> 0 votes

# Answer
You could change your circuit or just change `analogRead(0) < 750` to `analogRead(0) > 750`.
> 0 votes

---
Tags: programming, photoresistor
---


# Question
Title: Why does this button have a connection to ground?
I am testing this basic button example from the Arduino tutorial page.

This circuit lets power flow to pin 2 when the button is pressed. When the button is not pressed, the power goes through the resistor to ground, but my question is: why would you even need the connection to ground?

Can't you have power flow from 5V to pin2 or just have NO connection at all when the button is not pressed?

# Answer
> When the button is not pressed, the power goes through the resistor to ground

When the button in not pressed its not the 5v pin that is connected to ground but the input pin is connected to ground. This is to ensure that the input does not float between 0v and 5v.

When not connected to 5v or GND the input pin tends to randomly change from \`HIGH\` to \`LOW\`. To avoid this and quell external interference you just ground the pin.
> 6 votes

# Answer
That resistor is called a pull-down resistor. It's there to make sure pin 2 read low when the button isn't pressed. If you don't put it there pin 2 is left 'floating', and it could erroneously read a high value. Google it for more info.

If you want to simplify you circuit you could instead use a pull-up resistor, and connect the button to ground instead of 5v. The ATMega chip on the arduino has these pull-up resistors build into the chip itself, so you don't need to add one to the breadboard. Just not that the input values will be reversed. So pin2 will read LOW when the button is pressed, and HIGH when not. To activate the internal pull-up use `pinMode(2, INPUT_PULLUP)`
> 13 votes

# Answer
In simple words, to avoid undefined state. This type of resistor arrangement is known as Pull Down Resistor. (Pull-Up also exists)
> 1 votes

---
Tags: button
---


# Question
Title: Bluetooth module is neither sending nor receiving data at baudrate(115200)
Im sending data between my arduino and android via bluetooth, using a simple chat app called "Bluetooth Terminal" . the code work perfectly at baudrate(9600) but I need to increase the speed to that of (115200) but nothing gets transmitted, or at least visible, anymore.

here's my code

```
#include <SoftwareSerial.h>

const int TXD = 3;
const int RXD = 4;
SoftwareSerial mrBlue(TXD, RXD);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mrBlue.begin(9600);

}

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

  if (mrBlue.available() > 0) {

    String data = mrBlue.readString();
    Serial.println(data);

  }

  if (Serial.available() > 0) {

    String data = Serial.readString();
    mrBlue.println(data);
  }

  delay(20);
}

```

# Answer
> 0 votes
Software serial is not working good with 115200 speed because of too much CPU usage. When I'm using only the bluetooth communication in Arduino, I'm connecting HC-05 (for example) to hardware serial pins and everything works fine.

If you want to increase the speed you must also change it in AT mode.

# Answer
> 0 votes
Software serial is really limited because it needs relatively precise timing, full attention of CPU and there can't be any interruptions from other sources.

You can see source code for better understanding how it works.

And if you need faster communication, you should get board with more hardware serials.

---
Tags: bluetooth
---


title: How to delay outside loop

text:
# Question
Title: How to delay outside loop
I am using a function outside `loop()`, which is called after an interrupt. Inside this function, I am setting several relays that need to change after a second or two, depending on my setting. I tried the delay, it doesn't work. `millis()` isn't working as well; I found out it stops counting when I exit the loop function.

My code looks something like this:

```
const long on_interval = 2000;
unsigned long currentMillis = millis();
bool hv_bool = false;

void hv_switch() {
    if (digitalRead(hv_pin)==HIGH){
        hv_startup();
    }
}

void hv_startup() {
    unsigned long previousMillis = 0;
    digitalWrite(pre_charge, HIGH);
    digitalWrite(main_charge, LOW);
    //Wait interval
    previousMillis = currentMillis;
    while (currentMillis - previousMillis < on_interval) {
        Serial.println(millis());
        //Wait
    }
    digitalWrite(pre_charge, LOW);
    digitalWrite(main_charge, HIGH);
    hv_bool = true;
    loop();
}

void setup(){
    //Set some ports

    //Initiate interrupt
    attachInterrupt(digitalPinToInterrupt(hv_pin), hv_switch, RISING);
}

void loop() {
    //Low voltage loop after startup, high voltage off
    while (hv_bool == false) {
        Serial.println("Waiting on high voltage");
        digitalWrite(hv_led, LOW);
        digitalWrite(pre_charge, LOW);
        digitalWrite(main_charge, LOW);
    }
}

```

# Answer
@EdgarBonet has it - hv\_startup() is part of the the interrupt handler. Interrupt handlers should be as short (timewise) as possible, doing only what has to be done with the interrupts off, and leaving longer tasks for the mainline (loop() and its sub-functions) to do.

But a bigger problem is that loop() is called from hv\_startup(), also getting used as part of the interrupt handler, and loop() has a while{} loop that depends on hv\_bool, which can never get changed, 1) because there is no statement to set it false (besides the initialization); and 2) because loop is now running at interrupt level and no more interrupts (at the same level) can be taken.

So I'd suggest several fixes:

* Don't call loop from your interrupt handler. When your handler exits, loop() will resume from wherever it was when it got interrupted.
* Don't delay in your interrupt handlers. If the interrupting hardware needs to be reset, do that and any other processing you have to do while the interrupts are off. But if some longer processing needs doing, set a flag in the interrupt handler (remember to declare it to be 'volatile'!), and exit.

+ In loop(), test the flag. If it is set, *clear it* and call another function to handle the less urgent processing required by the interrupt.
> 2 votes

---
Tags: interrupt, millis
---


title: Convert a Double to an UnSigned Char

text:
# Question
Title: Convert a Double to an UnSigned Char
So, I'm working on **RedBear Blend Micro V 1.0**, and I must use the function:

```
ble_write(Serial.read());

```

To read some input from the serial monitor(*Input being stuff I type in the Serial Monitor*) and send it via bluetooth. It works perfectly this way!

Now what I need to do is create a random **double** data type number, and insert it in the place of **Serial.read()**

Read This:

## **ble\_write**

*Syntax: void ble\_write(unsigned char data); ble\_write sends a single byte data to the BLE Central.*

So, can you please help me, to:

1)Generate a random **double**

2)Send it using the ble\_write() function?

For a full list of function sin the ReadBear Library click on the link: https://github.com/RedBearLab/nRF8001

# Answer
> 1 votes
**Edit**: Chris Stratton rightfully points out that the question is about a `double`, not a `float`:

Most, but not all Arduinos, are AVR-based. In the following I assume you are talking about AVR doubles, i.e. floats. If this is not the case, then just replace the array of 4 bytes by an array of 8 bytes.

---

**Original answer**: A `float` is four bytes, so it is somewhat equivalent to an array of four unsigned chars, i.e. to `unsigned char[4]`. You can use this equivalence with an `union`. For example, the following function will send a float byte by byte:

```
void ble_write_float(float x)
{
    union {
        float f;
        unsigned char c[4];
    } data;

    data.f = x;
    ble_write(data.c[0]);
    ble_write(data.c[1]);
    ble_write(data.c[2]);
    ble_write(data.c[3]);
}

```

Notice that this will send the bytes in whatever is the natural order of the sending processor. If it's an AVR (like most Arduinos), this will be LSB (least significant byte) first. You have to make sure that this is what the receiver expects.

Following Ignacio Vazquez-Abrams' suggestion, for sending a random float you could just send four random bytes. However, it may be wiser to have an idea of the random distribution you want for your float, and use things like `random()` and `map()` to achieve that distribution. Using four random bytes, you get a very wide distribution (all the possible floats are equally likely) which includes weird things like denormals, infinities and NaN (literally meaning “not a number”).

---
Tags: serial, programming, arduino-ide, bluetooth, communication
---


# Question
Title: creating object of another class when initializing an object of a class
Here's what I want to achieve: I'm building a class for controlling step motors. In that class I want to have a method called "init". In that method I'd like to create an object of class Tone, which I'll need to control a motor. BUT I want to have seperate Tone class object for every object of my class that I create. How can I do it?

So, for exmaple, if I have:

```
myClass newmotor1;
memotor1.init();

```

After executing these two lines, I'd like to have my object newmotor1 (which I have, because I just created it) AND an object of class Tone, which I'll use.

# Answer
You don't need to "create" anything. Just have an object in your class:

```
class Tone {
    public:
        void dosomething() {
            // Whatever is in here
        }
};

class MyMotor {
    public:
        Tone tone;
        void init() {
            // Nothing much else to do in here now.
        }
};

```

You then:

```
MyMotor newmotor1;

```

And you can access:

```
newmotor1.tone.dosomething();

```
> 0 votes

---
Tags: class, stepper
---


# Question
Title: The Right Com Port (COM 7) is NOT Showing
I just finished a camp for the arduino and the arduino uno that they gave us is not working with my computer even though everything was working on their computers. I am trying to upload with the same schematic, same Arduino, and the same code. It is not wanting to upload even after changing in the preferences to the same com Port. I have tried updating the drivers, but Windows 7 64 bit s saying this error message : This device cannot start. (Code 10) . Also, there is an exclamation mark in the device manager but how hard I try, it doesn't go away.

# Answer
> 1 votes
I found out that I could not use the arduino drivers because I am using a DCcduino uno that has a separate driver.

# Answer
> 0 votes
> The Right Com Port (COM 7) is NOT Showing

It would appear that Microsoft Windows does not necessarily assign the same COM port for a given device from machine to machine. It is usually up to the user to map which COM port is being used for which device. Some applications which work with specific devices have been known to "search" for that specific device and automatically connect to the correct COM port.

> ...saying this error message : This device cannot start...

There is this Microsoft Web Page here about this error.

More specific help may be found here. In particular, this passage looks promising:

> On Windows 7 (particularly the 64-bit version), you might need to go into the Device Manager and update the drivers for the Uno or Mega 2560. Just right click on the device (the board should be connected to your computer), and point Windows at the appropriate .inf file again. The .inf is in the drivers/ directory of the Arduino software (not in the FTDI USB Drivers sub-directory of it).

---
Tags: clones, ch340
---


# Question
Title: can i configure 2 (XBee series 2) modules using one explorer
Can I configure 2 XBEE modules one then another using 1 XBEE Explorer, or I MUST do this configuration operation for them at the same time and I need 2 Explorer modules?

# Answer
> 1 votes
You only need one. In order to communicate in Point To Point, you must configure each xbee to belong to the same NetworkID (PAN ID). XBees can only communicate with each other if they have the same network ID. Configure one, switch the xbee then configure the other (see here)

There are more advanced configurations that you can use (check this tutorial for extended information).

---
Tags: xbee
---


# Question
Title: Atmega328p clock and safe operation zone
im not used to write in english but i hope you guys can understand. I have some doubts about using the arduino pro mini 3v3@8Mhz

* I know its possible to change the clock to 1 MHz with the fuses easily by setting CKDIV8 to '0'. But i dont understand if its possible to divide the internal 8 MHz clock to intermediate values like 4 MHz and 2 MHz.
* I know i can divide the clock with program running. The problem is i would like to run the arduino with a voltage less than 2,4V and arduino will start at 8MHz(out of safe operation area) for later change the clock to 4MHz(inside of safe operation area). Is there another way by software to always be in the safe zone ?

# Answer
Just let CKDIV8 set (it just sets system clock prescaler to /8). And you can set different system clock prescaler later.

For changing system clock prescaler you need:

```
#include <avr/power.h>

```

And:

```
clock_prescale_set(clock_div_2); // possible values are clock_div_1 ... clock_div_256

```

Just don't forget that millis, delays and basically everything based on F\_CPU might be slower/faster when prescaler gets changed.
> 3 votes

---
Tags: atmega328, arduino-pro-mini
---


# Question
Title: Doorbell for someone with hearing issues
I have an Arduino Uno with the basic kit, not very good at coding it however.

How could I make a doorbell that lights up an LED instead of making a noise?

I'm trying to make a doorbell for someone with hearing issues.

A simple LED lighting up would be more than enough. Would I need a wifi shield if it's not close enough to be hard wired?

Thanks

# Answer
> 1 votes
I know you are keen on using your Arduino. But simpler solutions abound. For instance, if the door bell already works at a lower then main voltage it might be easier to determine the feasibility of connecting a low voltage lamp to the door bell.

However, I can see a situation that an Arduino can fit very nicely into:

Events: 1) The door bell rings. 2) The Arduino senses this and starts turning on and off a room light at about 5 second intervals. 3) This can last until someone notices and resets the Arduino. 4) If no one is home to reset the Arduino, the Arduino stops turning on and off the room light after a minute passes (12 flashes).

There are 2 tricky bits that may need explaining. The first is how to sense the door bell. If mechanical you could use a micro switch:

That way you don't need to worry about isolating the Arduino from what is likely a strong electrically noisy solenoid. The other tricky bit is controlling a room light. I would suggest using a COTS remote controllable light switch (I just did a search and there are loads of them in every price range) and hack the (battery powered) remote control into the Arduino.

# Answer
> 0 votes
If you must do wireless, you can get by with a 433MHz rx+tx module. Be sure to align both antennas either vertically or horizontally. These modules kind of need two MCUs though, but clones are cheap. Personally I would add a small switch underneath the doorbell button, but separate from its circuitry. Debounce it. On the receiving end you need a good set of LEDs - iphone has a very annoying but attention-grabbing light pulse for people hard of hearing. You can see it on youtube. I would copy that pulse timing and intensity as closely as possible, thus infringing on Apple's no doubt copyrighted+patented 'technology'. Be a pirate, arrr!

---
Tags: arduino-uno
---


# Question
Title: What is the Arduino compiler's version of `__unused` for function parameters?
When I first started with the Arduino environment I noticed that it had `File | Preferences | Compiler Warnings` set to `None`, so I set it to `All` \- and there were many, many warnings in the supplied libraries! So I quickly set it to `None` again - until later.

Well, "later" is now, and I started going through the warnings to fix the code to quiet the compiler.

**Note that I don't want to *disable* any warnings** \- I want to placate the compiler at each spot so that it says to itself "No problem here!"

* If the compiler complains of an unused variable, I comment out the variable;
* If it complains of a signed/unsigned comparison, I change the type;
* If it complains of an unused parameter in a function, I...

...hmmm. If this was C++, I'd simply comment out the parameter name, leaving the type naked:

```
void Fn(int /*param*/) {
} // Fn(param)

```

> Arduino reports:
> `error: parameter name omitted`

But that isn't legal in C. With some compilers you can use the `__unused` attribute:

```
void Fn(int __unused param) {
} // Fn(param)

```

> Arduino reports:
> `error: expected ';', ',' or ')' before 'param'`
> It's interpreting `__unused` as the actual parameter name

or if they're fussy:

```
void Fn(int __attribute__((unused)) param) {
} // Fn(param)

```

> Arduino reports:
> `warning: unused parameter 'param' [-Wunused-parameter]`
> That's not the correct `__attribute__`, obviously

So none of the above work in the Arduino environment. Suggestions?

---

I've been programming in C and C++ for over twenty years, and I know that the #1 thing you should always do is ask the compiler to tell you about **everything** it notices. You need a warning-free compile at all times! Otherwise, you spend hours or *days* trying to find a bug - only to discover that the compiler has been warning you about it all along...

# Answer
> 3 votes
Well, I typed all that question up for posting, then tried one last thing. It worked!

```
void Fn(__attribute__((unused)) int param) {
} // Fn(param)

```

So, rather than let a good question go to waste: here's the answer!

Now all we need to do is get the maintainers of all the libraries to put these in... and fix the other warnings...

# Answer
> 1 votes
Within the body of a function you can do this to suppress a warning:

```
void do_something(int value) {
  (void) (value);
  . . .
}

```

You can use a macro to do the same thing, for better clarity:

```
#define UNUSED(v) (void) (v)

void do_something(int value) {
  UNUSED(value);
  . . .
}

```

This can be helpful in situations where you have conditional compilation:

```
void do_something(int value) {
  #ifndef USES_PARAM
    UNUSED(value);
  #else
    other_stuff(value);
  #endif
  . . .
}

```

---
Tags: c, compiler
---


# Question
Title: How to monitor a sensor for specific period
As noted in earlier posts, I am building a model railroad crossing gate signal, complete with gate arms, flashers and sound. Although I haven't settled on exactly how I am going to implement detection of the train entering the zone, determining when its completely passed the entry sensor, tripped the exit sensor and completely passed the exit sensor to re-open the gate, I am researching using RFID for this now.

My thought is to have an RFID card in every car of all my rolling stock. Therefore, I want to read all the ID's of the cars as they go buy and for this particular need, always store the latest ID in a variable so that once the whole train has passed by, the last ID in the variable SHOULD be the ID of the last car in the train. I would also have a counter incrementing for each unique ID read so I can use that as a secondary check for the exit routine (check that the exit RFID reader gets the same car count as the entry reader). The exit reader would also match its exitTag to the entryTag from the entry reader.

I am implementing a state machine to control all this functionality but the problem lies in the RFID reading, I need a way to determine when the reader has read all the train cars tags. I thought the easiest way to do this was to use the elapsedMillis library and monitor for some interval where no card was read (two seconds? that would be way more than the time between two train cars) and once met, change state.

That is proving more problematic than I thought. Here is my latest attempt. I also think it might be better if the tag reading method only returned the last tag ID AFTER ITS DETERMINED NO MORE TAGS TO BE READ so that the code in the case statement is not the code that's running continuously.

**Note: I am using the Adafruit RFID shield and Mifare Classic 1k S50 IC 13.56MHz RFID cards.**

Any thoughts appreciated

```
case CrossingZoneState::CROSSINGZONE_RFIDDETECTED:
    if (crossingZoneEntered == true)
    {
        // only thing we do here is monitor and identify the RFID tags of each car to determine last cars tag id
       //well, this doesnt work
        if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
        {
            //do all the tag reading in here
            tag = IndentifyTag(entryRFIDReader);
            readCount += 1;

            if (tag != priorTag)
            {
                tagCount += 1;
            }
            priorTag = tag;
            timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
        }
        // need to figure out how to determine no more cards are being read and change state and crossingZoneEntered back to false
    }

    if (crossingZoneExited == true)
    {

    }
    break;

```

IdentifyTags method:

```
uint32_t IndentifyTag(Adafruit_PN532 rfidReader)
{
    uint8_t tagID[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
    uint8_t tagIDLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
    uint32_t rfidCardID = tagID[0];
    boolean success = rfidReader.readPassiveTargetID(PN532_MIFARE_ISO14443A, &tagID[0], &tagIDLength);
    if (success) {
        // Display some basic information about the card for testing
        Serial.println("Found an ISO14443A card");
        Serial.print("  UID Length: "); Serial.print(tagIDLength, DEC); Serial.println(" bytes");
        Serial.print("  UID Value: "); rfidReader.PrintHex(tagID, tagIDLength);

        if (tagIDLength == 4)
        {
            // Mifare Classic card
            rfidCardID <<= 8;
            rfidCardID |= tagID[1];
            rfidCardID <<= 8;
            rfidCardID |= tagID[2];
            rfidCardID <<= 8;
            rfidCardID |= tagID[3];
            Serial.print("Mifare Classic card #");
            Serial.println(rfidCardID);
        }
        Serial.println("");
    }
    return rfidCardID;
}

```

Full switch statement:

```
switch (state)
{
case CrossingZoneState::CROSSINGZONE_CLEAR:
    // only thing we do here is monitor the zone entry sensor
    if (digitalRead(entrySensorPin) == HIGH) {
        crossingZoneEntered = true;
        state = CrossingZoneState::CROSSINGZONE_ACTIVATEGATES;
    }
    break;
case CrossingZoneState::CROSSINGZONE_ACTIVATEGATES:
    // Do these once: turn on the flashers, put down the arms and turn on the crossing gate bells
    if (didOnce = false)
    {
        // turn on flashers
        // turn on sound
        // lower gate arms
        didOnce = true;
        state = CrossingZoneState::CROSSINGZONE_READENTRYRFID;
    }
    break;
case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

    // only thing we do here is monitor and identify the rfid tags of each car to determine last cars tag id
    // need to figure out how to determine no more cards are being read and change state
        if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
        {
            //do all the tag reading in here
            entryTag = IndentifyTag(entryRFIDReader);
            readCount += 1;

            if (entryTag != priorTag)
            {
                entryTagCount += 1;
            }
            priorTag = entryTag;
            timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
        }
        else {
            //change state now that entry rfid tag reader is finished
            state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        }

    break;
case CrossingZoneState::CROSSINGZONE_OCCUPIED:
    // only thing we do here is monitor the zone exit sensor
    if (digitalRead(exitSensorPin) == HIGH) {
        state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
    }
    break;
case CrossingZoneState::CROSSINGZONE_READEXITRFID:
    if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
    {
        //do all the tag reading in here
        exitTag = IndentifyTag(entryRFIDReader);
        readCount += 1;

        if (exitTag != priorTag)
        {
            exitTagCount += 1;
        }
        priorTag = exitTag;
        timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
    }
    else {//check tags and count now that entry rfid tag reader is finished
        if (entryTagCount == exitTagCount && entryTag == exitTag)
        {
            state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
        }
    }
    break;
case CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES:
    // Do these once: turn off the flashers, raise the arms and turn off the crossing gate bells
    if (didOnce = true)
    {
        // turn off flashers
        // turn off sound
        // raise gate arms
        didOnce = false;
    }
    break;
case CrossingZoneState::CROSSINGZONE_ERROR:
    boolean success = writeToFileOnSD(modelRRErrorLogFile, "ModelRRXingErrorLog.txt", "error string");
    break;
}

```

# Answer
> 2 votes
Here is a solution I found on one of the forums, I modified/simplified it to suit, but it does what you are after.

I use a cheap MP3 player and small amp that runs all the time with the speaker output switched by a baby relay controlled by the UNO R3 and IR sensors from Ebay, you should be able to convert this for use on your player.

It runs the 4 steps you described.

code attached. (could not figure out how to get code into a box-very confusing..please enlighten me,,,,and what is a back tick??)

```
#include <Servo.h>

Servo gate1servo;// create servo object to control crossing gate 1
//ASSUMPTION Gate is down at position gatedownposition and up at position gateuppostion
Servo gate2servo; // create servo object to control crossing gate 2
unsigned long previousMillisSERVOSTART=0; //FLASH Millis() setup
int intervalSERVOSTART = 1000;
unsigned long previousMillisFLASH=0;  //FLASH Millis() setup
int intervalFLASH = 250;
int gateup  =  120;  // servo position for gate up
int gatedown = 30;
int gatepos; // variable to store the servo gateposition
int gp = 120;  // servo position for gate down
int sensor1 = 5; // IR sensor pin Assumption== Pin goes LOW when train detected
int sensor2 = 6; // IR sensor pin Assumption== Pin goes LOW when train detected
int led1 = 10;  // Led 1 pin first alternating flasher
int led2 = 11;  // Led 2 pin first alternating flasher
int gates_started = 0; // this says if the crossing is active

int entering_sensor = 5; //this will tell which sensor was triggered first
int leaving_sensor = 6; // this will tell which sensor shows train leaving
int flash_state = 0;

void setup() {
   Serial.begin(9600);
  gate1servo.attach(3);// attaches the servo on pin 3 to the servo object
  gate2servo.attach(4);// attaches the servo on pin 4 to the servo object
  gate1servo.write(gp);//start assuming no train
  gate2servo.write(gp);//start assuming no train
  pinMode(sensor1, INPUT);
  pinMode(sensor2, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  digitalWrite(led1, LOW);// Start with all flashers off
  digitalWrite(led2, LOW);
}

void loop() {
    if ((digitalRead (sensor1)==LOW)&& (gates_started==0)) {//read sensor 1, if LOW ...do it
        gates_started = 1;
        leaving_sensor = sensor2;
    }
    if ((digitalRead (sensor2)==LOW)&& (gates_started==0)) {//read sensor 2, if LOW ...do it
        gates_started = 1;
        leaving_sensor = sensor1;
    }
    unsigned long currentMillisFLASH = millis();                                                      // get current time stamp, only need one for all if-statements
    if ((unsigned long)(currentMillisFLASH - previousMillisFLASH) >= intervalFLASH) {// time between button presses
       flash_state = ~flash_state;
       digitalWrite(led1, flash_state);                                           //toggle flash_state
      digitalWrite(led2, ~flash_state);
      previousMillisFLASH = currentMillisFLASH;
  }

  unsigned long currentMillisSERVOSTART = millis();                                                     // get current time stamp, only need one for all if-statements
  if ((unsigned long)(currentMillisSERVOSTART - previousMillisSERVOSTART) >= intervalSERVOSTART) {      // time between button presses
    for(gp = gatedown ; gp <= gateup ; gp++) {                                                          // goes from gatedown  degrees to gateup degrees
      gate1servo.write(gp);                                                                             // tell servo to go to gateposition in variable 'gateposition'
      gate2servo.write(gp);

  previousMillisSERVOSTART = currentMillisSERVOSTART;
 }
 Serial.println(gp);
}
}

```

# Answer
> 0 votes
Your algorithm is the probably the problem. Use this entry `case` instead:

```
case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

    entryTag = IndentifyTag(entryRFIDReader);
    if (!entryTag) {   // zero is usually returned if no card is detected
        readCount += 1;   // seems u want to count number of reads

        if (entryTag != priorTag) {
            entryTagCount += 1;
            priorTag = entryTag;  // update priorTag
        }
        timeElapsedBetweenCardReads = 0;   /// reset the counter when u read ANY tag; negate the effects of reading a card more than once

    }
    // only check timeout if you didnt read ANY tag at all
    else if (timeElapsedBetweenCardReads >= readerInactiveInterval){
        //change state now that entry rfid tag reader is finished
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
    }

    break;

```

Something similar for the exit:

```
case CrossingZoneState::CROSSINGZONE_READEXITRFID:
    exitTag = IndentifyTag(entryRFIDReader);
    if (!exitTag) {   // zero is usually returned if no card is detected
        readCount += 1;   // remember this variable is shared with the other case

        if (exitTag != priorTag) {
            exitTagCount += 1;
            priorTag = exitTag;  // update priorTag
        }
        timeElapsedBetweenCardReads = 0;

    }
    else if ((timeElapsedBetweenCardReads >= readerInactiveInterval) &&
             (entryTagCount == exitTagCount) && (entryTag == exitTag)){
        //change state now that entry rfid tag reader is finished
        state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
    }
    break;

```

And in the OCCUPIED case:

```
case CrossingZoneState::CROSSINGZONE_OCCUPIED:
    // only thing we do here is monitor the zone exit sensor
    if (digitalRead(exitSensorPin) == HIGH) {
        state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
        timeElapsedBetweenCardReads = 0;   // reset the counter to prepare for exit case
        priorTag = 0;  // just in case
    }
    break;

```

---
Tags: arduino-mega, c++, timers, rfid
---


# Question
Title: analogRead() takes >400 us on Arduino Zero but ~100 us on Uno, why?
I've been trying to figure out why the analogRead() function takes about four times as long on an Arduino Zero than on an Uno, when the Zero has a faster clock than the Uno. Arduinos website says that it should take around 100 microseconds, and it does on the Uno, but it takes a little over 400 microseconds on the Zero. To time it, I've been setting a digital pin high immediately before the function call and low immediately after and measuring the period on a digital osscilloscope. I'm just trying to test analogRead, so I'm not doing anything else in this code. I've tried putting the ADC in freerun mode, and it trims ~15 us off of the ~415 us it currently takes. I've also used the on-chip debugger to look at the disassembly, and the line that takes too long is always the line waiting for the conversion to complete. I was also wondering if other ARM-based Arduinos (like the Zero) take over 100 us. Thanks!

```
int   sensorPin = A1;
int      ledPin = 11;
int sensorValue = 0;

void setup() {
  analogReadResolution(12);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin,HIGH);
  sensorValue = analogRead(sensorPin);
  digitalWrite(ledPin,LOW);
}

```

# Answer
> 1 votes
Arduino is universal platform, lot of wrappers to hide real hardware and it is slow. For example digital write is about 100times slower than direct access to hardware.

For example for AVR Mega328p based Arduino analogRead looks like (without macros):

```
int analogRead(uint8_t pin)
{
    uint8_t low, high;

    if (pin >= 14) pin -= 14; // allow for channel or pin numbers

    // set the analog reference (high two bits of ADMUX) and select the
    // channel (low 4 bits).  this also sets ADLAR (left-adjust result)
    // to 0 (the default).
    ADMUX = (analog_reference << 6) | (pin & 0x07);

    // start the conversion
    sbi(ADCSRA, ADSC);

    // ADSC is cleared when the conversion finishes
    while (bit_is_set(ADCSRA, ADSC));

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

    // combine the two bytes
    return (high << 8) | low;
}

```

There are no extra function calls, no much extra actions and ADC is enabled in the startup code (as most of hw).

On the other side there is ARM based arduino with SAM3X8E:

```
uint32_t analogRead(uint32_t ulPin)
{
    uint32_t ulValue = 0;
    uint32_t ulChannel;

    if (ulPin < A0)
      ulPin += A0;

    ulChannel = g_APinDescription[ulPin].ulADCChannelNumber ;

    static uint32_t latestSelectedChannel = -1;
    switch ( g_APinDescription[ulPin].ulAnalogChannel )
    {
        // Handling ADC 12 bits channels
        case ADC0 :
        case ADC1 :
        case ADC2 :
        case ADC3 :
        case ADC4 :
        case ADC5 :
        case ADC6 :
        case ADC7 :
        case ADC8 :
        case ADC9 :
        case ADC10 :
        case ADC11 :

            // Enable the corresponding channel
            if (adc_get_channel_status(ADC, ulChannel) != 1) {
                adc_enable_channel( ADC, ulChannel );
                if ( latestSelectedChannel != (uint32_t)-1 && ulChannel != latestSelectedChannel)
                    adc_disable_channel( ADC, latestSelectedChannel );
                latestSelectedChannel = ulChannel;
                g_pinStatus[ulPin] = (g_pinStatus[ulPin] & 0xF0) | PIN_STATUS_ANALOG;
            }

            // Start the ADC
            adc_start( ADC );

            // Wait for end of conversion
            while ((adc_get_status(ADC) & ADC_ISR_DRDY) != ADC_ISR_DRDY)
                ;

            // Read the value
            ulValue = adc_get_latest_value(ADC);
            ulValue = mapResolution(ulValue, ADC_RESOLUTION, _readResolution);

            break;

        // Compiler could yell because we don't handle DAC pins
        default :
            ulValue=0;
            break;
    }

    return ulValue;
}

```

As you can see there is little bit more actions to do single measure using HAL (Hardware Abstraction Level) so you have another level of abstraction here.

If you want faster actions, you can access hw directly, or use HAL and skip unnecessary steps. It would be much faster then.

---
Tags: analogread, adc, timing
---


# Question
Title: Problems with Powering Led Project Through Vin Pin
I am working on lighting some WS2812 Leds with a nodemcu form hiLetgo. The project works when it is powered from the usb that is on the board, but as soon as it is powered from the barrel jack, the leds will only light up to the last color that they were set, ignoring code. A schematic and code are included for reference.

```
#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>

// Which pin on the ESP8266 is connected to the NeoPixels?
#define PIN            D8

// How many NeoPixels are attached to the ESP8266?
#define NUMPIXELS      30

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 10; // delay for half a second
int x, y, z;

void setup() {
  // put your setup code here, to run once:
  pixels.begin(); // This initializes the NeoPixel library.
  x = 0;
  y = 0;
  z = 0;
}

void loop() {
  // put your main code here, to run repeatedly:
   for(int i=0;i<NUMPIXELS;i++){
    x = (x+1)%256;
    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255

    pixels.setPixelColor(i, pixels.Color(x,y,z)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds).

  }
  y= (y+1)%256;

}

```

# Answer
First: What is the purpose of that resistor you have in there? It serves no purpose as far as I can see, and would only cause problems anyway. Lose it.

Second: You have logic voltage level problems:

* You are supplying 5.2V to the LEDs.
* The ESP8266 is a 3.3V device.
* The ESP8266 outputs 3.3V as a logic HIGH.
* The WS2812 accepts 0.7Vdd as logic HIGH (as stated in the datasheet).
* **0.7 × 5.2 = 3.64v**

Ergo, the LEDs aren't seeing the logic HIGH signal as logic HIGH because it is too low a voltage.

Add to that the voltage drop across the resistor and your logic HIGH voltage will be even less.

So:

1. Lose the pointless resistor
2. Either reduce the supply voltage to the LEDs or increase the output HIGH voltage level with a logic level shifter circuit (3.3v -\> 5v).
> 1 votes

---
Tags: led, esp8266, nodemcu
---


# Question
Title: How do I Read and Write data from a USB stick?
Hello I have an Arduino Uno and I salvaged a USB port from an old computer. The USB port has 4 pins on it and it accepts USB sticks. I was wondering if it is possible to connect it to my Arduino so my Arduino can load data from files on the USB. I don't want to go out and buy a shield but I don't mind using libraries. Is it possible to read and write data from a USB stick with Arduino?

# Answer
> 2 votes
The Uno does not have any USB ***host*** or OTG capabilities on its own, and bit banging it is not easy. A USB Host shield, or a better microcontroller is needed.

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


# Question
Title: Bizarre behavior, loop function affects setup function
I've connected two stepper through two uln2003 chip. And wrote a small class to control them. The class works perfectly and I'm able to control the steppers (rotate the CW and CCW).

My main code looks like this :

```
#include "StepperControl.h"

StepperControl myStepperControls[2];

void setup() {
    delay(1000);
    myStepperControls[0].init(6,5,4,3);
    myStepperControls[1].init(11,10,9,8);

    delay(1000);
    for (int i = 0; i < 2; i++)
    {
        myStepperControls[i].DelayBetweenSteps = 1200;
        myStepperControls[i].StepCCWDegree(90);
        myStepperControls[i].StepCWDegree(51);
    }
}
int moveNumber = 0;
void loop(){
    int stepperNumber = moveNumber / 2;
    bool cw = ((moveNumber % 2)  == 0);
    moveNumber = (moveNumber + 1) % 4;
}

```

As you can see I:

* Init both instances of the class to different pins.
* Set the Delay between the steps (in microseconds).
* Rotate `myStepperControls[0]` counter clock wise and then clock wise.
* Same for `myStepperControls[1]`

This doesn't work correctly, one of the motors doesn't move clock wise.

It is not always the same motor !! For the last hour the problem appeared only in `myStepperControls[0]`, now it is only in `myStepperControls[1]`.

I'm 100% sure it is not a wiring/electrical problem because:

1. If I'll delete the content of the loop (which runs after setup) it will fix the problem.
2. If I'll make the delay between steps 2000 it will fix the problems.
3. As I've mentioned the problem was only in `myStepperControls[0]` for an hour, in that hour i switch the pins of the motors and still the motor that was connected to `myStepperControls[0]` was not able to rotate CW.

Any suggestions to how to investigate the problem will be appriciated

Here is my library code:

```
// StepperControl.h

#ifndef _STEPPERCONTROL_h
#define _STEPPERCONTROL_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

class StepperControl
{
 public:
    StepperControl();
    void init(byte blue, byte pink, byte yellow, byte orange);
    void StepCW(int steps);
    void StepCCW(int steps);
    void StepCWDegree(float degrees);
    void StepCCWDegree(float degrees);
    const int StepsPerFullRotation = 4076;
    int DelayBetweenSteps;
 private:

    void setPinsState(byte step);

    byte m_currentState;
    byte m_pinValuelookup[9];

    byte m_bluePin; // = 11;    // Blue   - 28BYJ48 pin 1
    byte m_pinkPin; // = 10;    // Pink   - 28BYJ48 pin 2
    byte m_yellowPin; // = 9;    // Yellow - 28BYJ48 pin 3
    byte m_orangePin; // = 8;    // Orange - 28BYJ48 pin 4
                            // Red    - 28BYJ48 pin 5 (VCC)

};

#endif

```

here is the cpp file :

```
#include "StepperControl.h"

StepperControl::StepperControl() : m_pinValuelookup{B01000, B01100, B00100, B00110, B00010, B00011, B00001, B01001, B00000}, DelayBetweenSteps(1100), m_currentState(0)
{
}

void StepperControl::init(byte blue, byte pink, byte yellow, byte orange)
{
    m_bluePin = blue;
    m_pinkPin = pink;
    m_yellowPin = yellow;
    m_orangePin = orange;

    pinMode(m_bluePin, OUTPUT);
    pinMode(m_pinkPin, OUTPUT);
    pinMode(m_yellowPin, OUTPUT);
    pinMode(m_orangePin, OUTPUT);
    delayMicroseconds(DelayBetweenSteps);
    setPinsState(8);
    delayMicroseconds(DelayBetweenSteps);
}

void StepperControl::StepCW(int steps)
{
    for(int i = 0; i < steps; i++)
    {
        m_currentState = (m_currentState - 1) % 8;
        setPinsState(m_currentState);
        delayMicroseconds(DelayBetweenSteps);
    }
    setPinsState(8);
}

void StepperControl::StepCCW(int steps)
{
    for(int i = 0; i < steps; i++)
    {
        m_currentState = (m_currentState + 1) % 8;
        setPinsState(m_currentState);
        delayMicroseconds(DelayBetweenSteps);
    }
    setPinsState(8);
}

void StepperControl::StepCWDegree(float degrees)
{
    float steps = degrees * (float)StepsPerFullRotation / 360.0f;
    StepCW((int)steps);
}

void StepperControl::StepCCWDegree(float degrees)
{
    float steps = degrees * (float)StepsPerFullRotation / 360.0f;
    StepCCW((int)steps);
}

void StepperControl::setPinsState(byte step)
{
  digitalWrite(m_bluePin, bitRead(m_pinValuelookup[step], 0));
  digitalWrite(m_pinkPin, bitRead(m_pinValuelookup[step], 1));
  digitalWrite(m_yellowPin, bitRead(m_pinValuelookup[step], 2));
  digitalWrite(m_orangePin, bitRead(m_pinValuelookup[step], 3));
}

```

# Answer
Some one helped me in the Arduino forums, and I felt obligated to add the answer here :

The : `m_currentState = (m_currentState - 1) % 8;` is the bug. I accidentally assumed that doing `%` on `-1` will jump to `7`.

Somehow this caused the strange behavior I had.
> 0 votes

# Answer
You found the solution yourself. I am posting this answer anyway just to give some background on the problem.

I must say you were somewhat unlucky: you have just hit a couple of the least intuitive features of the C and C++ languages: integral promotion and signed division.

1. **Integral promotion**: C does not know how to perform arithmetic on anything smaller than an int. When you write `m_currentState - 1`, the variable `m_currentState` is automatically promoted to `int`. Note that this promotion has converted an *unsigned* type (`byte` is unsigned) into a *signed* integer. Then, `(byte) 0 - 1` is `(int) -1` instead of `(byte) 255`.
2. **Signed division**: When dividing a negative number by a positive one, the quotient is rounded towards zero and, conversely, the rest is negative. Then, `-1 % 8` is -1 instead of 7.

There are several ways around these problems. One is to replace the modulo operation `% 8` by a bitwise and: `& 7`. This is an optimization the compiler would have done anyway if dealing with *unsigned* integers. The option I prefer is to simply undo the integral promotion by an explicit cast:

```
m_currentState = (byte) (m_currentState - 1) % 8;

```

This way, if `m_currentState` is zero, `(byte) (m_currentState - 1)` is 255 and the result is, as expected, 7. Also, the compiler optimizes the unsigned modulo operation into a bitwise and: the whole lines compiles very efficiently into just two single-cycle instructions:

```
subi r24, 0x01  ; subtract 1
andi r24, 0x07  ; bitwise and with 7

```

It is worth noting that nothing of this would have happened if `m_currentState` was an `unsigned int`, as there would have been no integral promotion in the first place.
> 0 votes

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


# Question
Title: How can I reduce the redundancy of this code, so one function can perform the task of printing on Serial and Softserial?
```
void Multi_print (String str)
{
  Serial.print(str);
  mySerial.print(str);
 }

void Multi_println (String str)
{
 Serial.println(str);
 mySerial.println(str);
}

void Multi_parse_int (int value)
 {
    Serial.print(value);
    mySerial.print(value);
 }

```

# Answer
Just send your data to a tee: this is a type of pipe fitting where you push the data through one end and it goes out through the other two ends. As it happens, both Serial and Softserial (and almost anything that can `print()`) inherit from the virtual `Print` class. You can implement a tee as a `Print` that outputs to two `Print`s:

```
class Tee : public Print
{
public:
    Tee(Print &_p1, Print &_p2)
    : p1(_p1), p2(_p2)
    {}

    size_t write(uint8_t c)
    {
        size_t count1 = p1.write(c);
        size_t count2 = p2.write(c);
        return min(count1, count2);
    }
private:
    Print &p1, &p2;
};

```

The `write(uint8_t)` is the only method you really need to implement to have a working `Print`. Then, all the `print()` and `println()` methods will work.

Example usage:

```
Tee dualSerial(Serial, mySerial);
dualSerial.print("The answer is ");
dualSerial.println(42);

```

Note that `parseInt()` will not work, as it is not a method from `Print`. But if you think twice, you will realize that `parseInt()` on a pair of channels just does not make sense.
> 4 votes

# Answer
LOL, while Edgar was busy answering your question, I posted a github implementation called NeoTee which will tee any number of streams. I have occasionally wanted such a class (attached at the end). He has explained the approach nicely.

One quirk of the Arduino `Print` and `Stream` classes is that the `flush` method is in `Stream`, not `Print`. So to provide that method in the `NeoTee` class requires deriving from `Stream`. But `Stream` requires that you implement `read`, `available` and `peek`. Although `available` can return the sum of the characters available on all `Streams`, the usefulness of `read` and `peek` is functional, but dubious. ;-)

One example sketch is available in the library. For your sketch, you would declare something like this:

```
Stream *streams[2] = { &Serial, &mySerial };
NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );

```

And used thusly:

```
tee.print( '!' ); // prints one character to both
tee.print( 123.45 ); // prints a floating-point number on both

```

---

NeoTee implementation:
```
#ifndef _NEOTEE_H_
#define _NEOTEE_H_

//------------------------------------------------------
// NeoTee
// Copyright (C) 2016, SlashDevin
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//

#include <Stream.h>

// This library is like the UNIX "tee" command, which splits an output stream
// into two streams, but with N branches.  On the Arduino, an output stream is
// instance of the Arduino Print class, and the flush method is in Stream.
//
// Simply declare your own array of streams:
//
//     Stream *streams[2];
//
// Pass the array and its size in to the NeoTee constructor:
//
//     NeoTee tee( streams, sizeof(streams)/sizeof(streams[0]) );
//
// Any Stream operation on "tee" will be duplicated on all Streams in the array.
//
//     tee.println( F("This is sent to all Stream instances in the array.") );
//
// Because there is no base class with "begin" and "end" methods, you
//   must call those explicitly on the individual Streams (e.g., Serial.begin)

class NeoTee : public Stream
{
  Stream **Streams;
  uint8_t  NumStreams;

public:

  NeoTee( Stream **streams, uint8_t numStreams )
    {
      Streams    = streams;
      NumStreams = numStreams;
    }

  virtual void flush()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        Streams[i]->flush();
    }

  virtual size_t write(uint8_t c)
    {
      size_t minWritten = 0;
      for (uint8_t i=0; i<NumStreams; i++) {
        size_t written = Streams[i]->write( c );
        if ((i == 0) || (minWritten > written))
          minWritten = written;
      }
      return minWritten;
    }

  using Stream::write; // make the other overloads visible

  virtual int available()
    {
      int total = 0;
      for (uint8_t i=0; i<NumStreams; i++)
        total += Streams[i]->available();
      return total;
    }

  virtual int read()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        if (Streams[i]->available())
          return Streams[i]->read();
      return -1;
    }

  virtual int peek()
    {
      for (uint8_t i=0; i<NumStreams; i++)
        if (Streams[i]->available())
          return Streams[i]->peek();
      return -1;
    }

};

#endif

```
> 1 votes

---
Tags: serial, programming, softwareserial
---


title: Reduce 5v Trinket Pro to 3.3v?

text:
# Question
Title: Reduce 5v Trinket Pro to 3.3v?
Apparently these nRF24L01+ modules need 3.3v, but I've only got 5v Trinket Pros that I'm using.

How can I reduce the voltage to the RF transmitter?

Would a voltage regulator work? Specifically looking at this: http://addicore.com/product-p/165.htm

# Answer
> 4 votes
The NRF24L01+ has inputs that are 5V tolerant! So you only need to provide 3.3V on the Vcc pin of the module, which you can do by putting a voltage regulator between it, and the 5V of the Trinket. So there isn't really any need to convert the Trinket to 3.3V.

PS Remember to add some capacitors to the output of the voltage regulator, as the NRF needs a pretty stable 3.3V. Noise in the power lines can cause instability in the operation of the device.

# Answer
> 1 votes
I also had a 5V Pro Trinket on hand and needed to connect one of its 5V output pins to the 3V pairing pin on an Adafruit's EZ-Key HID. I solved it easily for the price of a couple 1/8 watt resistors by including a simple voltage divider in the circuit as a "level shifter" and it works like a charm. In my case it's not serial data but give it a try.

Classic voltage divider equation: V out = V in * R1 / (R1 + R2)

1. In setup(), set the 5V Pro Trinket digital out pin to be normally LOW when it's not doing anything in the sketch, e.g. if it were pin 8: pinMode(8,OUTPUT); digitalWrite(8, LOW);
2. Connect this 5V output pin to one end of a 1.8K resistor (the "R1").
3. Connect the other end of that resistor to both: your 3V module's input pin AND to a 3.3K resistor (the "R2") to ground.
4. If you have a meter, perhaps before connecting to your module input first double check your circuit at the juncture of the resistors. Actual serial data probably won't produce a reliable reading so temporarily alter your sketch to just take the 5V Pro Trinket pin HIGH. I measured 3.1 V output on mine when the output goes HIGH and it works great with the EZ-Key module.

# Answer
> -1 votes
There are 3.3V Trinkets. Anything you try to do will cost more than buying one.

# Answer
> -1 votes
As said by JayEye: there are 3,3V Trinkets and that is probably the cheapest option.

If you want to pay the extra money, there are special boards for it by addicore: https://www.amazon.com/gp/product/B00VFNZN8K/ref=s9\_dcacsd\_bhz\_bw\_c\_x\_3

third option is to build yourself a small voltage regulating circuit. The regulator that you linked to will do.

---
Tags: voltage-level, adafruit, nrf24l01+, rf
---


title: How to volunteer for arduino projects?

text:
# Question
Title: How to volunteer for arduino projects?
I have master in electronics and IT. I know various microcontrollers programming in `c`. I want to volunteer myself to learn for arduino Projects especially for low Level Drivers etc. Can somebody suggest me Websites or way ?

# Answer
The Arduino paradigm is based on abstracting the hardware to a few simple function calls. So many drivers appear simple to the end user (end programmer).

Most go here for a list of libraries (which have already been written) and how to use them. I believe these libraries are distributed with the Arduino SDK. To learn more about writing libraries go here. I am not aware of any formal method of submitting Arduino libraries. If I wanted to find out more I would go here and participate in the forum. However, using the forums search, I found this specific (several years old) post where it says:

> You can add a page to the Playground section: http://playground.arduino.cc/ You might start by adding your website with Arduino code to the index of the playground, perhaps a page in the Playground section is not needed. The index can contain links to websites, to the Arduino forum or to a page in the Playground section.
>
> You can not change or add to the reference or official libraries.
> 2 votes

# Answer
Most of the libraries to read sensors like as Dallas/Maxim 1Wire products, or to interface to RF-, WiFi-, and other radios are user-contributed and maintained, and most, if not all, of them are community maintained and on github.

Update:

> Is there any official repository for arduino libraries where someone can contribute and submit patches?

"Official": I don't think so, at least I don't know of one if there is, but I am also just learning my way around the open sources.

But you'll probably find most of the libraries in github, and they are usually there to share development. They aren't generally grouped as "Arduino", but by each author's github username.

So the best approach is probably to identify the library in your "libraries" folder that you want to update, and its author's name which is usually in the source-code header comments. And, if you get lucky, a URL to the github project. Otherwise go to github and search for the library, using the author's name or a quick comparison of some the source code to be sure you've really found the same library.

(As I am a user & beneficiary of open source code, you have my sincere thanks for choosing to do this! I haven't gotten that far yet; I hope to, soon.)
> 0 votes

---
Tags: programming
---


# Question
Title: Receive sms on android phone without GSM module
I have done a simple project which measures CO gas in air.Now I want that sensor will measure the level of CO gas and sms will be received on android phone when the area is under danger zone.How to receive sms on android phone without GSM module?

# Answer
> 0 votes
There are exactly two ways of sending an SMS. Both of which require more than "just" an Arduino.

1. Directly using GSM - for which you NEED a GSM shield
2. Indirectly using an Internet Gateway - for which you NEED some form of internet connection.

Since you have an aversion to 1, 2 is your only option. So you require some extra hardware (unless you have an Arduino with built in WiFi or Ethernet) to connect your Arduino to the internet. Then you have to pay an SMS gateway provider to allow you to send SMS messages through them, and implement their API in the Arduino.

Also you need an internet connection available wherever the Arduino happens to be.

All in all a lot of work and you're really no better off than using a GSM shield.

# Answer
> 0 votes
**Alternative from price perspective:**

Assuming that you have internet at the location of sensor (WiFi or cable) you can buy a RaspberryPi (revision 3 has already integrated WiFi and bluetooth). Using python code you can than send SMS message using some free SMS service provider if there are any in your country using their API.

If SMS notificaion is not critical, you can use RaspberryPi to send an email or some other sort of notification. Heck you can even create a Twitter profile for your sensor and call it Mr.Sensor and then post tweets with sensor values. Possibilities are endless, it all depends on your use case and available infrastructure.

I hope you will find something that will satisfy your needs :)

---
Tags: arduino-uno
---


title: Real Time Clock Module Reset

text:
# Question
Title: Real Time Clock Module Reset
I just had a pretty simple question about the RTC Clock Modules, more specifically the DS3231 RTC. Once calibrated and running on my Arduino if I were to unplug it and plug it back in, will the time and everything reset and require another calibration, or will it work like a computer that, even when reset, retains the correct time and date. Thanks!

# Answer
It depends if your module has a battery backup or not. A bare chip, by itself, will loose everything. That's why many breakout boards will have a small lithium cell on them to retain everything when the power is removed.
> 1 votes

---
Tags: arduino-leonardo, rtc
---


# Question
Title: Why does servo library conflict with irremote?
I am building an Arduino Mega robot. I am planning to use IRremote.h library for it. I am using multiple libraries in my code and I do not know which timers are taken. I always get errors when compiling because I am using the wrong timer. Here are the libraries I am using:

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

```

I get this error message when compiling:

```
libraries\IRremote\IRremote.cpp.o: In function `__vector_42':

C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\IRremote/IRremote.cpp:339: multiple definition of `__vector_42'

libraries\Servo\avr\Servo.cpp.o:C:\Users\Lyuba\Desktop\Nick\Arduino\libraries\Servo\src\avr/Servo.cpp:95: first defined here

c:/users/lyuba/desktop/nick/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

```

Here is the code in the library where I can change the timers:

```
// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  //#define IR_USE_TIMER1   // tx = pin 11
  //#define IR_USE_TIMER2     // tx = pin 9
 // #define IR_USE_TIMER3   // tx = pin 5
  #define IR_USE_TIMER4   // tx = pin 6
  //#define IR_USE_TIMER5   // tx = pin 46

```

What can I do to use irremote library? Looking at the error message, the servo library conflicts with irremote. How can I fix this?

# Answer
> 1 votes
Usual problem is trying to use the same counter for both. For example arduino pins 6,7,8 are on TC4 and if you try to use IR on pin 6 and servo on 7 or 8, it won't work. You can't use pwms on these pins with servo either (it is possible to do it directly in registers, but in arduino framework it might get bad behavior)

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


title: CLion + Arduino

text:
# Question
Title: CLion + Arduino
Please, help me to set up Clion + Arduino.

Clion has an Arduino plugin which I've installed. Here is some instruction on Github but I'm fully noob about `cmake` and other things which are talking about in instruction. I have only used Arduino IDE before for my simple projects. Now in CLion I can create an Arduino projects but autocompletion doesn't work. Actually it works but does it on true C, not for Arduino code.

So if you can please explain like for complete idiot, what I should change to get working Arduino autocompletion.

# Answer
Rather than using any plugin, I am using CLion with PlatformIO, which supports several IDEs. CLion then not only gives you code completion, but also full support for refactoring, Git, and much much more.

From its documentation:

> \[...\] generate project via `platformio init --ide` command:
>
> ```
> platformio init --ide clion --board %TYPE%
>
> # For example, generate project for Arduino UNO
> platformio init --ide clion --board uno
>
> ```

Then import the project in CLion and you're about done.

Some hints:

* Make sure your code is in the `src` folder, and that the main file has a `.cpp` extension.
* For other files: either rename all `.ino` files to use `.cpp`, or tell CLion to associate the `.ino` extension with C++ files. (Preferences, Editors, File Types.)
* Whenever adding libraries to the `lib` folder (and using `#include` to refer to them), just run the above `init` command again.
* If you're using ESP-boards and changed `platform.txt` for an alternative `esptool`, then note that PlatformIO needs a different hack.
* Rather than using the CLion Serial Monitor plugin, I simply use a Terminal within CLion to upload and start the monitor as soon as possible:

```
pio run -t upload; pio device monitor -b 115200

```
* If you always want to upload and monitor whenever using `pio run`, then add:

```
[env]
targets = upload, monitor
upload_protocol = esptool
upload_speed = 115200
monitor_speed = 115200

```
* Nowadays, CLion has a PlatformIO plugin as well, including a menu Tools, PlatformIO with commands such as Re-init.
> 25 votes

# Answer
I know this was asked a long time ago, but maybe it will be useful for someone. I'm a beginner, regarding all this stuff, so if anybody knows a better way to do it, please correct me. here is how I set up CLion for Arduino (on Windows 10):

CLion 2016.1.3 + Arduino 1.6.9 + plugin

1. Download and install the official Arduino IDE (1.6.9).
2. Download and install MinGW to 'C:\MinGW'
3. In MinGW, install: 'mingw32-base' and 'mingw32-gcc-g++'
4. Download and install CLion.
5. Create an 'untitled' project, just to open CLion.
6. In CLion \> Settings \> Plugins \> Browse Repositories \> Search for and install: 'Arduino' (tools integration), and 'Serial Monitor' (misc).
7. In CLion \> Settings \> Search \> type 'MinGW'
8. At the environment select 'Use MinGW home', and browse to MinGW folder ('C:\MinGW'). Press apply, and wait until CLion finds the environment.
9. In File \> Close project.
10. Open any file manager and go to 'c:\Users\name\ClionProjects\\' and delete the 'untitled' project you just created.
11. Open CLion, select 'New Arduino sketch project'
12. In the project directory \> 'open cmakelists.txt' and configure lines:

```
6: set board version
7: set port (you can find out port# from the Arduino IDE)
8: set the path where you installed your Arduino libraries (Arduino sketch folder)

set(${CMAKE_PROJECT_NAME}_BOARD uno)
set(${CMAKE_PROJECT_NAME}_PORT COM3)
LINK_DIRECTORIES(c:\\ARDUINO\\libraries)

```
13. In the upper right corner in CLion, near the green 'Play' button, select 'Edit Configuration', on the left select 'Application' \> 'Upload', and set:

```
-target: 'upload'
-configuration: 'debug'
-executable: the project name

```

then press ok.
14. In the project .ino file, write some really simple code (blink).
15. Connect an Arduino Uno via USB, and press the green 'play' button to upload the sketch.
16. To start serial monitor:

* In CLion main window bottom left, click serial monitor tab (in 'the tool buttons')
    * Click the wrench icon to set up port and baud rate.
    * On the top of the wrench icon, click the blue 'connect' icon.
    * If values did not appear 'correctly', click the white 'switch to hex' icon (on the right of the wrench).
    * Before uploading sketch, disconnect the serial monitor.
17. For CLion to properly find the libraries, make sure to use the same name for the lib folder as for the '.h' file. example: for DallasTemperature.h use folder name DallasTemperature. After #inlcude-ing new libs, right click on 'External libraries folder' and select 'Reload cmake project'.
18. You may want to do further configuration in CLion settings like: theme, colours, text size, etc.
19. Also, you can configure some handy 'live templates', like: `serialprintln`, `digitalwrite`, `pinmode`, `switch`, etc. to enhance your productivity.
> 10 votes

---
Tags: arduino-ide
---


# Question
Title: Arduino SPI - MOSI not writing any data but clock works
I am trying to iterate over an int array and writing those values to a chip. Here is my code.

```
#include <SPI.h>

int sine[] = {0x7fc ,0x868 ,0x8d4 ,0x93c ,0x9a8 ,0xa10 ,0xa78 ,0xadc
,0xb3c ,0xba0 ,0xbfc ,0xc58 ,0xcb0 ,0xd04 ,0xd58 ,0xda4 ,0xdf0 ,0xe34 ,0xe74
,0xeb0 ,0xee8 ,0xf1c ,0xf4c ,0xf74 ,0xf98 ,0xfb8 ,0xfd0 ,0xfe4 ,0xff0 ,0xff8
,0xffc ,0xff8 ,0xff0 ,0xfe4 ,0xfd0 ,0xfb8 ,0xf98 ,0xf74 ,0xf4c ,0xf1c ,0xee8
,0xeb0 ,0xe74 ,0xe34 ,0xdf0 ,0xda4 ,0xd58 ,0xd04 ,0xcb0 ,0xc58 ,0xbfc ,0xba0
,0xb3c ,0xadc ,0xa78 ,0xa10 ,0x9a8 ,0x93c ,0x8d4 ,0x868 ,0x7fc ,0x794 ,0x728
,0x6bc ,0x654 ,0x5ec ,0x584 ,0x520 ,0x4bc ,0x45c ,0x400 ,0x3a4 ,0x34c ,0x2f4
,0x2a4 ,0x258 ,0x20c ,0x1c8 ,0x188 ,0x148 ,0x110 ,0xe0 ,0xb0 ,0x88 ,0x64 ,0x44
,0x2c ,0x18 ,0xc ,0x0 ,0x0 ,0x0 ,0xc ,0x18 ,0x2c ,0x44 ,0x64 ,0x88 ,0xb0 ,0xe0
,0x110 ,0x148 ,0x188 ,0x1c8 ,0x20c ,0x258 ,0x2a4 ,0x2f4 ,0x34c ,0x3a4 ,0x400
,0x45c ,0x4bc ,0x520 ,0x584 ,0x5ec ,0x654 ,0x6bc ,0x728 ,0x794};

#define samples 120

const int cs = 9;

int counter = 0;

const int chipSelectPin = 10;

void setup()
{
  pinMode(cs,OUTPUT);
  pinMode(chipSelectPin, OUTPUT);

 SPI.beginTransaction(SPISettings(20000,LSBFIRST,SPI_MODE3));
}

void loop()
{

  digitalWrite(cs,LOW);

  SPI.transfer(sine[counter]);

  digitalWrite(cs,HIGH);

  counter += 1;

  if(counter >= samples)
  {
    counter = 0;
  }

}

```

Very simple, I am using an Arduino nano and according to this reference the clock pin is 13 and MOSI is 11. I am seeing the clock signal for pin 13 but pin 11 is inactive.

# Answer
> 2 votes
You need to use SPI.begin() before the beginTransaction().

The documentation is not 100% clear but beginTransaction does not replace SPI.Begin to setup the SPI hardware.

Documentation not very clear: https://www.arduino.cc/en/Reference/SPIbeginTransaction

# Answer
> 3 votes
In addition to @Talk2's answer `SPI.transfer(...)` transfers one byte of data. Your array is made of `int` which means each entry is 2 bytes long.

Instead you should use `SPI.transfer16(...)` to transfer 16-bit values.

---
Tags: arduino-nano, spi
---


# Question
Title: I'm pretty sure I fried my Arduino Uno. Given my setup, what caused it to be fried? (I can't identify the short)
I was trying to drive a Nema 17 stepper motor using an arduino uno and an A4988 driver. I had it wired up according to this instructable (http://www.instructables.com/id/Drive-a-Stepper-Motor-with-an-Arduino-and-a-A4988-/) at step 2 without the motor power supply wired to the bread board yet. ALSO, I hadn't wired the sleep to reset yet (I just didn't read directions carefully). The board was connected to my computer via USB and I had uploaded the sketch on the instructable to it.

Then, because I misunderstood the directions, I plugged my 12V 8A power supply into the power input on the arduino. All of the sudden, my computer turned off. My computer is fine after restarting, but now the arduino isn't recognized at all by the computer when I plug it in.

Given this information, I am pretty sure that my arduino is fried. However, I can't understand why plugging in the power supply to the power input, which has a voltage regulator, would cause the board to fry.

# Answer
> 1 votes
The Uno is not one "thing" that fails. It has various components, some of which may have failed. I wrote a lengthy page about how to test various parts:

Have I bricked my Arduino Uno? Problems with uploading to board

---

> I plugged my 12V 8A power supply into the power input on the arduino.

Perhaps you reversed the leads, and shorted the USB power to ground, thus causing the PC to turn off? This would probably also blow most of the components on the Uno because they would have had -12V applied to them, assuming it got past the voltage regulator.

However there **is** a reverse polarity protection diode on the power input jack. Did you use that or the `Vin` pin? (or the `Vcc` pin?)

Note that the reverse polarity protection does not protect you if you use the `Vin` pin.

# Answer
> 1 votes
I wonder if you destroyed your Arduino's voltage regulator.

If the Arduino was connected to the stepper motor via the A4988 when you powered the Arduino with a 12V supply, the stepper motor might have drawn current from the Arduino's regulator. This current is likely ~2As, which is far more than the tens of milliamps the Arduino is designed to output. This kind of current draw could quite possibly destroy the regulator on your Uno.

This could also explain why your computer restarted. USB ports on computers are designed to provide an output voltage to their USB devices, so if you provide a voltage on the USB power lines your computer is also driving, you can short your ports if the two voltages are not exactly the same. This is actually why USB cables have the A vs B end design - they mark which side should supply power (A), and which should be powered (B). The Arduino might have provided a voltage on the USB cable's 5V line and thus shorted something in your computer that provides the voltage for your USB ports (I believe Unos are not designed to be powered by both USB and the 12V connectors simultaneously).

If the regulator fried on your Uno, you might have had a voltage that was way off of the expected 5v on the USB port. A well designed USB port will usually try protect itself in a situation like this, often causing the computer to shutdown or the USB bus to deactivate until restarting the computer.

You could check your Uno's voltage regulator with a multimeter or better yet and oscilloscope to see if that is in fact the problem. If so, you could solder a new one on pretty cheaply and quickly. However, there is no guarantee nothing else got fried, in which case buying a new $10-20 Uno looks like a pretty appealing option.

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


title: uint8_t * to integer and string

text:
# Question
Title: uint8_t * to integer and string
**Convert text array/buffer to integer and string.**

hi! i'm sending text to an arduino and the output of that library is a uint8\_t array.

Atm the text send is a number between "0" and "1023"

```
void something(uint8_t * text){
 analogWrite(13,text);// does not work
}
/*
toInt() also not
int() not
atoi() not
invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
*/

```

i need to convert it to an integer or better to a uint16\_t.

As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.

i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++

if it's needed the length is also aviable inside the function.

# Answer
Your problem is that you are storing your text in an *unsigned* pointer (`uint8_t *`)instead of a *signed* pointer (`char *`).

If you change all your text types to `char *` then you can directly use `atoi()`. If you have a lot to change, though, you can just *cast* the unsigned pointer into a signed one (and make it `const` at the same time):

```
analogWrite(13, atoi((const char *)text));

```
> 4 votes

# Answer
analogWrite is a function to set a PWM duty cycle value to a pin on the micro

Usually to control a motor speed or LED brightness or similar.

Unless you plan to use the char value to set the PWM value??

A bit more context would help with your problem.
> 0 votes

# Answer
I've converted first four bytes to string, and then to int :

```
void something(uint8_t * payload){
String str="";
char c;
for(int i=0;i<4;i++)
    if (isDigit(c=(char)(*(payload+i))))
        str += c;

int Val =str.toInt();
Val=Val>1023?1023:Val;

analogWrite(14,Val);
}

```
> -1 votes

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


# Question
Title: how to make led fade on and blink while wav file plays
To clarify I'm extremely new to this and I'm using an Arduino Uno with a wave shield. My circuit works as intended but I haven't learned enough of the code to know what to do to make it do exactly what I want.

Right now the following code makes the sound play on button press but the led sequence doesn't at all. If I move `root.rewind(); play(root);` to after the last `digitalWrite` then the led sequence runs but the audio doesn't play until the led sequence ends. I'm out to make the audio play while the led sequence runs. Any suggestions?

```
if (state == 1) {
    root.rewind();
    play(root);
    for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
        analogWrite(LED,i);     // set the LED brightness
        delay(15);              // wait 15ms because analogWrite
                                // is instantaneous and we would
                                // not see any change
    }
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second

    digitalWrite(RESET, LOW);
}

```

# Answer
> 3 votes
As this can not be your entire sketch we can only guess that you are using some sort of SDCard music playing Arduino shield and library.

An application can not call the delay() function if the application is trying to accomplish more than one task. Calls to delay() block the processor from doing anything other than waiting for the delay to time out.

In order to (appear to) do multiple tasks, run a loop with no calls to the delay() function. Instead call the millis() function checking if enough time has elapsed to call the LED function or the sound function. In neither function should you call the delay() function! If you did not write the function (for example you are using a library) you may need to edit the code in the library to ensure it is following the no-calls-to-delay()-function rule!

In general terms, this is referred to as a state machine. In this case, the state machine is driven by the amount of elapsed time as reported by the call to the millis() function.

---
Tags: arduino-uno
---


title: Reading Multiple switch inputs

text:
# Question
Title: Reading Multiple switch inputs
I am trying to setup 20 input switches that can be pressed with hand. I am trying to get the output based on the pattern in which the input switches are pressed with the hand. Based on the pressure and the area of the hand pressing the input switches, there can be multiple switches that can be pressed to display the output pattern at the same time. How can I use Arduino Uno inputs to support these multiple pin reads at the same time?

# Answer
> 2 votes
You could use a MCP23017 or similar. Its an IC that provides 16 IO ports via I2C, I think you can have 4 of them so that should be enough for both hands.

Or you could use resistors. All the buttons are connected to a single analogue port. The resistors are chosen so that when you press any combination of buttons you will get a unique reading at the port. So if you press button one and get a reading of 100, press 2 and get 150, press 3 and get 200, etc. So buttons 1+2 give you 250, 2+3 gives you 350 and 1+2+3 gives you 450. The problem with this is the maths get out of hand very quickly and the IC is \< $1.

# Answer
> 0 votes
I'd second the use of the MCP23017, have used this chip in several projects with good results, you can connect 8 of them together which gives 128 I/O pins. Off the SDA/SCL pins UNO R3 Link Adafruit MCP23017

Also on Ebay from other suppliers.

---
Tags: input
---


# Question
Title: USB connector between Arduino and a lever (switch)
I am not sure an Arduino forum is the right place to ask this question, but since I'm using Arduino here I thought it would be a good starting point. I am trying to connect a lever (you can think of it as a switch, when it's pressed it's ON, and otherwise it's OFF) to an Arduino via a USB connector. My setup worked perfectly fine when I connected the lever directly to the Arduino, but via the USB it doesn't work. Since I already built and invested in USB connectors I would like to solve this issue, or at least understand what I am doing wrong in here.

I've attached a photo to demonstrate the wiring. Note that it works if I bypass this USB connection. I'm trying to understand why this doesn't work via a USB.

# Answer
> 3 votes
I'd suggest using a multimeter to figure out what's connected to what after hooking up the complete wiring scheme; there aren't that many options and you should be able to figure out what's connected to what soon enough. On a more philosophical note, it's only a bad idea if the alternatives weren't worse.

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


# Question
Title: Is it possible to connect a camera to an arduino?
I working on a project that requires a small camera to be covering a (insect) nest entrance. The video needs to be transmitted to a computer to be processed. I am interfacing with Java using the RXTX library and will then be tracking objects using OpenCV.

This is the camera

My question is, it it possible to connect this camera to an Arduino (Uno or Yun) and transmit the data back to a computer?

# Answer
> 1 votes
Yes. Check out ArduCam. Do a google search. http://www.arducam.com

---
Tags: arduino-uno, arduino-yun
---