title: Adding data to an SD card file

text:
# Question
Title: Adding data to an SD card file
I'm reading data from the Shinyei PPD42 particle sensor unit.
Everything seems to work, but I'm encountering two problems

1. When I restart Arduino, the file is not being extended, nor overwritten. It just remains how it was before.
2. Even though my code looks fine, Arduino stops writing data to the SD card after 90 seconds.

Thanks for having a look at my code.

```
#include <SPI.h>  //een bibliotheek aan code toevoegen; Arduino heeft deze nodig om de Shield te kunnen 'lezen'
#include <SD.h>   //zie hierboven

int PM=8; //de fijnstofmeter zit in digitaal poortnummer 8

const int chipSelect = 10; //const = een variabele die nooit verandert

unsigned long sampletime_ms = 30000;  //unsigned long = een variabele die erg hoog kan oplopen, maar nooit negatief kan zijn

//hieronder volgen nog enkele variabelen. Denk eraan: float betekent dat het decimale getallen kunnen zijn

unsigned long duration;
unsigned long starttime;
unsigned long lowpulseoccupancy = 0;
unsigned long timediff;
float ratio = 0;
float concentration = 0;
unsigned long tijd = 30;

//void setup wordt één keer uitgevoerd, bij het opstarten van de Arduino-minicomputer

void setup()
  {
    Serial.begin(9600); //de snelheid (in bits/second) aan welke de seriële data zal worden getransfereerd
    pinMode(PM,INPUT);  /*PM is de variabele van helemaal bovenaan: pinMode vraagt twee parameters 1)de poort (werd gedefinieerd bovenaan) 2)INPUT of OUTPUT
                          Ditmaal leest de fijnstofmeter gegevens die we vervolgens IN onze Arduino willen importeren, dus INPUT*/

    starttime = millis(); //hoelang draait het programma? millis() geeft de duur sinds het werd opgestart

    Serial.println("SD-kaart opstarten indien aanwezig... "); //Je schrijft nu neer dat de SD-kaart wordt gezocht en opgestart (println = hierna op volgende regel verder gaan)

    //hieronder staat een 'als'-lus: als aan de eerste voorwaarde wordt voldaan, voert hij uit wat eronder staat, anders gaat Arduino verder achter de afsluitende accolade

    if (!SD.begin(chipSelect)) //Als er NIET (!) kan worden begonnen met de SD-kaart te selecteren ...
      {
        Serial.println("Corrupte of ontbrekende SD-kaart!"); //dan wordt deze boodschap getoond
        return;
      }
    //Als de SD-kaart dus WEL werkt, gaan we hieronder verder

    Serial.println("SD-kaart werkt...");
    Serial.print("Fijnstofsensor start op. Even geduld! Metingen om de 30 seconden.");
    Serial.println("\n");
  }

//void setup wordt oneindig lang uitgevoerd, tenzij je dat anders bepaalt

void loop ()
  {
    duration = pulseIn(PM, LOW); //als de fijnstofdetector niet meet (LOW), beginnen meten
    lowpulseoccupancy = lowpulseoccupancy+duration; //na elke meting de 'duration' (30 sec)  optellen bij de totale tijd

    if ((millis()-starttime) >= sampletime_ms)
      {
        //hieronder de wiskundige berekeningen om het fijnstofgehalte te berekenen

        ratio = lowpulseoccupancy/(sampletime_ms*10.0);
        concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;

        //hieronder alles wat zal worden geprint naar het seriële venster

        Serial.print("Fijnstofconcentratie na ");
        Serial.print(tijd);
        Serial.println(" seconden:");
        Serial.print(concentration);
        Serial.println(" deeltjes/0,01cf");
        Serial.print("\n");

        File dataFile = SD.open("test.txt", FILE_WRITE); //het bestand meting.txt moet op de SD-kaart worden geopend om erin te schrijven

        if (dataFile) //als het bestand kan worden geopend, volgende gegevens printen
          {
            dataFile.print("Fijnstofconcentratie na ");
            dataFile.print(tijd);
            dataFile.print(" seconden: ");
            //dataFile.println(ratio);
            dataFile.print(concentration);
            dataFile.print(" deeltjes/0,01cf");
            dataFile.print("\n");
            dataFile.close();
          }

        else //als het bestand niet kan worden geopend ...
          {
            Serial.println("Fout bij het openen van test.txt");
          }

        tijd = tijd + 30; //meting afgerond, totale tijd = +30 seconden
        lowpulseoccupancy = 0; //de status van de fijnstofmeter is terug 'LOW'
        starttime  = millis(); //volgende meting starten
      }
  }

```

# Answer
You need to open the file in append mode:

```
SD.open("file.txt", O_RDWR | O_APPEND);

```

It depends on the file being there. If it fails to open because the file isn't there you can open it in "create" mode instead:

```
SD.open("file.txt", O_RDWR | O_CREAT);

```

For example:

```
// Try and append
File f = SD.open("file.txt", O_RDWR | O_APPEND);
if (!f) {
    // It failed, so try and make a new file.
    f = SD.open("file.txt", O_RDWR | O_CREAT);
    if (!f) {
        // It failed too, so give up.
        Serial.println("Failed to open file.txt");
    }
}

// Only write to the file if the file is actually open.
if (f) {
    f.print(/* your data here */)
    f.close();
}

```
> 1 votes

---
Tags: arduino-uno, sd-card
---


# Question
Title: HMC5883L - Tilt compensation without Accelerometer
Trying to get an **HMC5883L** to compensate for being installed in 90 degrees. Doesn't seem to me that it'll need too complex math or accelerometer. But I have no idea how to do the compensation for it. Any idea?

Using the Adafruit HMC5883L and its library.

# Answer
You can always use the normal tilt compensation equations with a fixed value instead of a calculation from the accelerometer; Since you know the rotation beforehand the equations may not be as complex. For example, if the tilt is only on one axis, it's just one rotation matrix multiply (and you don't need to calculate the result z axis) instead of 3 in general.

If the tilt is constant and exactly 90 degrees, You just need to swap which magnetometer axis are put into the magnetic field angle equations. If one axis is pointed towards the center of the earth, you can use the other two axis to calculate the direction of the magnetic field without an explicit rotation transformation.
> 1 votes

---
Tags: library, adafruit, ide, magnetometer
---


# Question
Title: Not sure I'm understanding pipes for NRF24
I've started working with the NRF24 library for some fun little side projects. I have only gotten through some basic tests but I'm starting to look at ways to tinker with the code. I have more experience as a programmer so the hardware side is always new to me. Where I'm a little confused is how the pipes are used. Working from this example, I see that one pipe is used to listen and another is used to transmit. If there's just two devices, why don't they both use the same pipe? If you have multiple devices on the same pipe transmitting, can it jumble the signals? Is there a way to receive on multiple pipes? I'd love more information on how pipes are or should be used.

# Answer
> 1 votes
I don't see any reason for doing this.

Multiple devices sending data at the same time will cause collisions irrespective of the pipe-nr they are using.

Pipe is also a not very accurate name for what it actually is. It's just a number, that the receiving NRF can check, to see if the packet that was received was intended for it. Kind of like a MAC address on a network.

You can have two unique reading pipes. Then there are 4 more pipes you can use, that are identical to the second pipe, except for the last byte.

The first pipe is used to specify the pipe you are sending through. So if you send to different pipes, this pipe isn't ideal for listening, as you'd have to change it back every time you send a packet. Possibly loosing a packet that was send in between.

If you want more information, i'd suggest reading the datasheet, and read the documentation of one of the libraries. I personally checked the sourcecode of the library a lot while at the same time referencing the datasheet, to really understand what it's doing.

---
Tags: arduino-uno, nrf24l01+
---


# Question
Title: How to control a Nema 17 stepper motor with an arduino? (too much current / heat)
I am trying to control a Nema 17 motor with a L298n dual bridge and an Arduino Mega.

My wiring is from this Instructable:

http://www.instructables.com/id/Control-DC-and-stepper-motors-with-L298N-Dual-Moto/?ALLSTEPS

When I connect it to my laboratory power supply the current limitation blinks. Normally when there is too much current needed the LED is all the time on and not blinking.

