title: NEO 6M GPS speed

text:
# Question
Title: NEO 6M GPS speed
I am doing a project using a NEO 6M GPS with my Arduino LilyPad. I programmed it already, and it's working well except of the speed. I get stuck on fixing this. I wonder why the value is never getting zero although I am not moving to my place.

I need any suggestions/help that would make the speed working accurately.

Thanks.

Here is the code I used:

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

SoftwareSerial mySerial(4, 3); // RX, TX
TinyGPS gps;

void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(1000);
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
}

void loop() {
  bool newdata = false;
  unsigned long start = millis();
  // Every 5 seconds we print an update
  while (millis() - start < 5000) {
    if (mySerial.available()) {
      char c = mySerial.read();
      if (gps.encode(c)) {
        newdata = true;
      }
    }
  }
  if (newdata) {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump(gps);
    Serial.println("-------------");
    Serial.println();
  }
}

void gpsdump(TinyGPS &gps) {
  long lat, lon;
  float flat, flon;
  unsigned long age, date, time, chars;
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned short sentences, failed;
  gps.get_position(&lat, &lon, &age);
  Serial.print("Lat/Long(10^-5 deg): ");
  Serial.print(lat);
  Serial.print(", ");
  Serial.print(lon);
  Serial.print(" Fix age: ");
  Serial.print(age);
  Serial.println("ms.");
  // On Arduino, GPS characters may be lost during lengthy Serial.print()
  // On Teensy, Serial prints to USB, which has large output buffering and
  // runs very fast, so it's not necessary to worry about missing 4800 baud GPS characters.
  gps.f_get_position(&flat, &flon, &age);
  Serial.print("Lat/Long(float): ");
  printFloat(flat, 5);
  Serial.print(", ");
  printFloat(flon, 5);
  Serial.print(" Fix age: ");
  Serial.print(age);
  Serial.println("ms.");
  gps.get_datetime(&date, &time, &age);
  Serial.print("Date(ddmmyy): ");
  Serial.print(date);
  Serial.print(" Time(hhmmsscc): ");
  Serial.print(time);
  Serial.print(" Fix age: ");
  Serial.print(age);
  Serial.println("ms.");
  Serial.print("Alt(cm): ");
  Serial.print(gps.altitude());
  Serial.print(" Course(10^-2 deg): ");
  Serial.print(gps.course());
  Serial.print(" Speed(10^-2 knots): ");
  Serial.println(gps.speed());
  Serial.print("Alt(float): ");
  printFloat(gps.f_altitude());
  Serial.print(" Course(float): ");
  printFloat(gps.f_course());
  Serial.println();
  Serial.print("Speed(knots): ");
  printFloat(gps.f_speed_knots());
  Serial.print(" (mph): ");
  printFloat(gps.f_speed_mph());
  Serial.print(" (mps): ");
  printFloat(gps.f_speed_mps());
  Serial.print(" (kmph): ");
  printFloat(gps.f_speed_kmph());
  Serial.println();
  gps.stats(&chars, &sentences, &failed);
  Serial.print("Stats: characters: ");
  Serial.print(chars);
  Serial.print(" sentences: ");
  Serial.print(sentences);
  Serial.print(" failed checksum: ");
  Serial.println(failed);
}

void printFloat(double number, int digits) {
  // Handle negative numbers
  if (number < 0.0) {
    Serial.print('-');
    number = -number;
  }
  // Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (uint8_t i=0; i<digits; ++i)
    rounding /= 10.0;
  number += rounding;
  // Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;
  Serial.print(int_part);
  // Print the decimal point, but only if there are digits beyond
  if (digits > 0)
    Serial.print(".");
  // Extract digits from the remainder one at a time
  while (digits-- > 0) {
    remainder *= 10.0;
    int toPrint = int(remainder);
    Serial.print(toPrint);
    remainder -= toPrint;
  }
}

```

NOTE: The altitude and longitude were already working. It's the speed that I want to fix. I want to see it as "ZERO SPEED" when at a steady state. How can I fix this? Please help me. Thanks!

# Answer
The speed value is correct, like TisteAndi said. Your GPS location "wanders" around the same way. You can simply ignore small speed values.

One problem you may not be aware of yet: the printing isn't really coordinated with the GPS updates. Sometimes that doesn't matter, but if you want your speed to update every second, you'll need to synchronize the two. And as noted in the code, you can actually lose GPS data if you print too much.

I wrote a GPS library, called NeoGPS, to fix some of these problems. They are described in the Troubleshooting section of the online documentation.

Also, `SoftwareSerial` is very inefficient. I maintain a more-efficient alternative, NeoSWSerial. As you add more features to your GPS program, the efficiency will become important.

Here is your program, modified to use NeoGPS and NeoSWSerial, and it uses TisteAndi's suggestion to set the speed to zero:

```
#include <Arduino.h>
#include "NMEAGPS.h"
#include <NeoSWSerial.h>

NeoSWSerial mySerial(4, 3); // RX, TX//

NMEAGPS     gps;
gps_fix     fix;
uint8_t     GPSupdates = 0;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  delay(1000);

  Serial.print("Sizeof(gps) = "); Serial.println(sizeof(gps));
  Serial.println();
}

void loop() // run over and over
{
  while (gps.available( mySerial )) {
    fix = gps.read();

    if (fix.valid.speed && (fix.speed_mkn() < 1000)) {
      // Too slow, zero out the speed
      fix.spd.whole = 0;
      fix.spd.frac  = 0;
    }

    GPSupdates++;
  }

  // Print once every 5 seconds
  if (GPSupdates >= 5) {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump();
    Serial.println("-------------");
    Serial.println();

    GPSupdates = 0;
  }

}

void gpsdump()
{
  Serial.print("Lat/Long(10^-7 deg): ");
  if (fix.valid.location) {
    Serial.print(fix.lat);
    Serial.print(", ");
    Serial.print(fix.lon);
  }
  Serial.println();

  // GPS characters may be lost during lengthy Serial.print()
  //   See the NeoGPS Troubleshooting section.

  Serial.print("Lat/Long(float): ");
  if (fix.valid.location) {
    Serial.print(fix.latitude(), 5);
    Serial.print(", ");
    Serial.print(fix.longitude(), 5);
  }
  Serial.println();

  Serial.print("Date/Time: ");
  if (fix.valid.date | fix.valid.time)
    Serial << fix.dateTime;
  Serial.println();

  //*
  Serial.print("Date: ");
  if (fix.valid.date) {
    Serial.print(fix.dateTime.month);
    Serial.print("/");
    Serial.print(fix.dateTime.date);
    Serial.print("/");
    Serial.print(fix.dateTime.year);
  }

  if (fix.valid.date | fix.valid.time) {
    Serial.print("  Time: ");
    Serial.print(fix.dateTime.hours);
    Serial.print(":");
    Serial.print(fix.dateTime.minutes);
    Serial.print(":");
    Serial.print(fix.dateTime.seconds);
    Serial.print(".");
    Serial.print(fix.dateTime_cs);
  }
  Serial.println();
  //*/

  Serial.print("Alt(cm): ");
  if (fix.valid.altitude)
    Serial.print(fix.altitude_cm());

  Serial.print(" Course(10^-2 deg): ");
  if (fix.valid.heading)
    Serial.print(fix.heading_cd());

  Serial.print(" Speed(10^-3 knots): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_mkn());
  Serial.println();

  Serial.print("Alt(float): ");
  if (fix.valid.altitude)
    Serial.print(fix.altitude());

  Serial.print(" Course(float): ");
  if (fix.valid.heading)
    Serial.print(fix.heading());
  Serial.println();

  Serial.print("Speed(knots): ");
  if (fix.valid.speed)
    Serial.print(fix.speed());
  Serial.print(" (mph): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_mph());
  Serial.print(" (mps): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_kph()*3600.0/1000.0);
  Serial.print(" (kmph): ");
  if (fix.valid.speed)
    Serial.print(fix.speed_kph());
  Serial.println();

  Serial.print("Stats: characters: ");
  Serial.print(gps.statistics.chars);
  Serial.print(" sentences: ");
  Serial.print(gps.statistics.ok);
  Serial.print(" failed checksum: ");
  Serial.println(gps.statistics.crc_errors);
}

```

(Notice the increased accuracy of the integer lat/lon! And you don't need `printFloat`.)

If you'd like to try it, be sure to follow the NeoGPS Installation instructions. NeoSWSerial is installed like most Arduino libraries.
> 6 votes

# Answer
Usually, this should be solved by just going outside to get the first fix point. If you still don't manage it, try the U-center software to make sure your GPS is properly working.
> 1 votes

---
Tags: arduino-uno, arduino-mega, gps, tinygps
---


title: Variable scope error

text:
# Question
Title: Variable scope error
guys.

I'm writing here because I cannot find an obvious error, so I'm stuck. Could you please help me?

Here's the code:

```
int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

int newArrayLength = 0;

void setup() {

    Serial.begin(9600);

}

void loop() {

  String dir = "AAA";

  if (dir == "AAA"){

      //Copy existing array to the new one...
      newArrayLength = arrayAAALength;              //Get the size of source array
      int newArray[newArrayLength];                 //Make the new array of the same size
      memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

      /*
      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //Here everything works just fine...
          Serial.print("   ");
      }
       */
  }

  for (int i = 0; i < newArrayLength; i++){
      Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope
      Serial.print("   ");
  }

  Serial.println();
  Serial.println();

}

```

What I'm trying to do is to copy the array to a new one, but depending on the circumstances I need to take different source arrays (AAA or BBB).

The problem is in checking the values of an newly crreated array:

```
'newArray' was not declared in this scope

```

if I try to check its valus outside of if statment.

It seems my stupid mistake, but I can't find it.

# Answer
After a careful study of C/C++ documentation, I finally managed to use pointers in Arduino :)

So, the final code became like this:

```
int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

//Create a pointer, which will point to any of your arrays of your choice
int *newArray;

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

void setup() {

    Serial.begin(9600);

    //Uses the address of arrayAAA (i.e. inherits the content of arrayAAA).
    //&: points to address of a chosen array.
    //[0]: is a must to grab all values!
    newArray = &arrayAAA[0];

    Serial.print("arrayAAA:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(arrayAAA[i]);
    }
    Serial.println();

    Serial.print("newArray:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(newArray[i]);
    }
    Serial.println();
}

void loop(){
    //Left empty
}

```

And it works perfectly, just what I expected!
> 1 votes

# Answer
The clue is in the indenting:

```
  if (dir == "AAA"){

      //Copy existing array to the new one...
      newArrayLength = arrayAAALength;              //Get the size of source array
      int newArray[newArrayLength];                 //Make the new array of the same size <<<==== DEFINED IN THE SCOPE OF "IF"
      memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

      /*
      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //Here everything works just fine...
          Serial.print("   ");
      }
       */
  }

  for (int i = 0; i < newArrayLength; i++){
      Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope <<=== USED IN THE SCOPE OF "FOR"
      Serial.print("   ");
  }

```

As you can see by the indenting the definition of `newArray` is in a different block of code which you come right out of before you use it.

You must define `newArray` at a scope that is *outside* where you use it.

From that code you don't actually need to copy the contents of one array into another - you can just *point* to the array you want to use with a pointer. Alternatively, if you do need to clone the array contents (for some other purpose we don't know of) then you should pre-create an array that is big enough to hold *either* of your other arrays.

```
int newArray[max(arrayAAALength, arrayBBBLength)];

```
> 0 votes

# Answer
*Made corrections per @Majenko's comment*

The following will **not** work on real Arduinos, but it did work for me on the ESP8266 and the Teensy3, which are what I use mostly, and the only ones I tested the code for: https://github.com/jayeye/jardino/tree/master/esp8266/ase25017

```
#include <vector>
  ...
  size_t vector_size = 42;
  std::vector<int> foo(vector_size);  // foo is a vector of 42 integers

```

**Another correction:** Exceptions do not work even on the aforementioned platforms, so do not access the vector with `.at(n)`

If you *must* have an array, use a unique\_ptr with an array allocator:

```
#include <memory>
  ...
  size_t vector_size = 42;
  std::unique_ptr<int[]> arr(new int[vector_size]);

```

When `arr` goes out of scope, the array will be automatically freed.

You can always use malloc(), but you'll have to remember to free() it, and that's always a source of bugs.
> -1 votes

---
Tags: arduino-due
---


title: Why connect arduino with Rasberry pi?

text:
# Question
Title: Why connect arduino with Rasberry pi?
I have a question about connecting a Arduino with Raspberry Pi.

What is the benefit of connecting the two?

# Answer
Interfacing hardware is easier with the Arduino: more available I/O pins capable of sourcing and sinking more current, 5 V I/O, analog inputs, very predictable timings, etc. The Raspberry, on the other hand, is a real computer with a real OS, has **a lot** more computing power and memory, has Internet connectivity, can easily run “standard” web servers like Apache or nginx... or mostly any Linux software for that matter.

Some projects can benefit from using both. E.g. if you want to make a web interface for some low-level hardware sensors.
> 8 votes

# Answer
**Why add an Raspberry Pi to an Arduino?**

There are some things that simply are beyond the possibilities of Arduino. The first thing that would cross my mind is video processing, HDMI output, decent sound etc.

A Raspberry Pi can be used to add some features to your project aswell. If you make an Arduino controlled robotic arm, you could add an "user interface" to it, using a Raspberry Pi.

**Why add an Arduino to an Raspberry Pi?**

Some may argue that the Raspberry Pi is much more capable as an Arduino, in every form. Though, the strengths of Arduino are:

* Ease of use. (For GPIO on Raspberry Pi you'll likely need to install something, to make it work with your favorite programming language.)
* Real time / deterministic timing, this is one of the best things of Arduino. Given that an Arduino has no "operating system" that can induce random (tiny) delays in your program (other than the millis()/micros() interrupts).

**Why do any of this? You could choose an Arduino OR Raspberry Pi**

One thing you might not think about is, that by joining an Arduino and a Raspberry Pi, you're joining two important parts of Embedded Systems. Which you can learn a lot from.

Microcontrollers and Single-board computers. This really has a good educational effect. Since you'll not limit yourself to one device or "way of thinking".

Moreover, the interfacing between two devices is often important and will bring some extra problems. (And solving them gives extra knowledge/experience)
> 7 votes

# Answer
I prefer to use arduino type boards as data acquisition units then transfer the data to an actual computer (or raspberry pi) in most of my projects. Arduinos are, in my experience, much more tolerant of fault and accidental crossed circuits than the R pi. Thus is especially true of the ruggedized or industrial arduino versions.
> 3 votes

---
Tags: arduino-uno, raspberrypi
---


title: SparkFun EL Sequencer does not work

text:
# Question
Title: SparkFun EL Sequencer does not work
I have connected to EL wire, 12v EL Inverter to SparkFun EL Sequencer but it does not work (no battery is connected). The connections are the same like in Hookup Guide (https://cdn.sparkfun.com/assets/learn\_tutorials/3/6/9/ELSequencerHookUp\_bb.png). Furthermore, there is no light indicating that it works but I hear a noise/whistle from the Inverter.

Do I have to program the EL Sequencer or does it automatically turn the EL wire on?

# Answer
> 1 votes
It looks like Sparkfun probably only put the bootloader on the board. The tutorial is written in a way that suggests the need to flash the board.

Also the board does not imediatly work with the 12V inverter. If you have the battery you should attach it and see the `PWR` LED turn on.

*The inverter only provides voltage to the EL wire* and **not the Microcontroller**, power to the microcontroller is provided by way of a regulator(`U2`), ***not*** *the LM317* the last quote from the one comment shows how you can connect to the 12V inverter.

What you should do instead of having to go the route of all the wiring is to connect both the battery to `BATT IN` and the inverter, but ensuring that the microcontroller is programmed before hand.

> Arduino Code
>
> Once you have all of your hardware hooked up properly, it’s time to program your Sequencer to run the EL Wire display as you want. You will need to download the Arduino code in order to follow along with the example.
>
> You can also download the most up-to-date code from the EL Sequencer GitHub repository.
>
> We will be working with the “SparkFun\_EL\_Example.ino” example. If you need a review on how to upload Arduino code to your board or using the Arduino IDE, please check our tutorial here. Also, if you are unsure about installing the FTDI drivers, please check out this tutorial.

Also from one of the Tech support notes:

> Using 12V to Power Both the EL Inverter & Microcontroller
>
> If you are using a 12V wall adapter to power the 12V Inverter, you would still need to provide power to the microcontroller side. One solution with your 12V wall adapter to provide power to the 12V inverter and Atmega328P is to get a barrel jack adapter to 2 pin JST adapter \[ https://www.sparkfun.com/products/8734 \], thus connecting the 12V wall adapter to the “BATT IN.” This is assuming that your wall adapter is using a center positive barrel jack.
>
> From there you can connect the 2 pin JST labeled “DC Out” to the 12V inverter’s input voltage. To connect, I recommend using the male DC barrel jack adapter \[ https://www.sparkfun.com/products/10287 \] and a 2pin JSt jumper wire \[ https://www.sparkfun.com/products/8670 or https://www.sparkfun.com/products/8671 \]. You will need to wire strip the cable to be able to connect it to the screw terminals.
>
> Lastly, you would need to add a solder jumper to SJ1 so that you bypass the voltage regulator between your external power (“BATT IN”) to provide power to the inverter’s “DC OUT”. This will provide power to your 12V inverter’s input.

**Warning: if SJ1 is closed, inverter will see 5V with FTDI plugged in and switch at USB**

---
Tags: wires
---


# Question
Title: RFID/NFC Tag get data from wordpress MySQL
I have a local workshop for students to teach them 3D printing/woodworking
I want to know if its possible to create **RFID/NFC tags using wordpress data from MySQL or HTTP/HTTPS**.

***Web Scenario*** :

I have a wordpress website where I setup a gamefication plugin.
Each time a student takes a quiz/posts on forum he gets a "x" number of points that are accumulated on his profile.

I want to know if I can get a RFID/NFC tag to get that number of points.
Each member has a RFID/NFC tag card and with that card he can get access to different things around the workshop .

***Workshop Scenario :***

**For each tool there will be a lock , RFID/NFC reader and a LCD display screen.**

**When a student want to access that tool he needs a number of points on the wordpress gamefication script that are transfered to the RFID/NFC card.**

If he has the needed points a text on the LCD screen will appear with something like " **You have access to this tool**" and the tool will be unlocked .

Else if the user doesn't meet the needed points the LCD screen will show "**You don't have the needed points for this tool, please visit \[URL\] to get more info**" and the tool will stay locked.

---

> **I need only info if this is possible, not the way to do it.**
>
> ***\[ In case you are kind to hand me some guides on where to start to will be great! \]***

---

Thanks and waiting to see if this is possible!

# Answer
> 2 votes
From what I can tell it's absolutely possible but will take some considerable development time and around $30-$70 of hardware per NFC terminal. Please note I would strongly not recommend this as a first project as it has a lot of individual components that all have to work together flawlessly and each is different. Properly done this will be complex software and hardware wise although more so from the hardware side of things.

Hardware wise you need/terminal:

* **LCD display** (I would recommend segmented for simplicity and cost)
* **Wifi or ethernet shield/breakout** and ethernet cable if the board is not wifi compatible
* **Arduino** (MKR1000 has wifi built in), Feather (Adafruit's boards that are frequently Arduino software compatible and have many shields available and guides written on how to use them), or cheap Arduino knock off (preferably not this option as giving money to arduino.cc, Adafruit, or other designers is important if we want new boards regularly)
* **NFC breakout** or shield (Google/DuckDuckGo/Bing RFID-RC52 for an economical option, they're ~$4 on Ebay)
* **Power supply** corresponding to the requirements of the chosen board + shields + breakouts
* **NFC tags**
* **Lock** able to be unlocked by a servo. If you expect security in absence of supervising shop manager (aka just to be safe, assume dishonesty in people using the shop) from this system, the locks need to be better than a Masterlock as those are insecure to even simple soda can shims. The rotary masterlocks can also be reduced to 100 possible combinations and then the combo can be brute forced easily from there so if you get a rotary based lock system make sure the assembly covering the dial is not easily removed.
* **Servo or stepper** powerful enough to actuate locks
* **Servo or stepper driver breakout board**

Then you'd just want to have the public key (note I don't mean a "public key" in the general cryptography sense but on that subject, you do want the key encrypted) to the user stored on the NFC tag and then use the arduinos+electronics to read the tags and see point values. User data from wordpress could be downloaded periodically to the boards so the individual checks don't use network resources and the system works offline.

---
Tags: arduino-uno, programming, lcd, rfid, networking
---


title: MG2639 CELL AND GPS LIBRARIES

text:
# Question
Title: MG2639 CELL AND GPS LIBRARIES
I'm using a MG2639 Cell Module with the SMS and GPS functionality. I have a sketch that sends through SMS the location of the arduino UNO.

This is my code:

```
#include <SoftwareSerial.h> //to communicate with mg2639 cell module.
#include <SFE_MG2639_CellShield.h> //basic librarie of the module.
#include <AltSoftSerial.h>   //to communicate with the GPS module
#include <TinyGPS++.h>    //to acquire the NMEA codes.

TinyGPSPlus gps;

AltSoftSerial ALTS(9, 8);
char celprim[11]="4423337388";
uint8_t GPStatus=0;
long temp=0;

 void configurado()
{
  sms.start(celprim);
  sms.print("Transmitiendo GPS Tracking....");
  sms.send();
  delay (6000);
}

     void GPSTracking()
{
   do
      {
        if (ALTS.available()>0)
          if (gps.encode(ALTS.read()))
      {
        if (gps.date.isValid() && gps.location.isValid() && gps.time.isValid()){
          sms.start(celprim);
          sms.print("Fecha/Hora/Ubicacion: ");
          sms.print(gps.date.day());
          sms.print("-");
          sms.print (gps.date.month());
          sms.print("-");
          sms.print(gps.date.year());
          sms.print(" ");
          if ((gps.time.hour()-5) < 10) sms.print("0");
          sms.print(gps.time.hour()-5);
          sms.print(":");
          if (gps.time.minute() < 10) sms.print("0");
          sms.print(gps.time.minute());
          sms.print(":");
          if (gps.time.second() < 10) sms.print("0");
          sms.print(gps.time.second());
    sms.print("https://www.google.com.mx/maps/dir/19.4161748,-99.1664011/");
          sms.print(gps.location.lat(), 6);
          sms.print(",");
          sms.print(gps.location.lng(), 6);
          sms.print("/@");
          sms.print(gps.location.lat(), 6);
          sms.print(",");
          sms.print(gps.location.lng(), 6);
          sms.print(",19z");
          sms.send();
          GPStatus=1;
        }
    }
      if ((millis()-temp) > 30000 && GPStatus==0)
      {
        GPStatus=1;
        sms.start(celprim);
        sms.print("Imposible ubicar equipo, intente mas tarde...");
        sms.send();
      }
    }while (GPStatus ==0);
}

void setup()
{
  delay (5000);
  int beginStatus = cell.begin();
  if (beginStatus <= 0)
  {
     while(1)
      ;
  }
  delay (10000);
  sms.setMode(SMS_TEXT_MODE);   //Se pone al modulo en modo de recepción y envio de sms
  ALTS.begin(115200); // Or whatever rate the GPS uses
  configurado();
}

void loop()
{
  if (GPStatus==0)
  {
    temp = millis();
    GPSTracking();
  }
}

```

Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space? If it's possible, what changes should do in the MG2639 library to make it work? Or what could i do to reduce space.

# Answer
> 1 votes
> Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space?

The question is a little vague.

`AltSoftSerial` only works on pins 8 & 9, so I thought you were asking if you could connect both the cell and the GPS to pins 8 & 9 (using jumper pads on the back of the board), and use one `AltSoftSerial` instance to talk to both devices. If it were possible, this would save RAM (just one instance) and program space (you wouldn't need two link in another software serial class, like `SoftwareSerial`). However, this is not possible. Serial connections are always point-to-point. Although two "things" can listen to one RX line, the TX line cannot be shared by two devices.

If you were asking if you can have two instances of `AltSoftSerial` on two separate pairs of pins (e.g., 2/3 and 8/9), the answer is again "No", because... `AltSoftSerial` only works on pins 8 & 9. Also, the SparkFun library only uses SoftwareSerial to talk to the cell.

> what could i do to reduce space.

Use NeoGPS instead, and use the F macro around double-quoted strings that you print:

```
    sms.print( F("Imposible ubicar equipo, intente mas tarde...") );

```

That will save several hundred bytes of RAM.

Also, you may be sending multiple SMS's per second. It depends on what sentences the GPS emits. As it is, your sketch will send one SMS per sentence (i.e., one for each `encode`). Even if you don't use NeoGPS, look at the example program `NMEAloc.ino` et al for the correct program structure. The Troubleshooting section also contains some tips.

---
Tags: arduino-uno, library, gps
---


title: Hooking up the Arduino to a car's 12v

text:
# Question
Title: Hooking up the Arduino to a car's 12v
I am planning an uno based tachometer for my truck, which doesn't have a tachometer. With nothing in place for me to get a reliable signal, I started looking at other sources to read the rpm from the engine.

It seems to me that an engine should affect the power every time a cylinder fires --the power should spike in some way. So in theory I should be able to hook up to the 12v cigar lighter, count the spikes, and calculate the rpm. It would only need to be accurate within 500 rpm or so.

This is a two part question.

1. How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?
2. How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

# Answer
> How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

First you're going to need to do some investigative work. You're going to need to beg, steel, borrow (or use your own if you have one) an oscilloscope. You can then use that to examine the 12V power coming from the cigarette lighter. Armed with that you can then tell:

1. If there is any power fluctuation from the engine, and
2. What form that fluctuation takes.

If there is any fluctuation it will appear as an AC component imposed on top of the 12V DC voltage. Removing the 12V DC offset is simple enough. All you need to do is pass the power through a *high pass* filter. That's simply a capacitor and a resistor. You need to ensure that the cut-off frequency of the filter is below the lowest frequency you want to measure (idle frequency) yet high enough to cut out the DC component effectively.

Once you have done that you can then clip the waveform using a diode to protect against negative voltage, and a resistor and zenner diode to limit the positive voltage.

For instance, something similar to the following (it's not exact - the source isn't creating spikes, but an offset low duty cycle PWM, which is kind of similar for demonstration purposes):

The first point measured is the 12V signal with big high voltage spikes. Next the power has been high-pass filtered by the RC network and the lower portion of the waveform clipped by the reverse biased diode. Following that the zenner diode clips the upper portion of the waveform to within safe limits for the Arduino. The 100Ω resistor with the zenner is there to limit the current through the zenner.

Don't take any of those values as gospel, since the signal I am filtering there is not your signal. You need to know your signal first before you can work out exactly how it should be filtered, but that gives you the basic idea of how it can be done.

> How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

Connect the filtered and clipped signal to an interrupt input on the Arduino. Count the pulses within a given time period (1 second, 5 seconds, whatever you choose) and multiply up for number of pulses in a minute. Don't forget to then divide by 4 for a 4-cylinder engine, since I would expect you would see 4 sparks per revolution. How you then gather the data is up to you. It might be simplest to add an SD card shield to your Arduino and record the data onto an SD card. You can then place that card into your computer to process the data at your leisure.

The best way to power your Arduino is, of course, direct from the truck's power. The safest way, because of all those nasty spikes in the power, is to use car USB phone charger adapter. Plug that into the USB of the Arduino and all should be nice and happy.
> 1 votes

---
Tags: voltage-protection
---


# Question
Title: Can I connect a remote control relay to a arduino uno board by disabling the remote control in the relay?
I was making a home automation system by making some of the appliances in the home like fans and lights voice activated. But by mistake I bought a remote controlled relay in place of a normal relay from a shop and return does not seems possible. So I want to know if I will be able to use that remote controlled relay in this project?

# Answer
I don't like to work with mains, so I use those outlets and connect a 433MHz transmitter to the arduino to activate the outlets.

You'd have to check the frequency of the unit, and see if anyone have decoded the transmitted data package.

If that doesn't float you're boat, you could open up the unit, and remove/desolder the relay. Add a transistor, and flyback diode and you're done. Just be careful with mains power.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: 74HC595N shift register with separate power supply
I have wired up a 74HC595N with an Uno, and the standard 8 LEDs and resistors, per the usual youtube "shift register tutorial" and written a sketch that works. For example, I wrote a routine to walk from values 0 through 255 and light up the LEDs as a hex number. So my wiring and code are correct.

As an experiment, I tried disconnecting the pin on my breadboard's power rail that goes to the Arduino 5V, and the pin that goes to Arduino ground, and instead plugged in a breakout (if that's the right word) that plugs into the breadboard and provides 5V on the power rail when a 9V battery is plugged into it. (It's been checked with a multimeter, it's just under 5V.) The only pins still going to the Arduino are for DS, SHCP and STCP.

Things sort of work, but not really. It seems clear to me that the shift register keeps getting reset. (All of the LEDs briefly light back up in each iteration as I'm running my hex number display routine.) All of the other wiring remains the same; specifically OE-bar is still connected to ground on the power rail. But it still seems to reset.

Can someone explain why the shift register keeps resetting? Also, am I doing anything that might burn up the Arduino and/or shift register?

# Answer
All ground connections except those which are explicitly isolated must be connected together in order to provide a common voltage reference for the circuit. Any breaks in the ground connection can result in gross misbehavior such as what you are experiencing.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Why do I get "invalid operands of types 'const char*'" error?
I am making an Arduino alarm. This is the error:

```
exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

```

Here is the code that triggers it:

```
lcd.print("0"+hours+":"+minutes);

```

This code is similar, but worked before:

```
String none="00";
lcd.print(none+":"+none+":"+minutes);

```

I can post the full code if you need it. How can this be fixed?

# Answer
> 7 votes
Your first code took a `String` object, then added other strings (note lowercase) to it - which are characters enclosed in quotes. It is legal to add strings to `String` objects.

Your new code doesn't have any `String` objects at all - and you're not allowed to add strings to strings (both lowercase).

It will work if you change your new code to:

`lcd.print(String("0")+hours+":"+minutes);`

That turns the original string `"0"` into a `String` object, and then adds more strings to it.

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


# Question
Title: Why does my lcd screen work fine and then display random characters?
It works as expected for a few seconds and then random letters appear on the second row. The wiring and the programming should be correct. I wired it according to an Arduino Starter Kit Book and coded it myself.

Code:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=23;
int minutes=0;
String none="00";
unsigned long timer;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("23:00");
}

void loop() {
timer=millis();
if(timer%600==0){
   minutes++;
  if(minutes==60){
      minutes=0;
      hours++;
      }
   if(hours==24){
      hours=0;
   }
  lcd.clear();
  lcd.setCursor(6, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 1);
  if(minutes<10){
    if(hours<10){
      lcd.print(String("0")+hours+":"+"0"+minutes);
    }
    else{
      lcd.print(hours+String(":")+"0"+minutes);
    }
  }
  else{
    if(hours<10){
       lcd.print(String("0")+hours+":"+minutes);
    }
    else{
       lcd.print(hours+":"+minutes);
    }

  }
  delay(200);
  }
}

```

I was able to narrow down the problem. I was testing what happens when it hits 24 hours so I set hours to 23 in the beginning and made the time 600 ms. Once it hits 10 seconds, the characters appear. If the hour is a 2 digit number, the issue happens. I made the hours 9, and the issue disappeared. What can I do?

# Answer
The problem was that I was adding ":" to the printed string on the lcd without making it a String object. That only occurred if I had double digit hours and minutes.

Incorrect way:

```
lcd.print(hours+":"+minutes);

```

Correct way:

```
lcd.print(hours+String(":")+minutes);

```
> 3 votes

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


# Question
Title: Setting the frequency of a timer interrupt
**The concept:**

Play a sine wave saved as a character array in PROGMEM through an 8-bit DAC connected to the PORTC pins on the Arduino Mega.

**This works:**

```
// File just defines an array and a size

#include "sine440.h"

int i = 0;
void setup() {
  DDRC = B11111111;
}

void loop() {
  PORTC = pgm_read_byte(&sine[i++]);
  if(i >= sine_size){
    i = i - sine_size;
  }

  delayMicroseconds(60);
}

```

The above code produces a sine wave of about 440 Hz, exactly what I wanted. Now, I'd like to move this into an interrupt routine, as follows:

### This doesn't work

```
#include "sine440.h"

int i = 0;
void setup() {
  DDRC = B11111111;
  TCCR5B = (1 << WGM52) | (1 << CS50 );
  OCR5A =  16000000/16000;
  TIMSK5 = (1 << OCIE5A);
}

ISR(TIMER5_COMPA_vect){
  PORTC = pgm_read_byte(&sine[i++]);
  if(i >= sine_size){
    i = i - sine_size;
  }
}

void loop() {

}

```

The above code produces a sine wave of 1721 Hz. I know that this means it's iterating through the array too fast, but I don't know how to change it. In order for it to produce 440 Hz, it needs to be preforming 16,000 iterations per second, which is what I believe  `OCR5A = 16000000/16000;` does. **But** it doesn't appear that changing the value of OCR5A does anything at all. Giving it the max value of 65,535 still produces a 1721 Hz sine wave...

So what am I doing wrong here? How do I change the speed of this timer interrupt?

# Answer
> 3 votes
I second BrettAM's comment. The Arduino IDE sets most of all the timers up for PWM, and I had to comment out a section once to use my own ISR with Timer 3 on a 32u4, because no matter where or how I set it, the CTC interrupt never went. The `WGM50` and `CS51` are set at the start of the Arduino files basically, so that messes with your settings.

You will need go into the Arduino core files. This is `$install_path/arduino-1.x.x/hardware/arduino/avr/cores/arduino/`, and under that directory you need to find file `wiring.c`. This file contains all the setup of the timers for PWM and the `millis()` or `micros()` functions.

Go to line 342. Located there is this:

```
#if defined(TCCR5B) && defined(CS51) && defined(WGM50)

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

#endif

```

Here you can place another `#if defined()` macro around this, resulting in:

```
#if !defined(doNotSetTimer5)

  #if defined(TCCR5B) && defined(CS51) && defined(WGM50)

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

  #endif

#endif

```

Now when you want to use your custom settings, you will put the following at the top of your .ino file:

```
#define doNotSetTimer5
#include <wiring.c>

```

That does not block the Arduino environment from setting up Timer 5 when compiled with other code, but only when you want to use custom settings (changed because of @Gerben's suggestion). When you change these settings you will lose PWM on 3 pins: `44 45 46`. But you will be able to make use of setting your own PWM up or a CTC `ISR()`.

This doesn't mess with anything else and is the easiest way to do it.

---
Tags: arduino-mega, interrupt, timers, sound
---


# Question
Title: How to solve "error 2" from the Arduino MPU6050 accelerometer
I'm new to Arduino and Stack Exchange. I've been building a fitness tracker and am receiving a certain error in the serial monitor. The accelerometer seems the work, but it seems to go to sleep after a while. I'm using an Arduino Uno (for the time being), a Bluetooth HC-05 module and an MPU6050 accelerometer. I connect it to an app, Retroband to monitor the steps taken and calories burnt.

I've wired it like this:

Accelerometer:

```
 SDA-A4
 SCL-A5
 VCC-3.3v
 GND-GND

```

Bluetooth:

```
 VCC-3.3v
 GND-GND
 TX-2
 RX-3

```

Here is the code I'm using:

```
#include <math.h>
#include <Wire.h>
#include <SoftwareSerial.h>

/* Bluetooth */
SoftwareSerial BTSerial(2, 3); //Connect HC-06. Use your (TX, RX) settings

/* time */
#define SENDING_INTERVAL 1000
#define SENSOR_READ_INTERVAL 50
unsigned long prevSensoredTime = 0;
unsigned long curSensoredTime = 0;

/* Data buffer */
#define ACCEL_BUFFER_COUNT 125
byte aAccelBuffer[ACCEL_BUFFER_COUNT];
int iAccelIndex = 2;

/* MPU-6050 sensor */
#define MPU6050_ACCEL_XOUT_H 0x3B // R
#define MPU6050_PWR_MGMT_1 0x6B // R/W
#define MPU6050_PWR_MGMT_2 0x6C // R/W
#define MPU6050_WHO_AM_I 0x75 // R
#define MPU6050_I2C_ADDRESS 0x68

typedef union accel_t_gyro_union {
  struct {
    uint8_t x_accel_h;
    uint8_t x_accel_l;
    uint8_t y_accel_h;
    uint8_t y_accel_l;
    uint8_t z_accel_h;
    uint8_t z_accel_l;
    uint8_t t_h;
    uint8_t t_l;
    uint8_t x_gyro_h;
    uint8_t x_gyro_l;
    uint8_t y_gyro_h;
    uint8_t y_gyro_l;
    uint8_t z_gyro_h;
    uint8_t z_gyro_l;
  } reg;

  struct {
    int x_accel;
    int y_accel;
    int z_accel;
    int temperature;
    int x_gyro;
    int y_gyro;
    int z_gyro;
  } value;
};

void setup() {
  int error;
  uint8_t c;

  Serial.begin(9600);
  Wire.begin();
  BTSerial.begin(9600);  // set the data rate for the BT port

  // default at power-up:
  // Gyro at 250 degrees second
  // Acceleration at 2g
  // Clock source at internal 8MHz
  // The device is in sleep mode.
  //
  error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);
  Serial.print(F("WHO_AM_I : "));
  Serial.print(c,HEX);
  Serial.print(F(", error = "));
  Serial.println(error,DEC);

  // According to the datasheet, the 'sleep' bit
  // should read a '1'. But I read a '0'.
  // That bit has to be cleared, since the sensor
  // is in sleep mode at power-up. Even if the
  // bit reads '0'.
  error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);
  Serial.print(F("PWR_MGMT_2 : "));
  Serial.print(c,HEX);
  Serial.print(F(", error = "));
  Serial.println(error,DEC);

  // Clear the 'sleep' bit to start the sensor.
  MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

  initBuffer();
}

void loop() {
  curSensoredTime = millis();

  // Read from sensor
  if(curSensoredTime - prevSensoredTime > SENSOR_READ_INTERVAL) {
    readFromSensor();  // Read from sensor
    prevSensoredTime = curSensoredTime;

    // Send buffer data to remote
    if(iAccelIndex >= ACCEL_BUFFER_COUNT - 3) {
      sendToRemote();
      initBuffer();
      Serial.println("------------- Send 20 accel data to remote");
    }
  }
}

/**************************************************
 * BT Transaction
 **************************************************/
void sendToRemote() {
  // Write gabage bytes
  BTSerial.write( "accel" );
  // Write accel data
  BTSerial.write( (char*)aAccelBuffer );
  // Flush buffer
  //BTSerial.flush();
}

/**************************************************
 * Read data from sensor and save it
 **************************************************/
void readFromSensor() {
  int error;
  double dT;
  accel_t_gyro_union accel_t_gyro;

  error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) &accel_t_gyro, sizeof(accel_t_gyro));
  if(error != 0) {
    Serial.print(F("Read accel, temp and gyro, error = "));
    Serial.println(error,DEC);
  }

  // Swap all high and low bytes.
  // After this, the registers values are swapped,
  // so the structure name like x_accel_l does no
  // longer contain the lower byte.
  uint8_t swap;
  #define SWAP(x,y) swap = x; x = y; y = swap
  SWAP (accel_t_gyro.reg.x_accel_h, accel_t_gyro.reg.x_accel_l);
  SWAP (accel_t_gyro.reg.y_accel_h, accel_t_gyro.reg.y_accel_l);
  SWAP (accel_t_gyro.reg.z_accel_h, accel_t_gyro.reg.z_accel_l);
  SWAP (accel_t_gyro.reg.t_h, accel_t_gyro.reg.t_l);
  SWAP (accel_t_gyro.reg.x_gyro_h, accel_t_gyro.reg.x_gyro_l);
  SWAP (accel_t_gyro.reg.y_gyro_h, accel_t_gyro.reg.y_gyro_l);
  SWAP (accel_t_gyro.reg.z_gyro_h, accel_t_gyro.reg.z_gyro_l);

  // Print the raw acceleration values
  Serial.print(F("accel x,y,z: "));
  Serial.print(accel_t_gyro.value.x_accel, DEC);
  Serial.print(F(", "));
  Serial.print(accel_t_gyro.value.y_accel, DEC);
  Serial.print(F(", "));
  Serial.print(accel_t_gyro.value.z_accel, DEC);
  Serial.print(F(", at "));
  Serial.print(iAccelIndex);
  Serial.println(F(""));

  if(iAccelIndex < ACCEL_BUFFER_COUNT && iAccelIndex > 1) {
    int tempX = accel_t_gyro.value.x_accel;
    int tempY = accel_t_gyro.value.y_accel;
    int tempZ = accel_t_gyro.value.z_accel;
    /*
    // Check min, max value
    if(tempX > 16380) tempX = 16380;
    if(tempY > 16380) tempY = 16380;
    if(tempZ > 16380) tempZ = 16380;

    if(tempX < -16380) tempX = -16380;
    if(tempY < -16380) tempY = -16380;
    if(tempZ < -16380) tempZ = -16380;

    // We dont use negative value
    tempX += 16380;
    tempY += 16380;
    tempZ += 16380;
    */
    char temp = (char)(tempX >> 8);
    if(temp == 0x00)
      temp = 0x7f;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
    temp = (char)(tempX);
    if(temp == 0x00)
      temp = 0x01;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;

    temp = (char)(tempY >> 8);
    if(temp == 0x00)
      temp = 0x7f;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
    temp = (char)(tempY);
    if(temp == 0x00)
      temp = 0x01;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;

    temp = (char)(tempZ >> 8);
    if(temp == 0x00)
      temp = 0x7f;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
    temp = (char)(tempZ);
    if(temp == 0x00)
      temp = 0x01;
    aAccelBuffer[iAccelIndex] = temp;
    iAccelIndex++;
  }

  // The temperature sensor is -40 to +85 degrees Celsius.
  // It is a signed integer.
  // According to the datasheet:
  // 340 per degrees Celsius, -512 at 35 degrees.
  // At 0 degrees: -512 - (340 * 35) = -12412
//  Serial.print(F("temperature: "));
//  dT = ( (double) accel_t_gyro.value.temperature + 12412.0) / 340.0;
//  Serial.print(dT, 3);
//  Serial.print(F(" degrees Celsius"));
//  Serial.println(F(""));

  // Print the raw gyro values.
//  Serial.print(F("gyro x,y,z : "));
//  Serial.print(accel_t_gyro.value.x_gyro, DEC);
//  Serial.print(F(", "));
//  Serial.print(accel_t_gyro.value.y_gyro, DEC);
//  Serial.print(F(", "));
//  Serial.print(accel_t_gyro.value.z_gyro, DEC);
//  Serial.println(F(""));
}

/**************************************************
 * MPU-6050 Sensor read/write
 **************************************************/
int MPU6050_read(int start, uint8_t *buffer, int size)
{
  int i, n, error;

  Wire.beginTransmission(MPU6050_I2C_ADDRESS);

  n = Wire.write(start);
  if (n != 1)
    return (-10);

  n = Wire.endTransmission(false); // hold the I2C-bus
  if (n != 0)
    return (n);

  // Third parameter is true: relase I2C-bus after data is read.
  Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
  i = 0;
  while(Wire.available() && i<size)
  {
    buffer[i++]=Wire.read();
  }
  if ( i != size)
    return (-11);
  return (0); // return : no error
}

int MPU6050_write(int start, const uint8_t *pData, int size)
{
  int n, error;

  Wire.beginTransmission(MPU6050_I2C_ADDRESS);

  n = Wire.write(start); // write the start address
  if (n != 1)
    return (-20);

  n = Wire.write(pData, size); // write data bytes
  if (n != size)
    return (-21);

  error = Wire.endTransmission(true); // release the I2C-bus
  if (error != 0)
    return (error);
  return (0); // return : no error
}

int MPU6050_write_reg(int reg, uint8_t data)
{
  int error;
  error = MPU6050_write(reg, &data, 1);
  return (error);
}

/**************************************************
 * Utilities
 **************************************************/
void initBuffer() {
  iAccelIndex = 2;
  for(int i=iAccelIndex; i<ACCEL_BUFFER_COUNT; i++) {
    aAccelBuffer[i] = 0x00;
  }
  aAccelBuffer[0] = 0xfe;
  aAccelBuffer[1] = 0xfd;
  aAccelBuffer[122] = 0xfd;
  aAccelBuffer[123] = 0xfe;
  aAccelBuffer[124] = 0x00;
}

```

This is the error I got in serial monitor:

```
    WHO_AM_I : 0, error = 2
PWR_MGMT_2 : 0, error = 2
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, -3840, at 2
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 8
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 14
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 20
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 26
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 32
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 38
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 44
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 50
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 56
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 62
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 68
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 74
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 80
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 86
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 92
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 98
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 104
Read accel, temp and gyro, error = 2
accel x,y,z: 2969, 409, 123, at 110
Read accel, temp and gyro, error = 2
accel x,y,z: -26357, -26367, 31488, at 116

```

I'm not too good at Arduino, and any help will be immensely appreciated.

# Answer
You have a problem that you can see (the error 2) and a theory about what might be causing it (the accelerometer going to sleep). That's a great place to start from!

I have a few of suggestions to make:

* Collect documentation for the components you are using, a data sheet for the accelerometer, tutorials and instructions for the code to drive it, etc.

A search on:

`MPU6050 accelerometer data sheet`

is likely to get you lots of links to sites hosting data sheets for the accelerometer. With luck you'll be able to find the actual vendor and in addition to the data sheet you may able to find application notes there as well.

For the library, you may find a tutorial or an API description on the site where you downloaded it. You can also do a search on something like:

`MPU6050 accelerometer tutorial`

to find suggestions for how to get started with the device and the code to use it. Tutorials often have sections on testing and avoiding common pitfalls with the device.
* Once you have some documentation see what you can learn about the error. Who generates "error 2?" What does it mean? When does it occur? Once you understand the problem, the answer may be obvious.
* Create minimal test cases. The code sample above is a lot for you, or us, to make sense of and then to test/debug. Pare your code down (or build it up, depending where you are in the process and how you like to work on problems) until you have the **minimum** code needed to test the accelerometer.

Do you see the problem in that code? If you do, then you have many fewer possible problems to look at. If you don't, then add the next piece – perhaps in this case, try to exercise the condition that "error 2" is supposed to report (does it still seem likely that "going to sleep" is the problem?

If you're still stumped at this point you've got the resources at hand to post a great question and the evidence that you've worked on it and understand it for yourself will go a long way towards establishing good will with the people who are trying to help you find answers.

Since this is (potentially) a hardware **and** a software problem, be sure to include an accurate schematic, or photo, of how your project is put together. If you are using someone else's schematic be especially cautious of any potential differences!
> 1 votes

# Answer
From examination of the sketch, the error '2' that you are seeing is returned from `MPU6050_read()`, by the line

```
n = Wire.endTransmission(false); // hold the I2C-bus

```

Looking at the reference for the Wire library, `endTransmission()` returns 2 when

> 2:received NACK on transmit of address

So, when you transmit to the MPU6050, the MPU6050 appears to be returning a Not Acknowledged (NACK) packet.

Why a NACK is being returned is not too clear. From Mpu6050 - error 2 - endTransmission:

> It means the chips is either not connected (or not correctly) or the wrong address was sent.

From the MPU-6050 page on Arduino Playground, it seems that the address should be 0x68 or 0x69

> The pin "AD0" selects between I2C address 0x68 and 0x69. That makes it possible to have two of these sensors in a project. Most breakout boards have a pullup or pulldown resistor to make AD0 default low or high. Connect AD0 to GND or 3.3V for the other I2C address.

What is AD0 connected to? You do not mention that, in your wiring list for the MPU-6050. If you connect AD0 to GND then address 0x68 is used, if it is to 3.3V then the address is 0x69. From MPU6050 SparkFun Breakout to Arduino Uno - No Communication.

> AD0 must be connected to ground or 3.3V (with solder jumper). Connect it to ground for I2C address 0x68. SCL and SDA are connected directly to the Arduino, but you could add extra pull-up resistors to the 3.3V. The resistors could be 4k7 or 10k (the board already has 10k pull-up resistors, but I prefer 4k7). You don't need the INT, you could leave it open. The CLKIN and FSYNC can be tied to ground, because they are not used.

I would suggest checking your wiring, and look for any loose contacts on the MPU6050 board.
> 1 votes

# Answer
I have got same problem and you can solve it in minutes! Firstly check all your I2C addresses with same code:

```
#include "Wire.h"

byte start_address = 0;
byte end_address = 127;

void setup()
{
  byte rc;
  Wire.begin();

  Serial.begin(9600);
  Serial.println("\nI2C Scanner");

  Serial.print("Scanning I2C bus from ");
  Serial.print(start_address,DEC);  Serial.print(" to ");  Serial.print(end_address,DEC);
  Serial.println("...");

  for( byte addr  = start_address;
            addr <= end_address;
            addr++ ) {
      Wire.beginTransmission(addr);
      rc = Wire.endTransmission();

      if (addr<16) Serial.print("0");
      Serial.print(addr,HEX);
      if (rc==0) {
        Serial.print(" found!");
      } else {
        Serial.print(" "); Serial.print(rc); Serial.print("     ");
      }
      Serial.print( (addr%8)==7 ? "\n":" ");
  }

  Serial.println("\n-------------------------------\nPossible devices:");

  for( byte addr  = start_address;
            addr <= end_address;
            addr++ ) {
      Wire.beginTransmission(addr);
      rc = Wire.endTransmission();
      if (rc == 0) {
        Serial.print(addr,HEX); Serial.print(" = ");
        switch (addr) {
          case 0x50: Serial.println("AT24C32/AT24C64 - EEPROM"); break;
          case 0x68: Serial.println("DS1307"); break;
          default: Serial.println("Unknown"); break;
        }
      }
  }

  Serial.println("\ndone");
}

// standard Arduino loop()
void loop()
{
    // Nothing to do here, so we'll just blink the built-in LED
    digitalWrite(13,HIGH); delay(300);
    digitalWrite(13,LOW);  delay(300);
}

```

And you will get something like this:

```
I2C Scanner
Scanning I2C bus from 0 to 127...
00 2      01 2      02 2      03 2      04 2      05 2      06 2      07 2
08 2      09 2      0A 2      0B 2      0C 2      0D 2      0E 2      0F 2
10 2      11 2      12 2      13 2      14 2      15 2      16 2      17 2
18 2      19 2      1A 2      1B 2      1C 2      1D 2      1E 2      1F 2
20 2      21 2      22 2      23 2      24 2      25 2      26 2      27 2
28 2      29 2      2A 2      2B 2      2C 2      2D 2      2E 2      2F 2
30 2      31 2      32 2      33 2      34 2      35 2      36 2      37 2
38 2      39 2      3A 2      3B 2      3C 2      3D 2      3E 2      3F 2
40 2      41 2      42 2      43 2      44 2      45 2      46 2      47 2
48 2      49 2      4A 2      4B 2      4C 2      4D 2      4E 2      4F 2
50 2      51 2      52 2      53 2      54 2      55 2      56 2      57 2
58 2      59 2      5A 2      5B 2      5C 2      5D 2      5E 2      5F 2
60 2      61 2      62 2      63 2      64 2      65 2      66 2      67 2
68 2      69 found! 6A 2      6B 2      6C 2      6D 2      6E 2      6F 2
70 2      71 2      72 2      73 2      74 2      75 2      76 2      77 2
78 2      79 2      7A 2      7B 2      7C 2      7D 2      7E 2      7F 2

-------------------------------
Possible devices:
69 = Unknown

done

```

The address `69` is your device, MPU-6050! Now check your code and you can see that you use:

```
#define MPU6050_I2C_ADDRESS 0x68

```

But you must use the correct address of MPU, change it:

```
#define MPU6050_I2C_ADDRESS 0x69

```

Code source.
> 1 votes

---
Tags: arduino-uno
---


title: RC Car Hack Issue

text:
# Question
Title: RC Car Hack Issue
I am trying to hack a cheap RC car as to be able to control it using my Arduino. I took apart the cars remote controller and found the pins that make it go forwards, backwards, left, and right. So I soldered 4 jumper wires to these pins and connected them to the Arduino as follows: Pin 8 - Left Pin 9 - Right Pin 10 - Forwards Pin 11 - Backwards I found the remote controller is controlled by a chip called TX-2E, I checked the data sheet online and found that if any of the pins that control the pins motion are ground, the car will move in that corresponding direction. So if the forwards pin is grounded the car is supposed to move forwards. To test this, I connected each jumper wire to ground on the Arduino individually and found that it worked as described on the datasheet.

Then I decided to create a sketch that makes the car move forwards for 1 second and backwards for 1 second, it worked as expected.

Then I wrote a sketch that makes the wheels turn left for 1 second and then turn right for 1 second. But it didn't work as expected instead the wheel turned left for 1 second, went to neutral for a second.

I wasn't sure what was wrong, but I decided to run a sketch that should move the car forwards for 1 second, move it backwards for 1 second, turn the wheels left for 1 second, and then turn right for 1 second. But all it actually did was just turn left for 1 second every couple of seconds. I removed the jumper wire connected to pin 8 that is supposed to control the wheels turning left, while the sketch was running and everything worked as expected except the turning left part. it moved forwards for 1 second, moved back for a second, waited at neutral for a second, and then turned right for a second. When I connected back the jumper wire that controls the car moving left everything stops working again. I am not sure whats wrong, I even connected a multimeter to each pin and found they were pulsing between 0V and 5V as expected but for some reason they weren't moving the car, it was only moving left, in this case at least. Any help to get this working, ideas to why its not working, or any troubleshooting tips would be greatly appreciated. Below you can find the code for the sketch, that is supposed to move the car forwards, backwards, left and right.

```
const int LEFT = 8;
const int RIGHT = 9;
const int FWD = 10;
const int BWD = 11;

void reset () {
  //Sets all pins to HIGH as the car moves when the pins are grounded.
  //And we want the car to start out by not moving.

  digitalWrite(LEFT, HIGH); //For some reason everything works when I remove this
  digitalWrite(RIGHT, HIGH);
  digitalWrite(FWD, HIGH);
  digitalWrite(BWD, HIGH);
}

void setup() {
  // put your setup code here, to run once:

  pinMode(RIGHT, OUTPUT);
  pinMode(FWD, OUTPUT);
  pinMode(BWD, OUTPUT);
  pinMode(LEFT, OUTPUT);
  reset();
}

void Forward(){

  digitalWrite(FWD, LOW);
  delay(1000);
  digitalWrite(FWD,HIGH);
  delay(1000);
}

void Backward(){
  digitalWrite(BWD, LOW);
  delay(1000);
  digitalWrite(BWD, HIGH);
  delay(1000);
}

void Left(){
  digitalWrite(LEFT, LOW);
  delay(1000);
  digitalWrite(LEFT, HIGH);
  delay(1000);
}

void Right(){
  digitalWrite(RIGHT, LOW);
  delay(1000);
  digitalWrite(RIGHT, HIGH);
  delay(1000);
}

void loop() {

  Forward();
  Backward();
  Left();
  Right();

}

```

# Answer
> 1 votes
Without details of the car's circuitry one can't say with certainty what the problem is. However, from the description given, one thing sticks out: The TX-2E spec sheet says to ground a control pin to select a motion. But besides grounding pins at times, you are also taking them high.

Instead, try leaving pins open when not active, and pulled down for active. Eg, try code like:

```
void motion(const int pin) {
  pinMode(FWD, OUTPUT);
  digitalWrite(pin, LOW);
  delay(1000);
  pinMode(pin, INPUT);
  delay(1000);
}
void Forward() {
  motion(FWD);
}
void Backward() {
  motion(BWD);
}
void Left() {
  motion(LEFT);
}
void Right() {
  motion(RIGHT);
}

```

---
Tags: arduino-uno, programming, hardware, electronics, remote-control
---


title: programming via ISP

text:
# Question
Title: programming via ISP
A short question:

I wonder weather I can program an AVR chip *(ATMega328, ATMega664, ATMega1284, ATTiny etc.)* using the Arduino IDE, via ISP, **without needing to bootload first.**

Does programming via ISP clear the bootload, if installed previously in the chip?

# Answer
> 2 votes
As Ignacio mentioned, using ISP does not require a bootloader, however, it is also very nearly mutually exclusive with retaining one.

> Does programming via ISP clear the bootload, if installed previously in the chip?

Indeed, it does. The ISP interface on the ATmega cannot erase individual pages but only the entire chip. This is distinct from the SPM instruction used by a bootloader running on the chip itself, which can perform a partial erase. It is also distinct from the ATxmega, which does apparently offer an ISP page erase capability.

So in order to end up with both a bootloader and sketch on the ATmega, you would need to erase the full chip, and then load both the bootloader and the sketch, either in a unified hex file or by loading one and then the other to distinct already-blank memory regions *while using the -D option to tell avrdude not to perform an automatic erase*.

I do not believe the the Arduino IDE supports this, rather its menu option to program a sketch via a programmer is intended to set up a chip for operation with a sketch alone and no bootloader. There does not appear to be any way at GUI-level to configure it to do otherwise.

Someone determined enough could probably craft a customized board configuration that built a functional bootloader into every sketch (or merged or additionally programmed a pre-built one), allowing one shot installation of both an operable sketch and an operable bootloader that could field upgrade it. However, the Arduino IDE would be a poor choice for production programming...

---
Tags: arduinoisp
---


title: Getting POST data into a char array

text:
# Question
Title: Getting POST data into a char array
I'm using Energia to program TI's CC3200 MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.

I'm trying to get the CC3200 to act as a Webserver which when successfully starts up serves up a page with two fields for the username and password that the user needs to fill. Now I'm able to see that the two fields are being successfully POST'd (through Serial.write but only when the code to get it into `buffer` is not present) but I was hoping someone can help me get this content into a character array (called buffer declared before the setup loop begins).

The code in the section `//Here is where the POST data is` does not seem to be working as I see garbage values in `buffer` and in the `Serial.write`. How do I get these POST values into `buffer` OR even better how do I split the two field values and store them into two separate character arrays?

```
void loop()
{
  // listen for incoming clients
  WiFiClient client = server.available();

  if (client) {
    //Serial.println("Client connected");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;

    while (client.connected()) {
      while(client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {

            // Here is where the POST data is.
            Serial.println("Post data: ");
            int ctr = 0;
            while(client.available())
            {
            Serial.write(client.read());
            buffer[ctr] = client.read();
            ctr++;
        }
        Serial.println("Buffer: ");
        Serial.write(buffer);
        Serial.println();

        //Serial.println("Sending response");
        // send a standard http response header
        client.println("HTTP/1.0 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: keep-alive");
        client.println();

        //form added to send data from browser and view received data in serial monitor
        client.println();
        client.println("<!DOCTYPE html>");
        client.println("<html lang=\"en\">");
        client.println("<body>");
        client.println(" <FORM action=\"\" method=\"POST\">");
        client.println("    <P>");
        client.println("    <LABEL for=\"username\">Username:</LABEL>");
        client.println("    <INPUT type=\"text\" name=\"uname\"><BR><BR>");
        client.println("    <LABEL for=\"password\">Password:</LABEL>");
        client.println("    <INPUT type=\"text\" name=\"pwd\"><BR><BR>");
        client.println("    <INPUT type=\"submit\" value=\"Submit\">");
        client.println("    </P>");
        client.println(" </FORM>");
        client.println("</body>");
        client.println("</html>");

        client.println();

        client.stop();
        }
        else if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    //Serial.println("Disconnected");
    Serial.println();
  }
}

```

# Answer
> 2 votes
In this loop

```
while(client.available()) {
    Serial.write(client.read());
    buffer[ctr] = client.read();

```

you're using `client.read()` twice, so the `buffer` gets only every second character.

A solution could be:

```
while(client.available()) {
    int c = client.read();
    Serial.write(c);
    buffer[ctr] = c;

```

---
Tags: web-server
---


title: 0.96" OLED and Arduino UNO usage error

text:
# Question
Title: 0.96" OLED and Arduino UNO usage error
I have Arduino UNO with 0.96" OLED display with 128(width)\*32(height). It is said that I have to edit Adafruit\_SSD1306.h for my 128\*32 OLED, okey I did it from 128\*64 to 128\*32 but I still get the compiler error:

```
ssd1306_128x32_i2c.ino:54:2: error: #error ("Height incorrect, please
fix Adafruit_SSD1306.h!");

```

Yes, I fixed the Adafruit\_SSD1306.h file, **but now,** it is still gives me a compiler error:

```
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::requestFrom(uint8_t, uint8_t, uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:47: error:
too many arguments to function 'uint8_t twi_readFrom(uint8_t,
uint8_t*, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:85: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::endTransmission(uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:48: error:
too many arguments to function 'uint8_t twi_writeTo(uint8_t, uint8_t*,
uint8_t, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:140: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp: In member
function 'virtual size_t TwoWire::write(const uint8_t*, size_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
invalid conversion from 'const uint8_t*' to 'uint8_t*'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
initializing argument 1 of 'uint8_t twi_transmit(uint8_t*, uint8_t)'

```

How can I use my four-pin OLED display with no errors?

# Answer
> 1 votes
May I suggest the following. I found this fork of the Adafruit library which works better than the one they have on their website Adafruit\_ssd1306syp. The original `Adafruit_ssd1306` library doesn't play nice with SPI and when you want to have your OLED running on i2c and use the SPI for something else. This is a great resource. Download, unzip to your libraries directory. Then run this sketch:

```
#include <Adafruit_ssd1306syp.h>

#define SDA_PIN A4
#define SCL_PIN A5

Adafruit_ssd1306syp display(SDA_PIN, SCL_PIN);

void setup() {

  display.initialize();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  printM("Starting Demo...");

}

void printM(String mess) {

  display.println(mess);
  display.update();
}

void loop() {

  printM("working");
  delay(1000);

}

```

# Answer
> -1 votes
You may wanna try this lib: https://github.com/olikraus/u8glib

Supports many devices and is very well documented!

Cheers

---
Tags: arduino-uno, arduino-ide, compile, display
---


# Question
Title: What is commonly done to stop a servo after reaching desired position?
When I started Arduino, I did not expect that everything must be contained in an infinite loop. I thought I could just write something like: motor start -\> motor stop. But in actuality, what I get is motor start -\> motor stop -\> motor start -\> ... forever and ever.

What is commonly done to stop a servo after it is in a desired position? Do I use `servo.write(desired position)` to keep it from turning? Do I detach the output wire?

What are some of the risks involved?

# Answer
You do not "stop" a servo.

A servo is always running. In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target. If you want the target to be maintained, then the servo must be running.

A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position. If the target does not match the current position, it turns on the motor to turn until the two match. Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off". Off meaning the DC motor is drawing little or no current. The servo control loop is always running comparing the shaft position to a target.

If you powered off the entire servo motor, the position is not under control and could move. For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn. But in general, you do not count on friction to make things work.

```
Do I use...Servo.Write(desired position) to keep it from turning?

```

Yes. To tell a servo to stay at one position, you can just keep sending it the same target.

But you do not have to Write() again and again. If you want, you can keep track of what the last setting was and apply only when you have a change. For example, you can code like this:

```
if(position_target != position_last_set) {
  Servo.Write(position_target);
  position_last_set = position_target;
}

```

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.
> 15 votes

# Answer
A normal servo doesn't have a "go" function, it only has positional control. That is, whether you run `servo.write(90)` forever or once, the servo will go to 90 and continue to actively keep that position until you write another position. The only way to turn a servo off is:

```
servo.detach();

```

For a normal DC motor, you will need to turn it on then off and then have kind of state tracking in the loop to never turn it on again, using a variable or `millis()` etc.

Of course, if you want something to only run once, put it in `setup()` (maybe within a loop in setup for simple tasks).

Also, you can simulate ending the program by entering an infinite loop with `while(true){}` or `for(;;){}`.
> 9 votes

# Answer
`myservo.detach();` is what you are looking for. Moving it to a location than detaching. This is good when you want to use it to control a servo and not have it continue to take power like when using a battery. Here is a example.

```
#include <Servo.h>
Servo myservo;  // create servo object to control a servo

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

void loop() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
  delay(15);
  myservo.write(1);
  // sets the servo position according to the scaled value
  delay(1000);
  // waits for it to get to the position
  myservo.detach();
  delay(1000);
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
  delay(15);
  myservo.write(179);
  // sets the servo position according to the scaled value
  delay(1000); // waits for it to get to the position
  myservo.detach();
  delay(1000);

```
> 6 votes

# Answer
The word *servo* has a vague definition and can encompass many types of subcomponents. If you want **no-power position holding** using an electromagnetic motor, then there are four options:

* High viscosity grease
* Dash pot
* Very high gear ratio
* magnetic brake shoe / brake band

EDIT: There are some additional possibilities, but it's sort of an effect of some motor designs:

* Permanent magnet pole holding torque, or detent torque
* Permanent magnet drag torque

The high viscosity grease and dash pot have similar functions; providing a high static friction to resist motion, which then breaks away into movement. (A dash pot is essentially a toothed gear inside a toothed wall container, and which is permanently filled with a high viscosity fluid.)

However both of these will add to the motor load, and when they get hot they tend to become thin and runny and lose holding ability.

A high gear ratio increases the torque required to back-spin the motor. Though note, if any gearbox could have a perfectly frictionless lubricant, no amount of gear reduction could stop back-spinning.

So really this is similar to the thick grease and dash pot, but gear reduction allows just the normal thin lubrication to have enough static breakaway friction, to stop back-spinning.

A magnetic brake gives you active control over the static breakaway friction, and can allow for very high holding ability vs intermittent load spikes on the output shaft. Typically with the power off, a spring engages the brake to hold position with no power.

Note, there are two different kinds of braking: static position holding, and deceleration of a moving mechanism.

The second type both dumps heat into the brake pads and friction plate, and wears down the pads and friction plate. If the brake overheats, the pads usually disintegrate, and the brake now won't hold position.

Unless we're talking about large machinery, usually servo brakes are simple designs without replaceable parts. When the brake fails, you pull the whole thing off and replace it ... including possibly the entire servomotor and gearbox too.

For long service life with magnetic braking, you need to actively decelerate the load using the servo, and then once it has stopped moving, then engage the brake to just do the job of holding position.

Using a magnetic brake for no-power static load holding only, will look like this:

* Power up motor, get current position, and begin actively holding position.
* Energize brake to release it
* Accelerate and move to new position
* Decelerate motor and hold end position
* Remove power from brake to engage it
* Turn off power to motor

The motor is powered up and goes into position holding first, so that the load doesn't suddenly slip in either direction, in the instant between the brake being released and the servomotor then becoming active.

**EDIT #1**: For some permanent magnet motors, even with the power off there is a resistance to rotation because in certain positions, the magnets and the pole pieces more closely attract to each other, known as *detent torque*.

This pole positioning is like a low-energy valley and it takes a bit of force to overcome the magnetic attraction and move the rotor in either direction using an external torque.

You can feel this in some brushless fans and stepper motors, where if you rotate the shaft unpowered, it resists continuous motion, and there seem to be high resistance points that the rotor does not want to cross. When spun, the rotor rapidly slows, and may fall into a back-forth oscillation as it settles into one of the magnetic attractive wells.

This can be used to resist external torques without a brake, but making use if it requires stopping the rotor in one of the magnetic wells rather than a specific position you may want. But if combined with a gearbox, the exact specific stopping position may not matter too critically, and there may be a number of wells next to each other where the rotor can stop that provide an acceptable end-effector alignment.

**EDIT #2**: Permanent magnet drag torque is an effect of shorting all the power wires together. When this is done it takes considerably more force to rotate the shaft than with the stepper coil wires disconnected from each other.

This is because with the coil wires all connected together, when the rotor turns it acts as a generator and current flows through the coils. This current flow creates what is known as counter electromotive force (CEMF), which counters the magnetic field of the permanent magnet.

This CEMF can provide additional resistance against rotation when the servo is unpowered. Although CEMF won't prevent motion, it can help resist continued motion and provide instant deceleration when intermittent load spikes are applied that try to move the unpowered servo.

All of the above is also generally true for linear motor servos. Those don't have gear reduction, but the motion carriage can be lubed with thick grease, be equipped with a dash pot, and have position holding magnetic brakes.
> 3 votes

# Answer
I had the same problem.

I figured out that simply adding `myservo.write(90); delay(4000);` helps to stop motor.

```
#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()

{
  myservo.write(180);
    delay(8000); ////stops motor for 8 seconds
  for(pos = 180; pos>=90; pos-=1)// goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15); // waits 15ms for the servo to reach the position

  }

    myservo.write(90);
    delay(4000); //stops motor for 4 seconds
  for(pos = 90; pos <= 180; pos +=1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);      // waits 15ms for the servo to reach the position

  }

}

```
> 2 votes

# Answer
This is a very brief explanation regarding servos.

The type of servo system that you are proposing is a none positional open loop system and is generaly used for accurate movement rate (controlled speed) . The loop in this case is usually a tachogenerator which sends a voltage (which is proportional to the motor speed) to a comparator which compares the tachogenerator voltage to the required adjustable voltage , the output of the comparator then regulates the motor speed, hence the required speed . this type of servo system will continue to run at the constant speed until A the comparator signal is set to zero or B the motive power is reremoved from the moter ( switched off) ----Point to point servo control , on the other hand ,, generally uses a position command which is verified with a signal from an encoder at which point the servo will stop until another command is issued from the stack ( EG. another position location or a dwell command (wait) or other ) the most common way to do this is to use gcode which has the ability to give full control of your servo system . If there is no encoding device then accurate servo position control is very difficult if not impossible.
> 2 votes

# Answer
A servo, by nature, is used to hold a position in the presence of disturbances trying to disturb that position. If you just need to move a mechanism that won't try to (or can't) back-drive the motor, your application ay be better served by a geared motor with a shaft encoder or position switches.
> 1 votes

---
Tags: servo
---


# Question
Title: How to generate true random numbers over Arduino Uno without any external hardware?
Using a 'random' function in sketch gives same pattern of numbers every-time. But, I need to generate different numbers such that any number to repeat itself should have a very less probability.

# Answer
The standard (but not very good) solution is to seed the random number generator from an `analogRead()` on an unconnected pin. For better options, see this answer to a related question.
> 6 votes

# Answer
Allocate 4 bytes in EEPROM to save a seed value.

Use the EEPROM library (#include ). Use EEPROM.put() and EEPROM.get() functions to write and read the seed value to EEPROM.

In setup(): Read the seed\_value from EEPROM, increment it and write it back to EEPROM. Then call randomSeed(seed\_value).

Now, after every run of setup(), random() will create a whole new random sequence. If you need a new sequence within your sketch, you can repeat the process, and don't forget to write the new seed to EEPROM for next time.

Note that I didn't bother with initialising the EEPROM value the first time we run. It'll probably be zero when you start a new Arduino board, but the only thing that matters is that you increment it each run. Incrementing by 1 will do the trick, but any increment value will probably do.
> 1 votes

---
Tags: arduino-uno, sketch
---


# Question
Title: Thermometer project shows fluctuation due to varying sensor value and voltage
I built this thermometer that reads the sensor value from the temperature sensor and displays it on the LCD display. It basically works fine, but the displayed temperature shows a fluctuation between +/-2 degrees due to varying sensor value and voltage every second. (This is my very first Arduino project and I am pretty new to electronics.) The Arduino gets the power via my Mac through USB.

When I check the sensor value and voltage, it slightly differs each second (or whatever delay interval I use in my code). Sensor value is between 123-125 and voltage usually 0.7, but also changes slightly, which causes the temperature calculation to vary around 2 degrees, which for a "thermometer" is quite a lot.

Is there any way to stabilize it? Should I use a capacitor or another resistor?

Code:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Temperature:");
}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal/1024.0)*powerSupply;
  Serial.print(", Volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5)*100;
  Serial.println(temperature);

  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(temperature);
  // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  delay(1000);
}

```

# Answer
What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions.

* Adding a capacitor between `Vcc` and `Gnd` near the sensor, 0.1µf
* Adding a low-pass filter on the signal line of the LM35 to Arduino
* heatsink on the LM35(they are very sensitive to movement, giving odd readings)

The capacitor on the `Vcc` and `Gnd` will lessen the effects of voltage spikes from the rest of the Arduino's circuitry.

The low-pass filter will help give a more filtered output from the sensor with a better response over time.

```
                2.2k
LM35>---------/\/\/\-0------<Arduino
                     |
                     |
                     |
                    === 1µF
                     |
                     |
                    GND

```

The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window.

All three of the above solutions will probably give the best results.

What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU.

An example of this would be:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;
int sensorVal = 0;

//these are NEW
unsigned long lastTime = 0;     // last time reading taken
unsigned long currTime = 0;     //current time variable intialised
float AverageReading = 0;

float _readingAv = 0;   // static variable for keeping the averaged reading
int _readingsCount = 0;
int _readings = 100;     //the number of readings to take

void setup() {
  Serial.begin(9600);
  //  lcd.begin(16, 2);
  //  lcd.print("Temperature:");
}

void loop() {
  currTime = millis();

  if ((currTime - lastTime) < 1000) {  //checks to see if a second has passed
    sensorVal = analogRead(sensorPin);

    if (_readingsCount < _readings) {
      _readingAv += sensorVal; //add the current value to the last
      _readingsCount++;
    }
    else {
      AverageReading = _readingAv / _readings; //get the average
    }
  }
  else {
    Serial.print("Sensor Value: ");
    Serial.print(sensorVal);

    float voltage = (AverageReading / 1024.0) * powerSupply;
    Serial.print(", Volts: ");
    Serial.print(voltage);

    Serial.print(", degrees C: ");
    float temperature = (voltage - .5) * 100;
    Serial.println(temperature);

    //~ reset the values used by the previous function
    _readingsCount = 0;
    lastTime = currTime;
    _readingAv = 0; //Important to set this back to 0 so not to get odd values

    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
   // print the number of seconds since reset:
    lcd.print(temperature);
    // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  }

}

```

Probably a better version of making filtering code of the LM35.
> 5 votes

# Answer
There are a few things you might try to stabilize your readings.

1. Add a small ceramic capacitor, say 22pF between the analog signal from the temp sensor (green on your example) and ground;
2. Perform multiple reading from your analog, let's say 10, discard max. and min. values and calculate the average. Use this instead of a single reading;
3. User the "internal" voltage as reference. It's normally more stable than using the external 5V. Just bear in mind that you might need to use a voltage divider as the "interval" voltage reference max value is 1.1V (https://www.arduino.cc/en/Reference/AnalogReference);
4. Reduce the wire sizes and make sure all connections are OK.

Probably just by using technique number "2" listed above you'll get much more stable results and don't need any hardware, just a small looping. Also adding the capacitor would be quite simple.

Hope it helps. Cheers!
> 1 votes

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


# Question
Title: How can I make push buttons react to being pressed instantly?
I am making an Arduino alarm clock. I am checking for the state of a button. If it is clicked, I increment the button counter. If the counter is divisible by 2, it is mode 0, if not, it is mode 1. I have small delays in the code for each mode to help the lcd clear itself. Those delays are preventing the buttons to reacting to my touch, because there is likely a delay during that time.

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=0; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){    //this is the part where I check for the state
  if(modeState==HIGH){
    buttonCounter++;
  }
}
prevModeState=modeState;
if(buttonCounter%2==0){
  mode=0;
}
else{
  mode=1;
}

if(mode==0){
  timer=millis();
  if(timer%600==0){
     minutes++;
    if(minutes==60){
        minutes=0;
        hours++;
        }
     if(hours==24){
        hours=0;
     }
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    writeTime();
    delay(200); //delay
    }
}
else if(mode==1){
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Set Time:");
  lcd.setCursor(6, 1);
  writeTime();
  delay(500); //delays

}
}