So I increase the current limit and the motor just starts moving on 3.1A @ 12V (doesn't move if less current) and in the description of the motor on amazon they say "Rated Current/Phase:1.2A" so I am wondering what did I do wrong here?

From my understanding "Rated Current/Phase:1.2A" means that I should run this motor (it's a bipolar stepper motor with 2 phases) not higher than 2.4A?

These are the informations from amazon about this motor:

**Specifications**:

* Led screw diameter: 8mm
* Lead screw length: 300mm
* Step angle :1.8 degree
* Nut material: Brass
* Holding Torque: 400mN\*m
* Thrust(full step): 12.5kg
* Rated Current/Phase:1.2A
* Rate Voltage: 3.3v
* Rated Resistance/Phase:2.2±10%ohm

What would be a good voltage to run this motor? I thought 12V is a good idea with.

The motor L298n gets really hot when I run it at 3.2A or more so I think my setup will destroy the dual bridge and / or the motor.

I really appreciate help on this! :-)

# Answer
The stepper motor does not directly control or limit its own current. When using the L298n for stepper control, the motor current control is performed by a PWM signal to the L298n ENABLE pin. If you have ENABLE high (100% duty), current will be a factor of only the DC resistance of the stepper winding and the power supply voltage. Here you are trying to drive a 1.2A@3.3V-rated stepper from 12V, so naturally the current will be ~3 times greater.

To adjust the motor current to a safe range for the driver, use analogWrite() from a PWM-capable pin on the Arduino connected to the ENABLE pin on the L298n, and set it to something less than 255 (50% is usually a good starting point). Even then, the instantaneous current draw on the L298n will likely be stressing it outside of its operating envelope.

EDIT: I reviewed the info at the link, and this is the relevant area of the code:

```
// set speed to 200 out of possible range 0~255
analogWrite(enA, 200);
// set speed to 200 out of possible range 0~255
analogWrite(enB, 200);

```

Here is where the code is setting PWM of the two ENABLE pins to 200 (~80% duty cycle). Drop this to 50 (~20% duty cycle) and you would likely resolve your overcurrent issue. Reading further still, even the author gives you your first hint at what is happening:

> This is not a speed value, instead power is applied for 200/255 of an amount of time at once.
> 2 votes

---
Tags: motor, stepper, l298n, heat
---


# Question
Title: How to make ESP8266-1S module work on Arduino Uno?
I currently have an Arduino Uno with an ESP8266-1S. However I can't make them work... I use the ESP8266wifi.h library and its connection functions do return a true (returns true when received a valid IP), but I can't find it in my network...

When I send 'AT' ending with CR and NL on 115200 baud I still don't get a response.

Also, do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

And also, do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX.

So this is how my board looks like:

So what am I doing wrong?

# Answer
> do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

If you want to do serial communication between a sketch running on the Arduino and the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to TX on the ESP8266.

If you want to do serial communication between the Serial Monitor on your computer through the USB port on the Arduino to the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to RX on the ESP8266.

TX stands for **Transmit** and RX stands for **Receive**. So it makes sense that you should connect the transmit pin to the receive pin in the first case. But why connect transmit to transmit and receive to receive in the second case? The reason is that you are not communicating between the main microcontroller (ATmega328P on the Uno) and the ESP8266. You are communicating between the USB-serial chip on the Uno (usually ATmega16U4 on the official Arduinos or CH340 on the clones) and the ESP8266. The main microcontroller is not being used at all, you're just using the Arduino as a bulky and inconvenient USB-serial adapter.

In fact some people will go so far as to remove the ATmega328P from their DIP Unos for this purpose. The RX pin on the USB-serial chip is connected to the TX pin on the main microcontroller as well as the TX header pin and vice versa for TX pin on the USB-serial chip. This means by connecting the ESP8266's TX pin to the TX pin on the Uno's header you are actually connecting it to the RX pin on the USB-serial chip. I would highly recommend getting a USB-serial adapter made for this purpose rather than trying to use an Arduino. You can buy FTDI FT232 or CH340 breakout boards on eBay or Aliexpress for \< $2 USD w/ free shipping.

> do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX

This is actually two questions. Let's address the easy one first. The TX pin of the ESP8266 is going to put out around 3 V. Even though the ATmega328P is running at 5 V this will still be seen as a high so no level conversion on that pin is necessary.

Now for the question of whether it's needed on the ~5 V level from the Arduino to the ESP8266 RX pin. There's a lot of disagreement on the question of whether the IO pins on the ESP8266 are 5 V tolerant. We certainly know that it's possible to connect the ESP8266 to 5 V levels as there are many projects published online that do this but the question is will this will shorten the life of the ESP8266?

The datasheet for the ESP8266 does not say the inputs are 5 V tolerant. There is a statement on the ESP8266 forum from a member of the Espressif (creator of the ESP8266) staff: http://bbs.espressif.com/viewtopic.php?t=1145

> We donot recommend you to apply 5V to IO.

We have a comment from someone on Facebook named "Teo Swee Ann" who appears to be the CEO of Espressif: https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442/?comment\_id=1732364133680532

> i can reply officially here: it is 5V tolerant at the IO. while the supply voltage is at 3.3V.

So there is conflicting information and none of it has been presented in the most official manner, such as actually putting it in the datasheet. One thing we do know for sure, you will not harm the ESP8266 with 3.3 V levels. So the safest option is to avoid giving it 5 V inputs. However, as you are currently struggling just to get the most basic communication working the extra complication introduced by adding level shifting circuitry may not outweigh the possibility of reducing the life expectancy of your ESP8266.
> 1 votes

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


# Question
Title: Tower Pro MG996R 180° high torque servo controlling using Arduino
We are trying to control a robotic arm using the *Tower Pro MG 996R 180°* high torque servo.

Firstly we tried to power the servo from Arduino's default 5V, but it didn't work, then we power it from an external source, the servo ran, but only in one direction. Then it stopped rotating. We used the sweep code from the Arduino examples to test the motor.

Here's the code:

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

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

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

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

Can anyone please specify what are we doing wrong, and what is the right way to do it.

# Answer
The Arduino's 5V is hardly enough for driving servos. I found that even a simple 9g micro servo draws well over 1A spikes, which causes the board to reset itself.

* Power the servo from an external battery pack (e.g. 3xAA or 4xAA batteries will do);
* Ensure that the GND of the battery pack is connected to the GND of the servo *as well as* to the GND of the Arduino;
* So you'll have two wires between the Arduino and the motor: GND and the driving signal.

It has to work, servos are pretty standard stuff. *However* there are many complaints against this particular type at this link Towerpro MG996R 10kg Servo 10kg / 0.20sec / 55g.
> 1 votes

# Answer
Si no me equivoco tiene 64 pasos. El servo no deberia ir de grado en grado sino por c/u de los 64 pasos. 180 grado / 6r es 3 grados x cada cambio de paso step to step. ? Atte.

If I'm not mistaken in 64 steps. The servo should not go from grade to grade but by c / u of the 64 steps. 180 degree / 6r is 3 degrees x each step change step to step. ? Atte.
> 1 votes

---
Tags: servo, robotics
---


title: Arduino IDE - Maximum serial COM ports

text:
# Question
Title: Arduino IDE - Maximum serial COM ports
**What is the maximum number of serial ports (com) can Arduino IDE detect ?**

I need to connect 6 Arduino UNO Wi-fi at a time to make a small network and I use a 7 port USB hub for the same. The device manager shows 6 com ports detected but Arduino shows only 4 serial ports detected. Is there a limitation on the serial ports interfaced with the Arduino IDE ?

# Answer
> 0 votes
Thanks for your comments. I found the solution. Inside the **My computer -\> Properties -\> Device manager** under ports I found that *multiple Arduino's where assigned same COM values*. Therefore, just go to properties of the COM and change them to COM values that are not used

# Answer
> 1 votes
According to the last version of code for Arduino IDE, there are no limits of discovered Serial or Network devices since they are stored in a list (not limited as an array).

To discard problems, try with another operating system.

---
Tags: arduino-uno, wifi, communication
---


title: Using dynamic variables in URL

text:
# Question
Title: Using dynamic variables in URL
I am trying to upload longitude and latitude data into MySQK using a GPRS shield, Arduino Uno R3 and a GPS module. The idea is to get longitude and latitude data from the GPS and use the GPRS to post the information into my database.

I have to insert the latitude and longitude data into the URL like this `steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785`. Values for longitude and latitude have to be dynamic not static. How do I go about this?

# Answer
It looks like you need to know how to create a string that contains: `steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785`

Its quite easy (I think) try this:

```
const int cDecimalPlaces(6);
String szLon = String(fLongitude, cDecimalPlaces);
String szLat = String(fLatitude, cDecimalPlaces);
String szUrl = "steetalert.co.zw/write_data.php?Longitude=" + szLon ",Latitude=" + szLat;

```

Normally I would use sprint or a Format function, but I can't find those in the reference.
> 0 votes

---
Tags: gps, tinygps
---


# Question
Title: How do I change number and bracket colors in the arduino IDE?
I recently personalized my arduino IDE (changed the background color, input text color, etc....) by going into the theme.txt file and replacing some hexadecimal values. I made the background black and the text lime green, but for some reason numbers and brackets still remain black, thus I can't see them against a black background. Anyone know how to fix this? I would really appreciate the help, got sick of looking at a white background when making sketches.

Sal

# Answer
Inside path `C:\Program Files (x86)\Arduino\lib\theme\syntax` there is file `default.xml` where I made some changes and the following lines are as follows:

```
  <style token="SEPARATOR" fg="ffffff" />
  <style token="LITERAL_NUMBER_DECIMAL_INT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_FLOAT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_HEXADECIMAL" fg="ffffff"/>

```

After this brackets and numbers occur white.
> 2 votes

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


# Question
Title: When a pushbutton and sensor are in a certain state, do something for a certain period of time (15 seconds)
I have a sketch that contains code for an analog input (FSR sensor), a pushbutton, and 6 blinking LEDs.

Currently, the sketch is written to allow the LEDs to blink only when the button is pressed and there is sensor input.

Can someone help me write code to make the LEDs blink for a certain period of time once there is input from the analog sensor and while the button is pressed? I am trying to make the LED blink for 15 seconds and then turnoff.

thank you!

```
/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;
const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup() {
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

if (SensorPinReading < 10) {
  Serial.println(" - No Pressure");
} else if (SensorPinReading < 200) {
  Serial.println(" - Light Touch");
} else if (SensorPinReading < 500) {
  Serial.println(" - Light Squeeze");
} else if (SensorPinReading < 800) {
  Serial.println(" - Medium Squeeze");
} else {
  Serial.println(" - Big Squeeze");
}

  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && SensorPinReading > 10)  {
  digitalWrite(LedPin1, HIGH);
  digitalWrite(LedPin2, HIGH);
  digitalWrite(LedPin3, HIGH);
  digitalWrite(LedPin4, HIGH);
  digitalWrite(LedPin5, HIGH);
  digitalWrite(LedPin6, HIGH);
  delay(600);
  digitalWrite(LedPin1, LOW);
  digitalWrite(LedPin2, LOW);
  digitalWrite(LedPin3, LOW);
  digitalWrite(LedPin4, LOW);
  digitalWrite(LedPin5, LOW);
  digitalWrite(LedPin6, LOW);
  delay(200);
  }
  else {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }

}

```

# Answer
> 0 votes
The code shown below is to “make the LEDs blink like the previous sketch during the 15 seconds”. The previous sketch (that is, the code in the question) turns the LEDs on for 600 ms and off for 200. The code below reverses the order – that is, does off for 200 and on for 600 – and repeats that pattern during the first 15 seconds after conditions being met. The annoyingly complicated `if` statements in the code are to prevent retriggering; that is, to prevent another 15-second blink session immediately starting up if the trigger conditions are still present. Your problem statement is not perfectly clear on how that should be handled.

```
// 6 Flashing LED Lights With A Pushbutton and FSR Sensor

enum { LedPin6=2, LedPin5, LedPin4, LedPin3, LedPin2, LedPin1 };
enum { buttonPin=8, SensorPin = A0};
enum { quantum=200, sessionLength=15000/quantum};

byte buttonState = 0;
byte SensorPinReading;
byte blinkLEDs=false, sessionDone=false;
unsigned long baseMilli;

void setLEDlevels(byte level) {
  digitalWrite(LedPin1, level);
  digitalWrite(LedPin2, level);
  digitalWrite(LedPin3, level);
  digitalWrite(LedPin4, level);
  digitalWrite(LedPin5, level);
  digitalWrite(LedPin6, level);
}

void setup() {
  Serial.begin(115200);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if (SensorPinReading < 10) {
    Serial.println(" - No Pressure");
  } else if (SensorPinReading < 200) {
    Serial.println(" - Light Touch");
  } else if (SensorPinReading < 500) {
    Serial.println(" - Light Squeeze");
  } else if (SensorPinReading < 800) {
    Serial.println(" - Medium Squeeze");
  } else {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);
  // Turn on 15-second blink session if conditions met
  if (buttonState == HIGH && SensorPinReading > 10)  {
    if (!blinkLEDs && !sessionDone) { // Is session eligible?
      blinkLEDs = true;
      sessionDone = false;
      baseMilli = millis();
    }
  } else {               // A condition failed.
    if (sessionDone)             // Has session finished?
      blinkLEDs = sessionDone = false; // Enable next session
  }

  if (blinkLEDs) {
    int age = (millis()-baseMilli)/quantum;
    setLEDlevels((age&3)>0);    // Off for 1 quantum, on for 3 quanta
    // See if blink session has run long enough
    if (age > sessionLength) {
      blinkLEDs = false;        // Stop blinking
      sessionDone = true;   // Prevent retrigger until conditions reset
      setLEDlevels(LOW);    // Turn off lights
    }
  }
}

```

The statement `setLEDlevels((age&3)>0)` calls `setLEDlevels()` with a parameter value of 0 or 1. It will be 0 if `age` is a multiple of 4. In binary, multiples of 4 have their lowest two bits clear. It will be 1 if `age` is not a multiple of 4. This will alternately turn the LEDs off for one quantum (200 ms) and then on for 3 quanta (600 ms).

---

*Edit 1:* To “make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed”, add a state variable (eg `sensorPressed`) to use in place of `SensorPinReading > 10`. Whenever `SensorPinReading` is large enough (and any other necessary conditions are met), set `sensorPressed`. When you start a blink session, reset `sensorPressed` (make it false).

Note, from your comment, you've added the following code near the end of `loop()`:

```
if (buttonState == LOW && blinkLEDs == true) {
  blinkLEDs = false;
  sessionDone = true;
  setLEDlevels(LOW);
}

```

A minor issue with that code is it leaves `sessionDone = true`. It is minor because the next pass through `loop()` usually will execute the `else` branch (of the `if (buttonState == HIGH && SensorPinReading > 10)` if-statement) which will go ahead and set `sessionDone = false` to enable the next blink session. Assuming you want to shut down blinking whenever the button is low, what I would do instead of that little code block is this:

```
if (!buttonState) {
  blinkLEDs = sessionDone = false;
  setLEDlevels(LOW);
}

```

(The expression `!buttonState` has the same value as `buttonState == LOW` and is four syllables shorter.)

Note, the code perhaps can be made more clear by using a *state machine* to control what happens. To do so, draw a diagram with nodes representing possible states – such as “idle” or “waiting for inputs”, “enabled”, “blinking”, “after blinking”. Draw lines between states, each labeled with the condition that triggers the particular state transition. State machines can be implemented using switch and case statements, or via an if–else sequence.

# Answer
> 1 votes
Here below is modified code based on your requirement. There are some changes in your code and I also comment it out. I hope it will help you.

```
/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;

const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

const int kDelay = 1000; // Take one varible "kDelay" and value = 1000

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup()
{
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);

  pinMode(buttonPin,INPUT_PULLUP); // Provide PULLUP
  pinMode(SensorPin, INPUT);
}

void loop()
{
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if(SensorPinReading < 10)
  {
    Serial.println(" - No Pressure");
  }
  else if (SensorPinReading < 200)
  {
    Serial.println(" - Light Touch");
  }
  else if (SensorPinReading < 500)
  {
    Serial.println(" - Light Squeeze");
  }
  else if (SensorPinReading < 800)
  {
    Serial.println(" - Medium Squeeze");
  }
  else
  {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);

  if(buttonState == HIGH && SensorPinReading > 10)
  {
    digitalWrite(LedPin1, HIGH);
    digitalWrite(LedPin2, HIGH);
    digitalWrite(LedPin3, HIGH);
    digitalWrite(LedPin4, HIGH);
    digitalWrite(LedPin5, HIGH);
    digitalWrite(LedPin6, HIGH);
    delay(15 * kDelay);            // You need 15 Sec, multiply kDelay with 15
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
  else
  {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
}

```

---
Tags: arduino-uno, sensors, led, sketch, button
---


# Question
Title: ESP8266 (ESP-01) Not booting with load on IO pin 2
I'm using an ESP-01 to control a load (SSR), which is connected to IO pin 2. This pin needs to be `HIGH` at boot time, otherwise the module won't boot. I've tried driving the load with an optocoupler to avoid driving the pin `LOW` while booting, but it's not working. Do you know of any solution to make it boot correctly without changing the IO pin? (there's only two GPIO pins, both ocuppied, plus serial port pins).

# Answer
> 2 votes
Simply invert the logic - so that LOW turns the SSR on and HIGH turns it off.

Try something like this:

simulate this circuit – Schematic created using CircuitLab

The P-channel FET will invert the logic. Pull GPIO2 LOW and it will turn on the FET which will enable the SSR. The 10KΩ resistor keeps the GPIO pin (and the gate of the FET) HIGH at other times.

If the GPIO pin can sink enough current to directly drive the SSR you can leave out the FET:

simulate this circuit

Again the logic is inverted. Pull GPIO2 LOW to sink current through the SSR to turn it on. The resistor keeps the GPIO pin held HIGH when booting.

# Answer
> 0 votes
I did something similar to what @Majenko proposed in his answer (as in I inverted the output), but instead of using R1 as a pullup resistor in paralell with the SSR's LED, I'm using it as a normal current limiting resistor. In other words, I just swapped GPIO2 from sourcing the SSR to sinking it. The schematic is like this:

---
Tags: esp8266
---


# Question
Title: Middle school Student stuck and needs help
I have a middle school student who is having problems getting her pollution sensor to work when asked to. I have attached her document to this post. Can anyone help her fix the issue?

```
int conductivitySensorValue; //initialize an integer variable to hold the sensor reading

void setup() {
Serial.begin(9600); //start serial communications so we can print the reading out

}

void loop() {
  conductivitySensorValue = analogRead(A0); //gat the integer representation of the sensor reading

  float voltage = conductivitySensorValue*(5.0/1023.0); //put the data in terms of our voltage (5 volts)

  Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port
}

Arduino: 1.8.2 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Users\sushmit\Documents\Arduino\sketch_apr19a\sketch_apr19a.ino: In function 'void loop()':

sketch_apr19a:13: error: invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

   Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port

                                          ^

exit status 1
invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

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

```

End copy.......

# Answer
> 4 votes
You can't add a string literal and a number together.

Instead you either have to convert one or both into a format that can be joined, or just treat them as separate entities. The simplest way is:

```
Serial.print(F("The Conductivity Is: "));
Serial.println(voltage).

```

Note the use of `F(...)` around the string literal - that forces it to stay in Flash so it doesn't waste RAM. Maybe not an issue with this project, but a good habit to get into nonetheless.

---
Tags: code-review
---


# Question
Title: SoftwareSerial response is semi-gibberish using ESP8266
I have a working SoftwareSerial connection to my ESP8266 module on my Arduino UNO board. However, the response I get from the ESP8266 using the SoftwareSerial library is semi-gibberish.

So I do get the correct response, but some characters are changed. For example when I ask the IP of the module, it sometimes returns the right IP, but most of the times just alters the IP, for example 092.168/123.5.

So what am I doing wrong?

This is the code I'm currently using:

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");
}

void loop() {
  if (esp8266.available()) {
    Serial.println(esp8266.readStringUntil("\n"));
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

```

When I send the `AT` command, I sometimes get `OK□` or some other extra random characters.

So how do I make the SoftwareSerial show (or receive) the correct response?

# Answer
Try lowering your baudrate to 9600.

https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/
> 0 votes

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


title: Arduino Nano, nodeJS serial

text:
# Question
Title: Arduino Nano, nodeJS serial
I tried to make a 2 way communication between my Arduino and a PC(running linux mint) using NodeJS:
My Arduino code:

```
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) Serial.println(Serial.readString()+"\r");
}

```

My NodeJS code:

```
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
  parser: SerialPort.parsers.readline('\r\n')
});

port.on('open',function(){
  setInterval(() => port.write('Test'),1000);
});

port.on('data',(data) => console.log(data.toString()));

```

There is possible encoding error, but I cannot seem to find and fix this. Thanks in advance

# Answer
You don't need to revert to sending single bytes. Line oriented protocols work well with both Arduino and Node.js. The only difficulty is that you have to *decide* what line terminators you want to use, and then *consistently* use them.

I tend to use CR for the PC → Arduino stream and CRLF for Arduino → PC. Using different line terminators is kind of odd, but this convention plays well with terminal emulators: the emulator usually sends CR when you hit `<Enter>`, and expects CRLF in return. Also, Arduino's `Print::println()` sends CRLF.

Here is a simple test demonstrating this convention. Node.js side:

```
var SerialPort = require('serialport'),
    port = new SerialPort('/dev/ttyACM0', {
        baudRate: 9600,
        parser: SerialPort.parsers.readline('\r\n')
    });

port.on('open', () => setInterval(() => port.write('Test\r'), 1000));
port.on('data', console.log);

```

Notice the different line terminators in `readline()` and `write()`.

The Arduino side:

```
void setup() {
    Serial.begin(9600);
}

void loop() {
    static char buffer[128];
    static size_t pos;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {                       // line terminator
            buffer[pos] = '\0';                // terminate the string
            Serial.print(F("Arduino received: "));
            Serial.println(buffer);            // echo received message
            pos = 0;                           // reset buffer position
        } else if (pos < sizeof buffer - 1) {  // regular character
            buffer[pos++] = c;                 // buffer it
        }
    }
}