void writeTime(){
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

```

How can I edit my code?

# Answer
The simple answer is, of course, don't use any `delay()` calls. There is no need for them in your code.

> I cannot remove delays since lcd.clear(); would be done very often and nothing would be visible on the lcd.

So don't clear the LCD. There is no reason to clear the LCD. Just over-print the existing text with new text. Go on, have a go. Just remove the `lcd.clear()` calls and the delays from your program and see just how smoothly the screen updates.

On an LCD a cell can only hold one character at a time. Printing one thing and then printing something else in the same place replaces the characters that are already there with the new ones. There is rarely any need to use `lcd.clear()` for normal screen updates - only if you really need to clear the *entire* screen should you use it. Just updating a bit of text on the screen does not require clearing of the entire screen.

In fact, you don't even need to print `Time:` or `Set Time:` every loop - you only need to do that once when you change mode. If you are going to clear the screen that is the time to do it. So a quick outline:

* When button pressed:
    + Set mode
    + Clear screen
    + Print static text (`Time:` etc)
* Every iteration:
    + Print the mode's dynamic text

You see the heavyweight screen clearing is only done once when you change mode. All the rest of the time it's just updating small portions of the screen. Not only does it look nicer (no flicker) but it's also considerably more efficient and allows your program to do more.
> 2 votes

# Answer
You have a few options, including using interrupts. But I believe the most important thing is: "do not use delay()" and you might not even need to use interrupts...

Have a look on this nice post from Nick Gammon: http://www.gammon.com.au/blink with some tips about non-blocking coding.

Also a very simple "Blink LED" example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
> 2 votes

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


title: Arduino Wireless SD Shield

text:
# Question
Title: Arduino Wireless SD Shield
Is it possible to use the Wireless SD shield without the wireless function, or XBEE Module? I do not need it to be wireless it simply was cheaper than any other I could find, so I was wondering if it was possible to use it just like a normal, non-wireless SD Shield? Thanks!

# Answer
In general, on a combined "Something plus SD card" shield like this the SD card is a completely separate section to the rest of it. The only real exception is on some audio shields (mp3) where the SD card is directly controlled by the audio CODEC chip.

So yes, you can pick and choose which portions of the shield you actually use in your code. Just by not using the bits you don't want to use.
> 1 votes

---
Tags: arduino-leonardo, sd-card, wireless
---


# Question
Title: wifi failled connection with yun and after upgrading openwrt
I recently bought an arduino yun. When trying to connect to the router following the procedure in https://www.arduino.cc/en/Guide/ArduinoYun#toc14. After the Configure & Restart, the Arduino network shut down after a few moments but it wasn´t linked to my router.

After reading a bit about it in the internet, i upgraded it following https://www.arduino.cc/en/Tutorial/YunSysupgrade. As i found that the firmware version 1.5.3 was from 2014 https://github.com/arduino/openwrt-yun/blob/master/ChangeLog, and as Reflashing the OpenWrt-Yun image on the Yún would void warranty, i proceeded by http://nootrix.com/software/upgrade-arduino-yun-openwrt/. Everything occured as detailled there.

However now, when i turn on the yún, none network appear and the WLAN LED doesn't blink.

Thanks

# Answer
Find out if the Linux system is running. Maybe you mistyped your WiFi password. Try the Following:

* connect via Ethernet check your router to see if the Yun request an IP via DHCP
* If unsuccessful connect via USB and install this sketch to see if you get a command prompt maybe your network settings are messed up

Still no success?

* Press the WiFi reset button for at least 30 seconds to do a reset to factory defaults.
> 1 votes

---
Tags: wifi, arduino-yun, wireless
---