```

Here you may notice that Arduino has no equivalent of `parsers.readline()`, so I had to implement it (comparing the incoming character to `'\r'`). Note that explicit buffering of the incoming message is a standard way of handling line-oriented protocols on Arduino. `Stream::readString()` does not work well for this purpose, as it waits for incoming bytes until it times out. `Stream::readStringUntil()` may work better, but I prefer to avoid it just because it returns a `String`, which relies on heap allocation.
> 1 votes

# Answer
Ok, I solved the issue by using pure bytes, and then casting the response to the string in nodeJS, I post the codes in case anyone needs them:

```
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
//  parser: SerialPort.parsers.readline('\r\n')
});

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

port.on('open',() => {
  setInterval(() => port.write('Test'),500);
});

port.on('data',(data) => {
  console.log(ab2str(data));
});

```

And the Arduino code:

```
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) Serial.write(Serial.read());
}

```
> 0 votes

---
Tags: serial, node.js
---


# Question
Title: How can I learn to use Generic ESP8266 boards Libraries in Arduino?
I am new to ESP8266. I am using the Arduino IDE to program the ESP8266-01 module. How can learn to make my own codes for ESP using Arduino?

I am going through the example programs and learning which part of the code does what. But, is there a better way to understand the syntax of those libraries.

Thanks!!

# Answer
They publish a reference page for the included libraries at each release of the ESP8266 core for Arduino. The latest at this time is here:

http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html

You can adjust that URL for the release version you're using.

The libraries try to follow the API of the standard Arduino libraries and that documentation mostly focuses on the differences. So you will also find some documentation for these libraries in Arduino's library reference pages:

https://www.arduino.cc/en/Reference/Libraries

and the reference pages for the Arduino core API:

https://www.arduino.cc/en/Reference/HomePage

Of course the definitive (albeit less beginner friendly) reference will always be the source code. There are two ways to quickly determine the location of the source code for a library:

**Option 1:**

1. Select the appropriate board from the **Tools \> Board** menu. The Arduino IDE may select the library to be used based on which board is selected.
2. File \> Examples \> {library name} \> pick any example
3. Sketch \> Show Sketch Folder. This will open the {library name}/examples/{example name} folder. The source files for the library will be found in the library root folder, `src` folder, or `utilities` folder.

**Option 2:**

1. File \> Preferences \> Show verbose output during: \> compilation (check) \> OK
2. Write or open a sketch that includes the library.
3. Sketch \> Compile/Verify
4. Wait for the compilation to finish.
5. Examine the contents of the black console window at the bottom of the Arduino IDE window. The path to any library used by the sketch will be found in that output.
> 0 votes

---
Tags: esp8266
---


# Question
Title: High power consumption of ATmega32u4 when connected to iOS device
Just wondering if I can get some help here.

I have a simple scheme of MIDI controller based on ATmega32u4: ATmega32U4 with TXLED and RXLED as output pins and USB functionality

And my team wants me to make this device Android/iOS compatible (because our Arduino prototypes worked fine with iPads and even iPhones).

I am experiencing a high power consumption of ATmega32u4 when connected to iOS devices. When we connect our device to iOS we get the following message:

Meanwhile, when I make almost the same scheme and run the identical sketch on ATmega328 chip it works just fine!

I tried running all the stuff on Arduino boards, and the result is stable:

* works on Arduino Uno and Arduino Mega (based on ATmega328 chip);
* doesn't work on Arduino Micro and some of its Chinese clones like Arduino Micro Pro (based on ATmega32u4).

We've found a small trick/workaround: connect even two our ATmega32u4 devices through an active USB hub with additional power supply to one iPad, and they both work perfectly, then we switch off the additional power on the hub, and devices continue to work fine using the power from this single iPad without any messages about high power consumption. This case leads me to the thought that high consumption of ATmega32u4 chip appears only on the device initialisation stage.

Is there a way to solve this?

Thanks in advance.

# Answer
> 2 votes
The major difference between ATmega32u4 and ATmega328 is that the former has USB functionality built in, while the latter requires an external USB to UART chip. When such UART chips go through enumeration, they will tell the host that they only consume 100 mA or less, because they have no idea what else you have on the board. ATmega32u4 however can potentially consume up to 200 mA (sinking 100 mA through each of the IO banks). Maybe it's requesting that current from the host when you connect it, and your phone refuses to power up a device requesting more than 100 mA of current.

You can connect your controller to a computer and check USB properties to confirm this.

---
Tags: atmega32u4
---


# Question
Title: Name of the Arduino Nano clone in the device manager
I'm working on an app using Matlab and it recieves data from an arduino. I've changed my board into an Arduino Nano (clone) recently. My program will automatically check for the device's name in the list of serial devices connected and it will connect to it directly once the user presses connect. The user doesn't have to input any Com port number or baud rate. This worked fine with my previous boards (UNO, Pro Micro, Leonardo). I just need to change the search string in my code and it'll automatically connect. My current board however is different, I'm using VMA102 (Arduino Nano clone). It uses FTDI drivers which I downloaded following this tutorial. I can upload the codes correctly to it but I just doesn't show a name with in the ports list in Arduino IDE as shown in the picture below.

Now when I looked it up in the device manager the name was 'USB Serial Port (COM5)' so I pasted 'USB Serial Port' as my search text in Matlab, it doesn't find it. I concluded that the correct name for it is not 'USB Serial Port' but rather the 'no name' as shown in Arduino IDE. Is there a way to find what is it called or how I can change it into a unique name so that my app can search for it?

Edit: here is the code, it works fine with all the other boards: devices = IDSerialComs();%gets all the avilabe com ports and thier names (name, com#) assignin('base','devices',devices);%save it to main workspace

```
i=1;index=0; tesst= zeros(length(devices),1);%saves the comparison results
while i<=length(devices)
    tesst(i)= strcmp(devices{i,1},'USB Serial Port');%compare the received names with the board's name
    % 'SparkFun Pro Micro''Arduino Uno'
    if ( tesst(i)==1 )
        index=i;%save the index
    end
    i=i+1;
end

if(isempty(find(tesst,1)))
    msgbox({'Connection failed' ' plug the device, wait for 5 seconds then try again'} ,'Connection Failure','error');
else
    msgbox('Connection successful, proceed to the next tabs', 'Connection success');
end
%get the COM# associated with the index and add COM before it to from the comport number as a string
COM_Num = strcat('COM',num2str(devices{index,2}));
comport= serial(COM_Num, 'BaudRate', 115200);

```

and here is a screenshot of my device manager

Thanks

# Answer
> 2 votes
The IDSerialComs() function scans the Windows registry and associated active COM ports with their registered "Friendly Name". To scans using the following path:

```
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\'

```

But driver FTDI uses another path:

```
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\'

```

Try to modify the function so that it meets your needs.

# Answer
> 1 votes
If you do a windows search for the device manager you will be able to see all the com devices currently connected to your computer. Unplug and replug your Arduino and it should be pretty easy to spot.

Mine is the USB-SERIAL CH340

---
Tags: arduino-nano
---


title: Arduino Due DAC pins with 0V

text:
# Question
Title: Arduino Due DAC pins with 0V
I know the DACs on the Arduino Due only allow for a range of output voltages from 1/6\*Vdd to 5/6\*Vdd (see here). This suits my needs, for the most part.

My question is if it is possible to have 0V on the DAC pins by, for example, switching the DACs of completely, or using them as normal digital out pins. I'd like to do this without the need for any external hardware or circuitry.

I googled for solutions but found none.

# Answer
> 0 votes
The DAC is port B15 and B16 so yes, it is possible to disable the DAC and use those pins as normal GPIO pins. Not sure how you would do it though, if the Arduino definitions have those pins set up for GPIO or not (away from my computer at the moment).

---
Tags: arduino-due, digital-analog-conversion
---


# Question
Title: How to receive data from my server database to a variable in my Arduino?
I am learning to work with the client - server communication. I am able to communicate with my server and able to store values in the table. But I want to receive one of the specific data from the database.

Here I want to get the 'abc' value from the 'Current' column to store in a variable in my Arduino.

Below is the code that I have done until now. I would be really happy if you could solve the problem.

Here is my database structure

```
---------------------------------------------------
| Device |  Previous |  Next |  Distance |  Current|
---------------------------------------------------
|katup123| xyz       | abc   | 2.600     | abc     |
---------------------------------------------------

```

Here is my PHP code:

locator.php

```
<?php
$con=mysqli_connect("your_domain.com","peter","abc123","locate");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Current FROM locate WHERE Device='katup123'");

while($row = mysqli_fetch_array($result)) {
  echo $row['Current'];
  echo "<br>";
}
?>

```

Here is my Arduino code:

```
// Include the GSM library
#include <GSM.h>
#define PINNUMBER ""
// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APNgpsll
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password
// initialize the library instance
GSM gsmAccess;
GSMClient client;
GPRS gprs;
// URL, path & port (for example: arduino.cc)
char server[] = "your_domain.com";
char path[] = "/locater.php";
int port = 80; // port 80 is the default for HTTP

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;
  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected) {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) & (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  Serial.println("connecting...");
}

void loop() {
  char result [20];
  Serial.print(" Connecting to server Database ");
  if (client.connect(server, port)) {
    client.print("GET /locator.php?");
    Serial.print("GET /locator.php?");
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: www.your_domain.com");
    Serial.println("Host: www.your_domain.com");
    client.println("User-Agent: Arduino");
    Serial.println("User-Agent: Arduino");
    client.println("Accept: text/html");
    Serial.println("Accept: text/html");
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
    Serial.println();
    Serial.println("\nCOMPLETE!\n");
    client.stop();
  } else {
    Serial.println("connection failed");
    Serial.println("\n FAILED!\n");
  }
  delay(5000);
}

```

Here I want to store the 'abc' value to my 'result' variable. I don't know how to do it.

# Answer
After you send the GET request, you read the response to fill the `char result [20]` variable you declared:

```
int i=0;
...
if (client.connect(server, port))
{
  client.print("GET /locator.php?");
  ...
  Serial.println("\nCOMPLETE!\n");

  // Read response from server
  i=0;
  while (client.available())
  {
    result[i] = client.read();
    Serial.print(result[i]);
    i++;
  }

  client.stop(); // disconnect
}

```

This is an example, `result` will contain the text output by locator.php. You will need to tweak this code to apply to your case. The above code has no error checking of any kind. Also, you should perform a check and only make the web call one time.

In locator.php you should replace `echo "<br/>";` with `echo "\n";`. And for good measure, make sure there is no white space before `<?`, and remove the trailing `?>`.
> 2 votes

# Answer
If you have your Arduino on tcp/ip your answer can be found in O'Reilly's Arduino Cookbook: Recipe 15-4. As Sourcery mentioned you need to make a new page on the PHP side that spits out just the data you are looking for and then use a web client on the Arduino side to download that data.

If you don't have your Arduino on the network then you have to stick the data over the serial line. One way would be to bake it into your source and recompile/reburn the Arduino. A smaller hammer would be to build-in something to your Arduino sketch that can deal with getting the data via USB serial and have a shim on the computer side to pull the data from PHP and send it to the Arduino. Serial communication with Arduino and Processing shows something similar where he is running Processing on the computer which is passing data to the Arduino.
> 1 votes

---
Tags: arduino-uno, gsm, web-server
---


# Question
Title: Converting a message received in char buffer to integer
I am receiving a message from my mobile to my microcontroller via GSM. The message is in a char buffer, but I want to convert it to an integer as I want to perform some mathematical operations on it. I tried many functions such as `atoi`, `toint` but it's not working. Please let me know if there is any way in which I could do this conversion.

# Answer
`atoi()` is the simplest way:

```
int val = atoi(buf);

```

If that doesn't work then your buffer doesn't start with the number you are after. If that is the case you will have to work out where in the buffer the number is and convert just that portion. How you do that depends on what the format of the data is in your buffer.
> 1 votes

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


title: Evaluating delay for Xbee

text:
# Question
Title: Evaluating delay for Xbee
I will explain my task in a simplified way. I'm communicating among 3 Xbee's.

The attached code is for the sender Xbee. This Xbee actually sends multiple values of **value1** (*here for simplification I assigned it to constant value 10*). For finding the value1 it does some other calculations as well and then assigns it.

But I find that if I reduce or remove the delay(100) I end up receiving improper values. I guess delay gives a buffer time for data transmission but my question is how to do I calculate the minimum delay or how can justify that this is the delay needed ?

I hope you can understand my question. If not please comment I will give some more pertinent details.

```
  // Sender Xbee
    void setup()
    {
    Serial.begin(9600);
    }
    void loop()
    {
    int value1 = 10; // some hardcoded values to send
    Serial.print('H'); // unique header to identify start of message
    Serial.print(value1,DEC);
    Serial.print(","); // note that a comma is sent after the last field
    Serial.print('\n'); // send a cr/lf
    delay(100);
    }

```

# Answer
Based on my experience with Xbee, I would say the limit is 50ms as Xbee can do the lowest sampling rate of 50ms.
> 1 votes

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


# Question
Title: how to move my robot to the assigned coordinates
I am working on an ground surveillance robot using an Arduino mega for programming, am using components like the HMC5883L compass, Adafruit GPS for assigning of coordinates (latitude and longitude) which are the way points, I have written up the code for both the compass and the GPS and am able to get information from them, but now what I want for my robot to move to those specified coordinates (latitude and longitude waypoints) which I don't know how to do please do pardon me for asking such question cause I am new to coding GPS and compass and I would appreciate it if anyone could help me out or explain a bit in details what I need to do please find my code here http://textuploader.com/drqwv

# Answer
> 1 votes
Due to my robot I have been thinking about this problem quite a few times but I never got to coding. So this is a purely my thinking no experience.

The problem is not only calculating where you are and where to go. The robot needs to move so it needs to know whether it needs to turn (left or right; slow or fast) to drive into the correct direction.
So basically you want a method that takes the compass direction the 2 gps locations and returns a speed and turn value.
The speed and turn value will be different for a waypoint and the final destination. I thought to do so by switching to the next waypoint before coming in the "slow down area". This should make that only one algorithm can handle both situations.
I think the algorithm is likely to look like this.
Given the 2 gps locations calculate the expected compass reading.
Given the 2 gps locations calculate the distance
Based on the distance and the difference between the expected and actual compass reading decide on the speed and turn.

As to the last step there is no "one size fits all" for instance a skid driven robot may opt to turn on the spot until it hits the expected compass reading.
If you have a slow turning robot and you are close to the waypoint you may opt to drive backwards first (like parking a car)

I hope this helps

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


# Question
Title: Arduino Uno with UsbSerial Android library w/ baud rate over 9600?
I am having no issues talking to Android at baud rate of 9600. But once I raise the baud rate to anything higher Android seems to become deaf. When I try to read the Serial output using putty all seems fine.

Has anyone had success with baud rate over 9600 when talking to Android?

I am using the felHR85/UsbSerial library.

# Answer
I have no enough reputations to make a comment so I will drop my two cents here.

Are you changing the baudrate at both sides?

I have been using the arduino's built-in UART library for a while using different baudrates with no problems. Your problem could be an issue related to the library you are using.
> 1 votes

# Answer
Seems like there is a bug in the library.
> 0 votes

---
Tags: android, baud-rate
---


title: Powering an USB to Serial from USB

text:
# Question
Title: Powering an USB to Serial from USB
I am creating a PCB which is a modification of the Arduino on a breadboard. I am intending to buy an USB to Serial breakout from Adafruit so that I can upload my sketches to the atmega 328 I'll be using.

However, in order to reduce power consumption (later I want to run my circuit by using some AA batteries), I would like to turn off the USB to Serial breakout. I thought originally about adding a SPST switch to disconnect it when not using it, but I wonder if it is possible to power it from the USB (whenever I connect something) instead of having to connect its VCC header to the circuit's 5v power.

Is it possible to do that? Or is there any other way I to accomplish this that I'm not thinking of?

**UPDATE:** *For clarity sake, I will explain my design choices: I want this circuit to power some peristaltic pumps that work on 12V. Thus, I'm providing 12V for the pumps and using a regulator to lower the voltage to the circuit. I don't see this is a huge problem for power consumption because the circuit will be in low-power 98% of the time, only waking up one minute per hour. Sometimes, it will run on batteries, which is the reason I wanna eliminate the USB-to-Serial. However, when connected to a power adaptor, I want the USB to be available.*

All the best,

Francis

# Answer
> 2 votes
You might be overthinking this. As Gerben points out in the comments, you might want to consider pluging in the USB to Serial breakout board only when required, instead of making it a permanent part of your prototype.

I do this myself in two ways, depending of what I need.

## Option 1:

When I foresee a lot of debbuging through the Serial Monitor, I use a permanent pin header so I can attach and dettach the breakout board easily.

In this case I use a right angle pin header so as to keep a low profile. Like in this Arduino Pro Mini:

## Option 2:

When I just need to upload the sketch to the Arduino and I know that I won't be using the breakout board from that moment on, I don't solder the pin header in place.

Instead, I've modified another breakout board using pogo pins (spring test probes):

This modified board is what I use to upload the code to the Arduino without any pin header whatsoever. Something like this (I've taken the picture just for illustrative purposes):

# Answer
> 1 votes
That is not easy to do. You could try diodes and mosfets as switches, but one way or the other, there will probably some leakage current. The 6N137 requires power for the receiving signal.
Other common optocouplers might have leakage current in the nA range for the transistor output. That might be possible. Connect the GNDs. The RX and TX via optocouplers. DTR to RESET with 100nF as usual. Maybe you don't need extra inverters when the transistor outputs are used as emitter followers.

Could you make your project with the ATmega328P without the usb-to-serial module ? The Arduino Pro Mini does not have a usb-to-serial either.
Now that I mention the Arduino Pro Mini: Instead of making an Arduino compatible circuit with a ATmega328P, you could also buy a Arduino Pro Mini 8MHz, and remove the voltage regulator and the power led. Then you have the same thing.

That breadboard Arduino tutorial has +5V connected to AREF. Please don't do that. Keep AREF open, or connect a capacitor of 100nF to it to reduce some noise for analogRead.

In the deepest sleep mode, the ATmega328P can run more than a year on three AA batteries. The timer of the WatchDog can be used to wake up.
The voltage of the three AA batteries is directly connected to the VCC of the ATmega328P, without voltage regulator.

A very good tutorial about power saving is this: Nick Gammon about power saving

# Answer
> 1 votes
Using separate power supplies at the same time for different parts of your system is a bad, bad idea; you never want two separate power supplies potentially pushing current at each other. Using separate +5V power sources for different chips but sharing a common ground across the device and connecting just data lines is problematic, too; as far as I know it's not trivial to do safely. Unless you really know what you're doing, full isolation between separately powered components is the way to go.

The two parts of the system we're talking about here, the USB-Serial converter and the rest of the system, exchange digital data only, and that at only three points, all of which are unidirectional: serial TX, serial RX and DTR. (DTR, when pulled low by the PC, resets the Arduino). Therefore if we can isolate these links not to exchange current when they communicate, we can separately power the devices on each side of this isolation barrier.

This is actually a common problem in things like power supplies (where we want data from the high-voltage side sent to the low-voltage side but don't want the risk that someone touching the low-voltage side could get electrocuted) and motor control boards (where the motors often use a separate power supply from the controller logic to reduce noise passed into the controller logic). One common solution is to use opto-isolators (also called optocouplers). Typically these use an LED and a sensor looking at it from across a gap; when the LED is lit up by one side, the other side sees it and generates a current.

The 6N137 (as used in this answer) or similar chip should work for this: 10 MHz is plenty of bandwith to run a 115,200 baud serial link. Each opto-coupler would be powered by the receiving side (Arduino for its RX and DTR, USB-serial for Arduino's TX) and on the other side you'd connect data to the VF\+ pin and ground to the VF\- pin. As per note 1 on page 4, you'll need caps at the power supply inputs, and you'll have to add inverters as well if you use this particular opto-isolator, since it inverts the signal; a 74HC04 will give you six of those. If you want to save a dollar, you could not bother to connect the DTR line and just reset the Arduino manually when you want to upload a program, if that's not too inconvenient.

Consumer warning here: I've not actually built this circuit (though I'd like to give it a try one day), so there could be something I'm missing here. (Hopefully someone more expert than me will speak up if that's the case.)

If you're going to be spending any significant amount of time connected to USB power and your whole system can run on less than 500 mA (the limit of the USB supply from many PCs), you may want to consider powering the entire system from USB while it's connected. This can be done in a way similar to how the Arduino Uno board disconnects USB power when receiving power on `Vin`: switch it with a comparator and a MOSFET.

---
Tags: power, atmega328, pcb-design
---


title: reverse 12v motor

text:
# Question
Title: reverse 12v motor
I am working on an RC car, and I need to be able to reverse a 12v circuit that powers my main drive motor.

I have a TIP102 transistor and a 5-30v relay for each motor terminal. I assumed that I could open up ground via the transistor on one side, and the power relay on the other, and then switch these to reverse.

My motor runs each direction when hooked directly to the battery, and my relays are definitely outputting the full 12v, but I seem to have a problem with the grounding circuit. Whichever side has the relay switched on, that transistor gets very hot, and my motor doesn't spin. I tested the transistor and can get it to ground when on a single directional circuit with just the relay on one side and the TIP102 on the other.

Here is my wiring. Can anyone tell me where I screwed up?

Ignore the 9v, I just couldnt find a 12v in fritzing

# Answer
> 0 votes
If the diagram correctly represents what you have, it isn't obvious to me what the problem might be. One possibility is that the base resistors to the TIP102's are too large. Too little current into a transistor base keeps a transistor out of saturation, ie operating in a linear mode instead of switching mode, leading to high power loss and high heat. Slightly more likely is that the fairly high voltage drop across the Darlington in the TIP102 is just heating it up a lot.

If, as suggested in a comment, you were to use an H-bridge motor driver, it might include heat sinks or might use MOSFETs with lower voltage drops; thus avoiding so much lost heat, one way or the other.

As it happens, you probably don't need the transistors in the circuit anyway. Label the relays as A and B. Hook one of the motor leads to the common terminal of A, and the other motor lead to the common terminal of B. Hook the NO lead of each relay to V+, and the NC lead of each to ground. To run one direction, switch A on and B off. To run the other direction, switch A off and B on. To stop, switch both off.

---
Tags: motor, relay, transistor
---


# Question
Title: Moving wiring.c functions from timer0 to timer1
I am using an Arduino Leonardo (ATmega32U4) and need to use timer0 for PWM. Since by default in the wiring.c file the functions `micros()` and `millis()` use timer0, I decided that, since timer1 isn't being used, I could set up timer1 exactly how timer0 is set up for the `micros()` and `millis()` functions and modify their code so that it all uses timer1 instead of timer0.

I think in theory this should work. I read the datasheet and timer1, while being a 16-bit timer, can run in an 8-bit fast PWM mode (which is what timer0 is set up for). So I modified wiring.c to do as above: adjusted the prescaler to match the original for timer0 (f/64) and put timer1 into fast-pwm 8-bit mode.

I modified all functions in wiring.c that used any register from timer0 and changed them to use the corresponding registers in timer1.

However, the problem is that it seems like I did everything right, but when I try to run a simple program that calls `Serial.println("hello world")`, it is messed up. The output instead shows a repeated 'h' character to the serial console. I'm not really sure what's wrong and wondering if anyone can help.

Here is my re-written wiring.c file that essentially moves all the functionalities from timer0 to timer1:

```
#include "wiring_private.h"

// the prescaler is set so that timer0 ticks every 64 clock cycles,
// and the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
// the whole number of milliseconds per timer0 overflow
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)

volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
/*************************** Modified wiring.c TIMER1 ISR ***********************/
ISR(TIMER1_OVF_vect)
#endif
{
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;
}
/************************** End TIMER1 ISR **************************************/

unsigned long millis() {
    unsigned long m;
    uint8_t oldSREG = SREG;
    // disable interrupts while we read timer0_millis or we might get
    // an inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;
    return m;
}

/************************ Modified micros() function ****************************/
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;
    cli();
    m = timer0_overflow_count;
#if defined(TCNT1)
    t = TCNT1;
#else
    #error TIMER 1 not defined
#endif

#ifdef TIFR1
    if ((TIFR1 & _BV(TOV1)) && (t < 255))
        m++;
#else
    #error TIFR 1 not defined
#endif
    SREG = oldSREG;
    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}
/************************ End micros() ******************************************/

void delay(unsigned long ms) {
    uint32_t start = micros();
    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us) {
    // call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable)
    // calling avrlib's delay_us() function with low values (e.g. 1 or
    // 2 microseconds) gives delays longer than desired.
    //delay_us(us);
#if F_CPU >= 24000000L
    // for the 24 MHz clock for the aventurous ones, trying to overclock
    // zero delay fix
    if (!us) return; //  = 3 cycles, (4 when true)
    // the following loop takes a 1/6 of a microsecond (4 cycles)
    // per iteration, so execute it six times for each microsecond of
    // delay requested.
    us *= 6; // x6 us, = 7 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 22 (24) cycles above, remove 5, (5*4=20)
    // us is at least 6 so we can substract 5
    us -= 5; //=2 cycles

#elif F_CPU >= 20000000L
    // for the 20 MHz clock on rare Arduino boards
    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 18 (20) cycles, which is 1us
    __asm__ __volatile__ (
        "nop" "\n\t"
        "nop" "\n\t"
        "nop" "\n\t"
        "nop"); //just waiting 4 cycles
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes a 1/5 of a microsecond (4 cycles)
    // per iteration, so execute it five times for each microsecond of
    // delay requested.
    us = (us << 2) + us; // x5 us, = 7 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 26 (28) cycles above, remove 7, (7*4=28)
    // us is at least 10 so we can substract 7
    us -= 7; // 2 cycles

#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards
    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)
    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can subtract 5
    us -= 5; // = 2 cycles,
#elif F_CPU >= 12000000L
    // for the 12 MHz clock if somebody is working with USB

    // for a 1 microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1.5us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/3 of a microsecond (4 cycles)
    // per iteration, so execute it three times for each microsecond of
    // delay requested.
    us = (us << 1) + us; // x3 us, = 5 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 20 (22) cycles above, remove 5, (5*4=20)
    // us is at least 6 so we can substract 5
    us -= 5; //2 cycles

#elif F_CPU >= 8000000L
    // for the 8 MHz internal clock

    // for a 1 and 2 microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 2us
    if (us <= 2) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/2 of a microsecond (4 cycles)
    // per iteration, so execute it twice for each microsecond of
    // delay requested.
    us <<= 1; //x2 us, = 2 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 17 (19) cycles above, remove 4, (4*4=16)
    // us is at least 6 so we can substract 4
    us -= 4; // = 2 cycles

#else
    // for the 1 MHz internal clock (default settings for common Atmega microcontrollers)

    // the overhead of the function calls is 14 (16) cycles
    if (us <= 16) return; //= 3 cycles, (4 when true)
    if (us <= 25) return; //= 3 cycles, (4 when true), (must be at least 25 if we want to substract 22)

    // compensate for the time taken by the preceeding and next commands (about 22 cycles)
    us -= 22; // = 2 cycles
    // the following loop takes 4 microseconds (4 cycles)
    // per iteration, so execute it us/4 times
    // us is at least 4, divided by 4 gives us 1 (no zero delay bug)
    us >>= 2; // us div 4, = 4 cycles
#endif
    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

void init() {
    // this needs to be called before setup() or some functions won't
    // work there
    sei();

    // on the ATmega168, timer 0 is also used for fast hardware pwm
    // (using phase-correct PWM would mean that timer 0 overflowed half as often
    // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
    sbi(TCCR0A, WGM01);
    sbi(TCCR0A, WGM00);
#endif

    // set timer 0 prescale factor to 64
#if defined(__AVR_ATmega128__)
    // CPU specific: different values for the ATmega128
    sbi(TCCR0, CS02);
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
    // this combination is for the standard atmega8
    sbi(TCCR0, CS01);
    sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
    // this combination is for the standard 168/328/1280/2560
    sbi(TCCR0B, CS01);
    sbi(TCCR0B, CS00);
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
    // this combination is for the __AVR_ATmega645__ series
    sbi(TCCR0A, CS01);
    sbi(TCCR0A, CS00);
#else
    #error Timer 0 prescale factor 64 not set correctly
#endif

    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
#else
    #error  Timer 0 overflow interrupt not set correctly
#endif

    // timers 1 and 2 are used for phase-correct hardware pwm
    // this is better for motors as it ensures an even waveform
    // note, however, that fast pwm mode can achieve a frequency of up
    // 8 MHz (with a 16 MHz clock) at 50% duty cycle

/******************** Modified Code for Timer 1 *********************************/
#if defined(TCCR1B) && defined(CS11) && defined(WGM10)
    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
    sbi(TCCR1B, CS10);

    // put timer 1 in 8-bit fast pwm mode
    sbi(TCCR1B, WGM12);
    sbi(TCCR1A, WGM10);

    // enable timer 1 overflow interrupt
    sbi(TIMSK1, TOIE1);
#endif
/********************* End Timer 1 **********************************************/

    // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
//#else
    // Timer 2 not finished (may not be present on this CPU)
#endif

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
//#else
    // Timer 2 not finished (may not be present on this CPU)
#endif

/************** Modified Code for Timer 3 ***************************************/
#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
    // set timer 3 prescale factor to 64
    sbi(TCCR3B, CS31);
    sbi(TCCR3B, CS30);

    // put timer 3 in 8-bit fast pwm mode
    sbi(TCCR3B, WGM32);
    sbi(TCCR3A, WGM30);

    // enable timer 3 overflow interrupt
    sbi(TIMSK3, TOIE3);
#endif
/************** End Timer 3 *****************************************************/

#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
    sbi(TCCR4B, CS42);      // set timer4 prescale factor to 64
    sbi(TCCR4B, CS41);
    sbi(TCCR4B, CS40);
    sbi(TCCR4D, WGM40);     // put timer 4 in phase- and frequency-correct PWM mode
    sbi(TCCR4A, PWM4A);     // enable PWM mode for comparator OCR4A
    sbi(TCCR4C, PWM4D);     // enable PWM mode for comparator OCR4D
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
    sbi(TCCR4B, CS41);      // set timer 4 prescale factor to 64
    sbi(TCCR4B, CS40);
    sbi(TCCR4A, WGM40);     // put timer 4 in 8-bit phase correct pwm mode
#endif
#endif /* end timer4 block for ATMEGA1280/2560 and similar */

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
    sbi(TCCR5B, CS51);      // set timer 5 prescale factor to 64
    sbi(TCCR5B, CS50);
    sbi(TCCR5A, WGM50);     // put timer 5 in 8-bit phase correct pwm mode
#endif

#if defined(ADCSRA)
    // set a2d prescaler so we are inside the desired 50-200 KHz range.
    #if F_CPU >= 16000000 // 16 MHz / 128 = 125 KHz
        sbi(ADCSRA, ADPS2);
        sbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #elif F_CPU >= 8000000 // 8 MHz / 64 = 125 KHz
        sbi(ADCSRA, ADPS2);
        sbi(ADCSRA, ADPS1);
        cbi(ADCSRA, ADPS0);
    #elif F_CPU >= 4000000 // 4 MHz / 32 = 125 KHz
        sbi(ADCSRA, ADPS2);
        cbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #elif F_CPU >= 2000000 // 2 MHz / 16 = 125 KHz
        sbi(ADCSRA, ADPS2);
        cbi(ADCSRA, ADPS1);
        cbi(ADCSRA, ADPS0);
    #elif F_CPU >= 1000000 // 1 MHz / 8 = 125 KHz
        cbi(ADCSRA, ADPS2);
        sbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #else // 128 kHz / 2 = 64 KHz -> This is the closest you can get, the prescaler is 2
        cbi(ADCSRA, ADPS2);
        cbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #endif
    // enable a2d conversions
    sbi(ADCSRA, ADEN);
#endif

    // the bootloader connects pins 0 and 1 to the USART; disconnect them
    // here so they can be used as normal digital i/o; they will be
    // reconnected in Serial.begin()
#if defined(UCSRB)
    UCSRB = 0;
#elif defined(UCSR0B)
    UCSR0B = 0;
#endif
}

```

# Answer
> 1 votes
Just for the record, I posted this question before I made an account by mistake, so that is why I cannot select best answer; BUT, I found the solution for anyone wondering.

I had the interrupt enabled for more than one timer (forgot to disable interrupts on the timer0 code). Once, i did that the code worked! I was able to move the millis, micros, delay, and delayMicros functions to the 16-bit timer 1!

# Answer
> 0 votes
My suggestion would be to keep the Arduino code as is and write your own micro() and millis() utilizing timer1.

It should be fairly simple.

# Answer
> 0 votes
Although I am not sure this would completely make all your changes correct, I see a potential issue in one existing line of code, that may be bad due to using a 16bits timer instead of 8bits:

```
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT1)
    t = TCNT1;
#else
    #error TIMER 1 not defined
#endif

#ifdef TIFR1
    if ((TIFR1 & _BV(TOV1)) && (t < 255))
        m++;
#else
    #error TIFR 1 not defined
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

```

Here, `t` is declared as `uint8_t` and initialized with `TCNT1`, which is a `uint16_t` (actually it is a **reference** to a `volatile uint16_t`), that may be an issue here.

I'd suggest replacing the line

```
t = TCNT1

```

with

```
t = TCNT1L

```

where `TCNT1L` is now a reference to `volatile uint8_t` accessing the low byte of TCNT1.

---
Tags: timers, arduino-leonardo
---


# Question
Title: SAMD21 Programming with Atmel ICE Fail to Write
I am trying to program my Adafruit M0 with the SAMD21G18 chip with Atmel studio and the Atmel ICE programmer. I have pin 1 on the ICE connected to 3.3V on the M0, pin 2 connected to SWDIO, pin 4 to SWDCLK, pin 10 to Reset, and pins 3, 5, and 9 to ground. This was all according to the ARM SWD connection section of the Atmel ICE manual. In Atmel Studio, I can read the device signature, but when I go to program the chip, I get the following error:

```
Timestamp:      2017-04-20 22:03:32.563
Severity:       ERROR
ComponentId:    20100
StatusCode:     131103
ModuleName:     TCF command: Modules:writeToMemory failed.

Failed to write segment at 0x0 to target for memorytype

```

I have searched the internet for hours, finding no solution to this problem.

# Answer
Whats is the fuse setting of `NVMCTRL_BOOTPROT`?

it should be:

`NVMCTRL_BOOTPROT = 0x07`

which will set your memory location to 0x00 (no bootloader).

`NVMCTRL_BOOTPROT` sets the amount of space to allocate for the bootloader in flash memory. Setting this fuse to 0x07 tells the chip you are not allocating space for a bootloader and the programmer will start to write at address 0x00, which is the beginning of flash memory. If you are programming with an Atmel ICE, you are not using a bootloader.
> 0 votes

---
Tags: adafruit, atmel-studio, arduino-zero
---


# Question
Title: Simplifying code, getting invalid conversion from 'const char*' to 'char*'
I have a program that does 4 times the same thing with different parapmeters; and was trying to simplify my code to take one parameter as a variable.

Example (what was):

```
const char MQTT_PUB_IRRIGATION_TANK_VALVE[]      = "ArgyleCourt/Property/Hub/IrrigationTank/Valve";
const char MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE[] = "ArgyleCourt/Property/Hub/HouseBoreWaterTank/Valve";

publishTankValveStatusIrrigation(false);

void publishTankValveStatusIrrigation(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "OFF");
  }
}

publishTankValveStatusHouse(false);

void publishTankValveStatusHouse(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "OFF");
  }
}

```

to one function now passing the topic also inot the function, thus needing only one function:

```
publishTankValveStatus(false, MQTT_PUB_IRRIGATION_TANK_VALVE);
publishTankValveStatus(false, MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE);

void publishTankValveStatus(bool demandStatus, char topicToPublishTo) {
  if (demandStatus) {
    mqttClient.publish(topicToPublishTo, "ON");
  } else {
    mqttClient.publish(topicToPublishTo, "OFF");
  }
}

```

when I compile the simplified function, I get "warning: invalid conversion from 'const char\*' to 'char' \[-fpermissive\]", but do neither understand why or how to fix it.

# Answer
The function declaration

```
void publishTankValveStatus(bool demandStatus, char topicToPublishTo)

```

declares `topicToPublishTo` as a `char`, that is, as a single character instead of as an array of characters that is constant.

Change `char` to `const char *` to say that `topicToPublishTo` is an array of characters that is constant.
> 1 votes

---
Tags: programming
---


# Question
Title: ATtiny85 Timer 1 comparator A interrupt problem
I'm writing a program on attiny85 using interrupts. It is a simple program: \- when rising edge is detected on PCINT0, drive `DEBUG_PIN` to `HIGH` \- when TIMER1 counts up to OCR1A, drive DEBUG\_PIN to LOW

Problem is that when program detects rising edge on PCINT0, it starts Timer1 comparator A and then immediately calls `ISR(TIMER1_COMPA_vect)`. As an effect, on `DEBUG_PIN` there is only a little narrow spike instead of a nice square wave of length 50ms (checked it with oscilloscope).

Im using ARDUINO IDE. Here is the code:

```
/*
 * Movement detection using interrupts instead of linear approach
 *
 * POS_TIMEOUT will be checked using COMPA on TIM0
 * IMP_TIMEOUT will be checked using COMPB on TIM0
 * LOOP_TIME will be chcecked using TIMER1 overflow
 *
 * INT0_PIN_IN  (PB2) is the pin that receives the signal
 * INT0_PIN_OUT (PB4) is the pin used for external interrupt debugging
 * DEBUG_PIN    (PB3) is the pin used for debugging
 * STATUS_PIN   (PB1) - high when awake, low when asleep
*/

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

//Watch out! do not use the reset pin (PB5)!

#define INT0_PIN_IN     0
#define INT0_PIN_OUT    4
#define STATUS_PIN      1
#define DEBUG_PIN       3
#define POS_TIMEOUT     50

#define PRE_1     0
#define PRE_2     1
#define PRE_4     2
#define PRE_8     3
#define PRE_16    4
#define PRE_32    5
#define PRE_64    6
#define PRE_128   7
#define PRE_256   8
#define PRE_512   9
#define PRE_1024  10
#define PRE_2048  11
#define PRE_4096  12
#define PRE_8192  13
#define PRE_16384 14

/*******MONITORING*VARIABLES*VOLATILES**************/
/* variable keeping last state of INT0 input */
volatile bool lastState = false;

/*************STATUS FLAGS**************************/
/* flags used for movement detection */
/* all flags are initiated as false */

volatile bool positiveFlag  = false;
volatile bool fallingEdge   = false;
volatile bool risingEdge    = false;
volatile bool positiveTimeoutCheck  = false;
volatile bool impulseTimeoutCheck = false;
/*************UTILS*********************************/
void timerOneCompADisable( void ){
  bitClear(TIMSK, OCIE1A);
}

void timerOneCompAInit( uint8_t compValue  ){
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

/******************
 * INTERRUPTS!!!
******************/

/*
 * This interrupt is called every time PCINT0 input state changes
*/
ISR(PCINT0_vect){
  bool readPin = digitalRead( INT0_PIN_IN );

  //falling edge
  if( lastState && lastState != readPin ){
    fallingEdge = true;
    lastState = false;
  }
  //rising edge
  else if( !lastState && lastState != readPin ){
    risingEdge = true;
    lastState = true;
  }
}

//TIMER 1 COMPARE match A
ISR(TIMER1_COMPA_vect){
  positiveTimeoutCheck = false;
  digitalWrite( DEBUG_PIN, LOW );
  timerOneCompADisable();
}

/**********************
 * MAIN CODE!!!!!!!
**********************/

void setup(){

  /* Pin config */
  pinMode( INT0_PIN_IN, INPUT );
  pinMode( DEBUG_PIN, OUTPUT);

  /* Pin initialization */
  digitalWrite( DEBUG_PIN, LOW );

  /* Timers configuration */
  //prescaler is 8192 so one tick is ~1 ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

  /* Interrupts initialization */
  bitSet( GIMSK, PCIE );
  bitSet( PCMSK, PCINT0 );
}

/* function resetting flags */
void resetFlags( void ){
   positiveFlag  = false;
   fallingEdge   = false;
   risingEdge    = false;
   positiveTimeoutCheck  = false;
}

int main(){
  cli();
  setup();

  /* Variables initialization */
  lastState = digitalRead( INT0_PIN_IN );
  resetFlags();
  sei();

  while(1){
      /* State machine */

      //if nothing is going on and rising edge is detected
      //reset everything and ignite positive flag
      if( risingEdge ){
        cli();
        resetFlags();
        positiveFlag = true;
        sei();
      } // if

      //INT0 is high, initiate positive timeout check
      else if( positiveFlag && !positiveTimeoutCheck ){
        cli();
        resetFlags();
        timerOneCompAInit( POS_TIMEOUT );
        positiveTimeoutCheck = true;
        digitalWrite( DEBUG_PIN, HIGH );
        TCNT1 = 0;
        sei();
      } //else if

  } //while

  return 0;
}

```

# Answer
Thank you guys! All I had to do is disable TIMER1, reset it, set COMPA, reset OCF1A ("bitSet(TIFR,OCF1A)") and set prescaler before `sei();`.

Here is my final, working code:

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

//Watch out! do not use the reset pin (PB5)!

#define INT0_PIN_IN     0
#define INT0_PIN_OUT    4
#define STATUS_PIN      1
#define DEBUG_PIN       3
#define POS_TIMEOUT     70

#define PRE_1     0
#define PRE_2     1
#define PRE_4     2
#define PRE_8     3
#define PRE_16    4
#define PRE_32    5
#define PRE_64    6
#define PRE_128   7
#define PRE_256   8
#define PRE_512   9
#define PRE_1024  10
#define PRE_2048  11
#define PRE_4096  12
#define PRE_8192  13
#define PRE_16384 14

/*******MONITORING*VARIABLES*VOLATILES**************/
/* variable keeping last state of INT0 input */
volatile bool lastState = false;

/*************STATUS FLAGS**************************/
/* flags used for movement detection */
/* all flags are initiated as false */

volatile bool positiveFlag  = false;
volatile bool fallingEdge   = false;
volatile bool risingEdge    = false;
volatile bool positiveTimeoutCheck  = false;
volatile bool impulseTimeoutCheck = false;
/*************UTILS*********************************/
void timerOneCompADisable( void ){
  bitClear(TIMSK, OCIE1A);
}

void timerOneCompAInit( uint8_t compValue  ){
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

void timerOneDisable(){
  TCCR1 |= (0<<CS13)|(0<<CS12)|(0<<CS11)|(0<<CS10);
}

/******************
 * INTERRUPTS!!!
******************/

/*
 * This interrupt is called every time PCINT0 input state changes
*/
ISR(PCINT0_vect){
  bool readPin = digitalRead( INT0_PIN_IN );

  //falling edge
  if( lastState && lastState != readPin ){
    fallingEdge = true;
    lastState = false;
  }
  //rising edge
  else if( !lastState && lastState != readPin ){
    risingEdge = true;
    lastState = true;
  }
}

//TIMER 1 COMPARE match A
ISR(TIMER1_COMPA_vect){
  positiveTimeoutCheck = false;
  digitalWrite( DEBUG_PIN, LOW );
  TCNT1=0;
  timerOneCompADisable();
}

/**********************
 * MAIN CODE!!!!!!!
**********************/

void setup(){

  /* Pin config */
  pinMode( INT0_PIN_IN, INPUT );
  pinMode( DEBUG_PIN, OUTPUT);

  /* Pin initialization */
  digitalWrite( DEBUG_PIN, LOW );

  /* Timers configuration */
  //prescaler is 8192 so one tick is ~1 ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

  /* Interrupts initialization */
  bitSet( GIMSK, PCIE );
  bitSet( PCMSK, PCINT0 );
}

/* function resetting flags */
void resetFlags( void ){
   positiveFlag  = false;
   fallingEdge   = false;
   risingEdge    = false;
   positiveTimeoutCheck  = false;
}

int main(){
  cli();
  setup();

  /* Variables initialization */
  lastState = digitalRead( INT0_PIN_IN );
  resetFlags();
  sei();

  while(1){
      /* State machine */

      //if nothing is going on and rising edge is detected
      //reset everything and ignite positive flag
      if( risingEdge ){
        cli();
        resetFlags();
        positiveFlag = true;
        sei();
      } // if

      //INT0 is high, initiate positive timeout check
      else if( positiveFlag && !positiveTimeoutCheck ){
        cli();
        resetFlags();
        timerOneDisable();
        timerOneCompAInit( POS_TIMEOUT );
        positiveTimeoutCheck = true;
        digitalWrite( DEBUG_PIN, HIGH );
        bitSet(TIFR,OCF1A);
        TCNT1 = 0;
        TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
        sei();
      } //else if

  } //while

  return 0;
}

```
> 2 votes

# Answer
You should move the line `TCNT1 = 0;` from `loop()` into `timerOneCompAInit()` function:

```
void timerOneCompAInit( uint8_t compValue  ){
  TCNT1 = 0;
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

```

Otherwise, during the timelapse between `OCR1A = compValue;` and `TCNT1 = 0;`, it is **highly possible** that `TCNT1` reaches `OCR1A` and thus sets the `OCF1A` flag in `TIFR`, which will generate an interrupt and call `ISR(TIMER1_COMPA_vect)` immediately after `sei()` is called in `loop()`.

The fact is Timer1 is always running since it has been enabled at `setup()`, hence `TCNT1` is continuously changing from 0 to 255 and back to 0.

Hence in your current code, at the time you execute `OCR1A = compValue;`, `TCNT1` may have any value between `0` and `255`, if its value is `>50` (`POS_TIMEOUT`), then an interrupt will be generated.

Roughly the probability for this interrupt to happen is at least 80% (i.e. `(255-50)/255`).
> 1 votes

# Answer
the code is a little too long for me to go through but sounds like this is a one-shot compare.

With that, you should turn off the timer1, clear the timer1 compa flag, set the compare match point forward (COMPA = target count if TCNT1 is reset, or COMPA = TCNT1 + target if TCNT1 is NOT reset), enable the timer1 compa interrupt, and start the timer1. All of that in the PCNT1 interrupt (where timer1 is armed).

Some of the actions can be structured in the timer1 initialization routine, or even after timer1 compa isr if you want to improve the code responsiveness.

Otherwise, your timer1 keeps running and once the counter passes COMPA, the flag is set, regardless of if the interrupt is set or not.
> 1 votes

---
Tags: interrupt, timers, attiny
---


# Question
Title: Molex power with USB serial Communication from the same PSU
Before I begin I just want to apologize for my mediocre understanding of things electrical and arduino. I know there are a lot of topics similar to this but I'm confused by the term external PSU

**Question**

Do I need to worry about any sort of issues (loops/grounding) if I use the molex connector to supply power to my arduino uno ***and*** continue to use the USB for serial communication at the same time? The source of both would be from the same PSU in my PC.

From what I understand the Uno when powered by DC should not exceed 7.5V for maximum efficiency. So it looks like the 5V from the molex would be more suitable than the 12V and sufficient for my needs of roughly 3.6A (60mA per LED * 60). Since USB can only supply a maximum of 2.0A and Molex appears to supply up to 5.0A from what I've read.

And I would connect it like so 5V molex powered Uno?

**Background**

Currently I'm using the arduino uno to power a single 5V strip of 30 rgb WS2812B leds, which works great when powered through the USB port, but since I need an additional strip of 30 leds and USB alone cannot supply enough amperage to power both I need a better source of current. I also needed the cleanest solution possible as it's for a PC tower and I don't want to use an external power source.

Edit - **Alternative solution**

If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino

# Answer
> 2 votes
Two important things first:

1. **The Uno 5 V pin and power bus must never be supplied more than 5.5 V** or the MCU may die. The DC power input jack (the barrel jack) and the `Vin` pin, which are connected together, are not directly connected this bus, which is why you can supply higher voltages to that (see below).
2. **You can not simultaneously supply power via both the USB cable and a power supply to the `5V` pin/5 V bus** because that would directly connect the two power supplies. That's a very bad thing, and probably not just for the Uno. (But there is a trick you can use here to still connect USB data when you are supplying power to `5V`; see below.)

Now on to the details.

You can safely connect `Vin` (the pin or the barrel jack; they are directly connected) and USB at the same time because there's a switch (`T1` on the schematic) on the board that will disconnect the USB power line from the Arduino 5V bus if more than 3.3 V is being supplied to `Vin`.

However, `Vin` goes through a regulator which, while it has the advantage of safely handling voltages much higher than 5 V, also causes some voltage drop, so you need to supply it with a minimum of 7 V. (6 V might work if there's very little power draw; 5 V almost certainly will not.) The maximum voltage you should supply is 20 V, but it's recommended that you stick to 12 V or less, since higher voltages mean that the regulator can get rather hot.

Unfortunately for you, this doesn't really help with your problem. While you could take the 12 V power off the molex connector, supply it to `Vin` and run the Arduino itself quite happily with the USB cable also connected, the regulator on `Vin` is rated for only 1 A, which is considerably less than you need for the entire system.

There are ways to have some parts of the system powered by one power supply and other parts powered by a separate power supply, but they're not trivial (and also beyond my expertise at the moment :-)).

Probably the easiest solution is to connect the 5 V output from the molex connector to your system power bus, which would be supplying both the `5V` pin on the Arduino and your external components, and then build a custom USB cable with only the `D+` and `D-` pins connected, dropping the power and ground pins. (You don't need the ground pin because the USB data signal is actually a differential signal: the difference or similarity in the voltage between D+ and D- pins is what determines whether the signal is a `1` or a `0`.)

By the way, just to make sure, you do have some separate switching for all those LEDs, right? You're not trying to provide all their power via the Arduino digital outputs? Because, as per section 32.1 of the ATmega328P datasheet, while you are allowed to sink up to 40 mA from any individual data pin, you cannot sink more than 200 mA in total from the chip.

# Answer
> 0 votes
If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino

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