body:
I do a school project (CanSat) it's an international project. But my problem is my GPS. I tried 2 different codes. Both they say the GPS is connected. They GPS led doesn't provide any light.

wiring:
UBlox Neo 6M
Arduino leonardo
Rx (GPS) to port 8
Tx (GPS) to port 9
Vcc to Vcc
Gnd to Gnd

Btw I sit near the window.

First code:
The gps.encode(c) is always false/0 I don't know why this one doesn't work.

<!-- language-all: lang-cpp -->

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

 SoftwareSerial mySerial(9, 8);
 TinyGPS gps;

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

 void setup()
 {
   // Oploen 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.println("uBlox Neo 6M");
   Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
   Serial.println("by Mikal Hart");
   Serial.println();
   Serial.print("Sizeof(gpsobject) = ");
   Serial.println(sizeof(TinyGPS));
   Serial.println();
 }

 void loop() // run over and over
 {
   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();
   // Serial.println(c);  // uncomment to see raw GPS data
    if (gps.encode(c)){
   newdata = true;
   break;  // uncomment to print new data immediately!
    }
  }
   }

   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.");

   gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
   Serial.print("Date: "); Serial.print(static_cast<int>(month)); Serial.print("/");
  Serial.print(static_cast<int>(day)); Serial.print("/"); Serial.print(year);
   Serial.print("  Time: "); Serial.print(static_cast<int>(hour+8));  Serial.print(":"); //Serial.print("UTC +08:00 Malaysia");
  Serial.print(static_cast<int>(minute)); Serial.print(":"); Serial.print(static_cast<int>(second));
  Serial.print("."); Serial.print(static_cast<int>(hundredths)); Serial.print(" UTC +08:00 Malaysia");
   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;
   }
 }

Second code:
Location is invailed but i will get the time with an 1 hour and some minuts diffrence.

 #include <TinyGPS++.h>
 #include <SoftwareSerial.h>
 /*
    This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
    It requires the use of SoftwareSerial, and assumes that you have a
    4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
 */
 static const int RXPin = 9, TXPin = 8;
 static const uint32_t GPSBaud = 9600;

 // The TinyGPS++ object
 TinyGPSPlus gps;

 // The serial connection to the GPS device
 SoftwareSerial ss(RXPin, TXPin);

 void setup()
 {
   Serial.begin(9600);
   ss.begin(GPSBaud);

   Serial.println(F("DeviceExample.ino"));
   Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
   Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
   Serial.println(F("by Mikal Hart"));
   Serial.println();
 }

 void loop()
 {
   // This sketch displays information every time a new sentence is correctly encoded.
   while (ss.available() > 0)
  if (gps.encode(ss.read()))
    displayInfo();

   if (millis() > 5000 && gps.charsProcessed() < 10)
   {
  Serial.println(F("No GPS detected: check wiring."));
  while(true);
   }
 }

 void displayInfo()
 {
   Serial.print(F("Location: "));
   if (gps.location.isValid())
   {
  Serial.print(gps.location.lat(), 6);
  Serial.print(F(","));
  Serial.print(gps.location.lng(), 6);
   }
   else
   {
  Serial.print(F("INVALID"));
   }

   Serial.print(F("  Date/Time: "));
   if (gps.date.isValid())
   {
  Serial.print(gps.date.month());
  Serial.print(F("/"));
  Serial.print(gps.date.day());
  Serial.print(F("/"));
  Serial.print(gps.date.year());
   }
   else
   {
  Serial.print(F("INVALID"));
   }

   Serial.print(F(" "));
   if (gps.time.isValid())
   {
  if (gps.time.hour() < 10) Serial.print(F("0"));
  Serial.print(gps.time.hour());
  Serial.print(F(":"));
  if (gps.time.minute() < 10) Serial.print(F("0"));
  Serial.print(gps.time.minute());
  Serial.print(F(":"));
  if (gps.time.second() < 10) Serial.print(F("0"));
  Serial.print(gps.time.second());
  Serial.print(F("."));
  if (gps.time.centisecond() < 10) Serial.print(F("0"));
  Serial.print(gps.time.centisecond());
   }
   else
   {
  Serial.print(F("INVALID"));
   }

   Serial.println();
 }
another small weird thing is, that if I upload the code to the Arduino the Serial monitor says normally COM6(Arduino leonardo), but when it is just finished it goes to COM6 only but the program still works.

I will appreciate all the help I can get :)

title: NEO 6M doenst provide coordinates

Answers: 0


body:
I would like to find an Arduino with built-in Bluetooth.
I know about the HC-06, the shields and the other Bluetooth modules, but i would like to have built in Bluetooth for eliminating the risk for miscommunication on the serial port.

The official Arduino foundation did produce an board but it's retired now.

title: Arduino board with built-in Bluetooth

Answers: 3

body:
There is this board called Bluno
Its an Arduino UNO Based board with built in Bluetooth 4.0

[Bluno - An Arduino Bluetooth 4.0 (BLE) Board][1]

[![Bluno - An Arduino Bluetooth 4.0 (BLE) Board][2]][2]

[![enter image description here][3]][3]

  [1]: https://www.dfrobot.com/product-1044.html
  [2]: https://i.stack.imgur.com/l2Bv8.jpg
  [3]: https://i.stack.imgur.com/gi67A.jpg

body:
Arduino has just released a **MKR WIFI 1010** board that includes an *ESP32* module that allows Bluetooth connectivity. It's mainly an internet of things board but it supports:

 - Bluetooth low energy, BLE
 - Wifi

[![Arduino MKR Wifi 1010][1]][1]

  [1]: https://i.stack.imgur.com/frMCO.jpg

body:
This is my currently favourite Arduino compatible board:
https://wiki.wemos.cc/products:d32:d32

[![enter image description here][1]][1]

ESP32 is great: offers both wi-fi, Bluetooth and BLE connection as well as lots of GPIO.
9 GPIO's can be used as capacitive touch sensors (it has 10, but only 9 are available).

  [1]: https://i.stack.imgur.com/wQfk6.jpg


body:
        void storedata(File filename ,int type , String data)
    {
        if(type == 1){
          Serial.println("Group Creation");
        }
        //Storing Data into file
        pinMode(10, OUTPUT);
        if (!SD.begin(SD_CS_PIN)) {
        Serial.println("initialization failed!");
        return;
      }
        Serial.println("initialization done.");
        filename = SD.open("filename.txt", FILE_WRITE);
        if (filename) {
        Serial.print("Writing to filename.txt...");
        SdFile file("sdfile.txt", O_WRITE | O_CREAT);
        if (!file.isOpen()) {
        Serial.println("filename.txt");
       }
        sdfile.println(data);
        //close the file:
        filename.close();
        Serial.println("done.");
        }else{
        // if the file didn't open, print an error:
        Serial.println("error opening filename.txt");
      }}

Im using this function to write on the Sd card , before calling this function the sketch memory is 28802 bytes ie ) 93% , simply just by calling this function from setup increased the sketch memory to 102% and iam unable to compile is there any unusual memory usage in this code ?

title: Sketch Memory in Pro

Answers: 2

body:
If you have a function that isn't called the compiler will just delete it (optimise it out). It also deletes any functions that the function calls that aren't used anywhere else.

By then calling that function the compiler keeps it, along with any other functions it relies on.

That includes the SDFat library code, much of which will have been removed before.

To make it now fit you will have to optimise your program. Look for blocks of code that do the same thing and replace them with calls to a function. Look for parts that could be replaced by a loop and an array instead of discrete calls to the same function(s) over and over again. Things like that.

Either that or use a board that has enough flash for your project.

body:
The good thing is that flash memory is instantly to be checked (you get the result after a (succesfull) compilation.

Refactoring you can do to reduce space:

- prevent duplicate code; try to make a function from duplicated code and call it whenever needed; this also makes the program much more easy to maintain (bugs in those part have to be solved only once, and changed only adapted once).
- If the code is almost the same but not an exact duplicate, use parameters in the function for the differences.
- Remove code that does not have a function but still is called. The compiler can automatically delete UNUSED code, but USED code that has no function you have to do yourself.
- Normally PROGMEM and F() is used to store arrays/strings in FLASH instead of SRAM, since mostly SRAM is more scarce, in your case you should not use this.
Try to optimize code using less lines. This does not mean you have to remove spaces or make big oneliners; that will not help. But changing code structurally without changing the functionality will reduce flash memory.
- Remove unused libraries (although these are probably optimized out by the compiler)
- Global variables/structs/arrays and lots of const variables will cost memory to. For const values it might be useful to use #defines, however this will reduce maintainability/type checking.
- Remove debugging code (printf's for debugging functionality); I never tried but I think it should be feasible to make unit tests separately from the sketch code.
- A tricky way that could help is to optimize the libraries and reducing code there when needed. It is not useful to throw away functions that will not be called though. And debugging information should not be present, but maybe you can remove some conditions or code fragments that will never occur.


body:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/tDOiK.png

Here is a program and circuit diagram of an Arduino-based car parking (copy pasted from http://www.arduining.com/2012/10/13/arduino-parking-lot-filled/ ) I want to replace the Exit and End switch with IR sensor or ultrasonic sensor.

<!-- language: lang-cpp -->

    /*ParkingL02.pde
      Arduining.com 08 JUL 2012
      Code used in the production of the Youtube material.
    */
    #include <Servo.h>
    Servo myservo; // create servo object to control a servo
    #define ServoM 12 //Connected to the servo motor.
    #define Bright 11 //servo library disable PWM on pins 9 and 10.
    #define Exit 9 //Pin connected to the EXIT button.
    #define In 8 //Pin connected to the IN button.
    #define BarLow 177 //Low position of the barrier.
    #define BarUp 95 //Up position of the barrier.
    #define CAPACITY 8 //Capacity of the parking lot.
    #define INTEN 80 //Display intensity %
    //Pins conections to segments (cathodes).
    #define segA 0
    #define segB 1
    #define segC 2
    #define segD 3
    #define segE 4
    #define segF 5
    #define segG 6

    int SensorIn(void);     // declare the sensor function for entering autos

    //Array with the segments to represent the decimal numbers (0-9).
    byte segments[10] = {
      // pgfedcba <--- segments
      B00111111, // number 0
      B00000110, // number 1
      B01011011, // number 2
      B01001111, // number 3
      B01100110, // number 4
      B01101101, // number 5
      B01111101, // number 6
      B00000111, // number 7
      B01111111, // number 8
      B01101111 // number 9
    };

    void setup() {
      myservo.attach(ServoM); // attaches the servo.

      pinMode(Exit, INPUT); // set "EXIT" button pin to input
      pinMode(In, INPUT); // set "IN" button pin to input

      digitalWrite(Exit, HIGH); // Connect Pull-Up resistor.
      digitalWrite(In, HIGH); // Connect Pull-Up resistor.

      pinMode(segA, OUTPUT);
      pinMode(segB, OUTPUT);
      pinMode(segC, OUTPUT);
      pinMode(segD, OUTPUT);
      pinMode(segE, OUTPUT);
      pinMode(segF, OUTPUT);
      pinMode(segG, OUTPUT);
      pinMode(Bright, OUTPUT);

      analogWrite(Bright, 255 * INTEN / 100);
      myservo.write(BarLow); //Barrier in the low position
      // delay(1000);
    }

    int Available = 9; // Number of places available.

    void loop() {
      Display(Available);
      if ( SensorIn() == 0 )
      {
        if (Available != 0) {
          Available--;
          myservo.write(BarUp);
          delay(3000);
          myservo.write(BarLow);
        }
      }
      if (digitalRead(Exit) == 0)
      {
        if (Available != CAPACITY) {
          Available++;
          myservo.write(BarUp);
          delay(3000);
          myservo.write(BarLow);
        }
      }
    }

    /*-------------------------------------------------------------------
      Put the segments according to the number.
      --------------------------------------------------------------------*/
    void Display(int number) {
      byte segs = ~segments[number]; //"~" is used for commom anode.
      digitalWrite(segA, bitRead(segs, 0) );
      digitalWrite(segB, bitRead(segs, 1) );
      digitalWrite(segC, bitRead(segs, 2) );
      digitalWrite(segD, bitRead(segs, 3) );
      digitalWrite(segE, bitRead(segs, 4) );
      digitalWrite(segF, bitRead(segs, 5) );
      digitalWrite(segG, bitRead(segs, 6) );
    }

    // We've moved the "sensor code" for entering autos to this function
    // For now, the "In-sensor" is just a push-button.
    int SensorIn(void) {
      return ( digitalRead(In) );
    }

title: Arduino car parking program help

Answers: 1

body:
If it were me, I'd approach it this way:

- Move each button read (digitalRead(xxx)) into its own routine.
- Get everything to work, still using the buttons.
- Write a separate sketch for whatever sensor or sensors you're going to use. All it needs to do is light an LED so you can be sure when it is detecting and when it isn't.
- Now replace the contents of each of the new button routines (from step 1) with the sensor code you just wrote. Your routines should return the *same values* for sensor detection that they returned for button detection. You shouldn't need to change any other part of your original code.
- Fix any bugs you made in the step above, and you're done.

Update:

I've just indented your code (above) and made one of the changes I suggested. You'll see that I made a new function called SensorIn() and put the code to read the "In" button there. Do the same thing for the "Exit" button.

Then, using a new sketch, learn to write code for whatever kind of sensor you want to use for entering autos. When that works, copy it into this sketches 'SensorIn()' function, replacing the line that reads the push button. Get this much working.

Then do the same thing, write a new sketch for the exit sensor until you can make that work reliably, too. Of course, if you choose to use the same kind of sensor for Exit as you used for In, you can just re-use the same code. Get this sketch working again.

Now you should have a sketch, just like your pushbutton sketch, but one that uses two real sensors instead of buttons.


body:
I don't know if this is the right place to ask, but I'm an arduino newbie and I'm seeking some suggestions.

For my Robotics subject at University, I'm going to build a robot that should be able to move some objects (dragging them on the ground, not lifting them) from one place to another. I was looking around the web for the necessary components when I stumbled on a doubt: are 3-6V motors powerful enough for the wheels? Or do I need something more powerful like the 12V motors?

I'm not sure of what to choose between step motors or servo motors either, what do you suggest?

Oh and last thing, I opted for a L293D bridge driver for the motors, is this a good idea?

Thanks in advance!

title: Which motors to choose?

Answers: 2

body: A 12 volt DC motor is good for dragging items, but then again it depends on the items weight. Stepper is used for millimeter precision, like 3D printing. Servo is an DC motor with precision for 180 degree movement, like robot arms. If the moving object is over 1kg you should look into geared DC motors or even the stronger brushed motors, or geared brushed motors. Whats the max weight?

body:
You need to size your motors correctly depending on how much load they are expected to overcome. You first consideration should be how much maximum force would your robot need to exert at any given time....

For a robot just starting to drag a load (assuming the surface is flat) behind it, the robot would have to at least apply a force just greater than...

Maximum Static Frictional Force due to Robot's own weight on its wheels + Maximum Static Frictional Force due to object being dragged.

Maximum Frictional Force = Normal Force (weight) * coeff of Friction for the two surfaces

So for example, the coeff of friction between a brick (load) and ice (surface) would be lesser than between a brick (load) and asphalt (surface).

You need to do these calculations first.

If the speed limitations of your robot are inconsequential, then you only need to choose your wheel size and then determine how much torque your motor needs to be able to generate.

You do this like so.....Motor Torque needed = Force to generate / (radius of wheel * number of motors you want to install). So for instance, the torque needed per motor in a 4WD robot would be half that needed for an equivalent robot with only 2 powered wheels.

Once you have the motor torque you need, you can choose a motor and then choose a suitable power source for this motor.

Now repeat ALL the steps above this time accounting for the weight of the motors and the battery.


body:
I have an authentic Arduino UNO, but I didn't want to pay full price for a new one to build semi perminate projects, so I bought a few ATMEGA328P-PU chips off of AliExpress:

https://www.aliexpress.com/item/1pcs-lot-ATMEGA328P-PU-CHIP-ATMEGA328-Microcontroller-MCU-AVR-32K-20MHz-FLASH-DIP-28/32346944696.html

But when I try to use Arduino IDE to upload the sketch to the new chips, I get these errors:

>avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

It happens 10 times and quits.

It works fine when I put the original chip back in.

If anyone has any experience with this I'd be very grateful!

**EDIT:**

Trying the burn bootloader steps, and I'm getting a new error.

Steps I took:

I'm doing the 8MHz option, and so I downloaded the breadboard-1-6-x.zip file. (I'm using Arduino IDE 1.6.5 on Mac).

I uploaded the ArduinoISP example to my working chip, then wired it up to the breadboard as per the picture.

I switched the programmer to Arduino as ISP and set the board to ATMEGA328 on breadboard (8MHz clock)

I went to tools>burn bootloader, and got this error:

> Arduino: 1.6.5 (Mac OS X), Board: "ATmega328 on a breadboard (8 MHz
> internal clock)"
>
> /Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude
> -C/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf
> -v -patmega328p -cstk500v1 -P/dev/cu.usbmodem411 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m
>
> avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
>          Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
>          Copyright (c) 2007-2009 Joerg Wunsch
>
>          System wide configuration file is "/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
>          User configuration file is "/Users/andy/.avrduderc"
>          User configuration file does not exist or is not a regular file, skipping
>
>          Using Port                    : /dev/cu.usbmodem411
>          Using Programmer              : stk500v1
>          Overriding Baud Rate          : 19200 avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
>          AVR Part                      : ATmega328P
>          Chip Erase delay              : 9000 us
>          PAGEL                         : PD7
>          BS2                           : PC2
>          RESET disposition             : dedicated
>          RETRY pulse                   : SCK
>          serial program mode           : yes
>          parallel program mode         : yes
>          Timeout                       : 200
>          StabDelay                     : 100
>          CmdexeDelay                   : 25
>          SyncLoops                     : 32
>          ByteDelay                     : 0
>          PollIndex                     : 3
>          PollValue                     : 0x53
>          Memory Detail                 :
>
>                                   Block Poll               Page                       Polled
>            Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
>            ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
>            eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
>            flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
>            lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>            hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>            efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>            lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
>            calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
>            signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
>
>          Programmer Type : STK500
>          Description     : Atmel STK500 Version 1.x firmware
>
> avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14
>
> avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02
>
> avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
>          Hardware Version: -1543397124
>          Firmware Version: 2165568.-1543397124
>          Topcard         : STK502
>          Vtarget         : 1.8 V
>          Varef           : 0.0 V
>          Oscillator      : Off
>          SCK period      : 0.1 us
>
> avrdude: stk500_initialize(): (b) protocol error, expect=0x10,
> resp=0x01 avrdude: initialization failed, rc=-1
>          Double check connections and try again, or use -F to override
>          this check.
>
> avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10
>
> avrdude done.  Thank you.
>
> Problem uploading to board.  See
> http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Making a little progress at least...

**Solution:**

I was using this layout:

[![enter image description here][1]][1]

Since that was failing I decided to try using the nano that I got at the same time, and after a lot of research I found this video:

https://www.youtube.com/watch?v=94KCYqS3--A

I jumpered the pins shown at the 1:30 mark to the ICSP port, **and tried burning the bootloader twice per chip, and on the second try it worked! Don't know why it had to be tried twice.**

I may go back to trying the breadboard method, just to see if it works if I try burning it twice.

  [1]: https://i.stack.imgur.com/rbnOU.png

title: Programming Chinese Arduinos

Answers: 1

body:
It's because these are unprogrammed chips, meaning they haven't had a bootloader programmed into them yet. [Here is a tutorial][1] for using your Arduino board to program a bootloader into them (there are many such tutorials available).

It only needs to be done once per chip so it will be worth your while to program all of them, once you have set up to do one. This is a very economical way to build "home-brew-duinos".

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


body:
I am currently working with a few robotic projects where i use lipo batteries. Currently I am working with a 1500 mah 3s lipo.

With my current setup I am using a arduino uno and a power distribution board. I put my lipo charger in my power distribution board which has two connections where I put two cables that goes to the VLN and GND.

(If needed I can make a quick schematic to explain it better!)

How can I now see the current battery percentage of the lipo?

I came across a project that uses this codesnippet:

    long previousMillis = 0;

    long interval = 1000;

    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);

    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis > interval) {
      previousMillis = currentMillis;
     if (voltage <= 3.5)
          Serial.println("Low Battery");
         else
          Serial.println(voltage, DEC);
    }

This snippet works with the A0 and I do not have anything connected there so I assume not.

Appreciate every help! :)

title: How to detect lipo battery % charge left?

Answers: 2

body: Characterize a few such batteries by putting them through a charge / discharge cycles so you can link their voltage with remaining capacity.

body:
LiPo batteries do not work well for percentage of charge remaining when using voltage as a reference. Lithium chemistry batteries hold a voltage quite close to level up to the point of near-exhaustion. That is to say, you can deplete such a battery by 80%, leaving only 20% capacity and have a few tenths of a volt reduction, depending on the configuration of your battery pack.

Unfortunately, should you continue to deplete the battery, damage may result. Some will say that damage WILL result.

The only certain way to determine a battery capacity is to use a smart charger and/or a smart discharger (often combined into one) to profile a battery.

For example, I have a 2000 mAh battery. After a few conditioning runs, either in use or on the smart dis/charger, the battery shows as having 1600 mAh capacity to 80% discharge.

Using a device to monitor the discharge rate, one can determine that if one uses 1550 mAh of the capacity, one is quite close to the risky cut-off point.
To continue discharging, there is risk involved in the lifespan of the battery.

LiPo batteries will have greater than 4 volts reading immediately off the charger and will "flatten" to optimum voltage in a short time and hold very close to that level, depending on the current load, until it virtually vanishes at the cut-off point.

One can approximate a safe voltage for the cut-off point, but one risks the chance of an inaccurate volt meter. Collecting ampere-hours as a reference for cut-off is the most accurate method and also allows more capacity with less chance of damage.


body:
this is my setup: I have an arduino uno + mpu-6050 + nrf24l01 all attached together and am transmitting data from that mpu-6050 to another arduino with an nrf24l01 attached to it. I got the arduinos to communicate with each other and transmit data ( ypr) wirelessly but it's still laggy and jumpy. Before I was getting FIFO overfull messages but I managed to somewhat fix that. Yet the data being transferred is still not running to stable nor smoothly. PLEASE HELP ME find the problem why these arduinos aren't transferring data fluently and smoothly. I posted the Receiver and transmitter codes down below. Also, I am illustrating the code on Processing 3.2.3, hence the teapot parts. THANK YOU

**************************RECEIVER*****************************************

    {
        #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    // format used for the InvenSense teapot demo
    #define OUTPUT_TEAPOT

    RF24 radio(7, 8);//pin assignment
    unsigned long t0;
    unsigned long t1;
    float ypr[3];
    uint8_t teapotPacket[14] = { };

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

      while (!Serial);
      Serial.begin(115200);

      radio.begin();
      radio.openReadingPipe(1, 0xF0F0F0F0A1LL);
      radio.openReadingPipe(2, 0xF0F0F0F0A2LL);

      radio.startListening();
      t0=0;
    }
    byte pipeNum=0; //variable to hold which reading pipe sent data
    void loop()
    {
      t1=millis();
      /*digitalWrite(13,HIGH);
      delay(500);
      digitalWrite(13,LOW);
      delay(500);
      */
      if (t1-t0>100){
      if (radio.available(&pipeNum))
      {

        typedef struct YPR_RX {
          int y;
          int p;
          int r;
        } YPR_RX;
        YPR_RX ypr_rx;

        //radio.read(&ypr_rx, sizeof(ypr_rx));
       // teapotPacket = new uint8_t teapoPacket(radio.getPayload)

        radio.read(&teapotPacket, sizeof(teapotPacket));
       // radio.read(&teapotPacket, sizeof(radio.getPayloadSize()));
    //    radio.SetDatarate();
        uint8_t newTeapot[14] = {'$', 0x02, teapotPacket[2],teapotPacket[3],teapotPacket[4],teapotPacket[5],teapotPacket[6],
                                            teapotPacket[7],teapotPacket[8],teapotPacket[9], 0x00, 0x00, '\r', '\n' };
        Serial.write(newTeapot, 14);
        newTeapot[11]++;

                Serial.print(newTeapot[2]);
                Serial.print("\t");
                Serial.print(newTeapot[3]);
                Serial.print("\t");
                Serial.print(newTeapot[4]);
                Serial.print("\t");
                Serial.print(newTeapot[5]);
                Serial.print("\t");
                Serial.print(newTeapot[6]);
                Serial.print("\t");
                Serial.print(newTeapot[7]);
                Serial.print("\t");
                Serial.print(newTeapot[8]);
                Serial.print("\t");
                Serial.println(newTeapot[9]);

    /*
        Serial.print(ypr_rx.y);
        Serial.print("\t");
        Serial.print(ypr_rx.p);
        Serial.print("\t");
        Serial.print(ypr_rx.r);
        Serial.print("\t");
        Serial.println();
        */

        t0=t1;

        //Serial.println("X-acceleration");
        //int number=atol(text);
        //Serial.println(number);
        //Serial.println((int)text);
        //Serial.println(value);
        //delay(100);

      }
      }

    }
    }

*********************************TRANSMITTER************************************

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    // format used for the InvenSense teapot demo
    #define OUTPUT_TEAPOT

    RF24 radio(7, 8);//pin assignment
    unsigned long t0;
    unsigned long t1;
    float ypr[3];
    uint8_t teapotPacket[14] = { };

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

      while (!Serial);
      Serial.begin(115200);

      radio.begin();
      radio.openReadingPipe(1, 0xF0F0F0F0A1LL);
      radio.openReadingPipe(2, 0xF0F0F0F0A2LL);

      radio.startListening();
      t0=0;
    }
    byte pipeNum=0; //variable to hold which reading pipe sent data
    void loop()
    {
      t1=millis();
      /*digitalWrite(13,HIGH);
      delay(500);
      digitalWrite(13,LOW);
      delay(500);
      */
      if (t1-t0>100){
      if (radio.available(&pipeNum))
      {

        typedef struct YPR_RX {
          int y;
          int p;
          int r;
        } YPR_RX;
        YPR_RX ypr_rx;

        //radio.read(&ypr_rx, sizeof(ypr_rx));
       // teapotPacket = new uint8_t teapoPacket(radio.getPayload)

        radio.read(&teapotPacket, sizeof(teapotPacket));
       // radio.read(&teapotPacket, sizeof(radio.getPayloadSize()));
    //    radio.SetDatarate();
        uint8_t newTeapot[14] = {'$', 0x02, teapotPacket[2],teapotPacket[3],teapotPacket[4],teapotPacket[5],teapotPacket[6],
                                            teapotPacket[7],teapotPacket[8],teapotPacket[9], 0x00, 0x00, '\r', '\n' };
        Serial.write(newTeapot, 14);
        newTeapot[11]++;

                Serial.print(newTeapot[2]);
                Serial.print("\t");
                Serial.print(newTeapot[3]);
                Serial.print("\t");
                Serial.print(newTeapot[4]);
                Serial.print("\t");
                Serial.print(newTeapot[5]);
                Serial.print("\t");
                Serial.print(newTeapot[6]);
                Serial.print("\t");
                Serial.print(newTeapot[7]);
                Serial.print("\t");
                Serial.print(newTeapot[8]);
                Serial.print("\t");
                Serial.println(newTeapot[9]);

    /*
        Serial.print(ypr_rx.y);
        Serial.print("\t");
        Serial.print(ypr_rx.p);
        Serial.print("\t");
        Serial.print(ypr_rx.r);
        Serial.print("\t");
        Serial.println();
        */

        t0=t1;

        //Serial.println("X-acceleration");
        //int number=atol(text);
        //Serial.println(number);
        //Serial.println((int)text);
        //Serial.println(value);
        //delay(100);

      }
      }

    }

title: arduino + mpu6050 + nrf24l01 >>>>>>>>>>>>nrf24l01 + arduino ( Not running fluently)

Answers: 0


body:
I'm trying to make my ESP8266 (running NodeMCU meaning Arduino code gets compiled on it). I followed a guide and now I can read the IR codes from my remote using my Arduino UNO, and then send them to the LED strip. So far sending it actually works, but it blinks REALLY fast.

Some part of me tells me it's trying to send it twice or the radio frequency is wrong. For TVs and so on, it doesn't really matter, as you can't turn on and off a TV instantly. You can with this LED strip though. This is how I send my NEC signal to the strip:

    irsend.sendNEC(0xFF02FD, 433);

433 is the frequency (433 kHz), as I read that's the most common frequency these LED strips work at. The entire code I used [can be found here](https://github.com/JZ-SmartThings/SmartThings/blob/master/Devices/TVDevice/IRremoteESP8266-Using5Volts/IRSender5V.ino). Do you think I have a frequency issue? I have tried a lot of different frequencies and they all seem to do the same thing.

Also, when I try to send the exact same NEC signal to my receiver, I get two different results. It is only being sent one time as well. Here is what I receive:

**Using the actual receiver**:

    Decoded NEC(1): Value:FF02FD (32 bits)
    Raw samples(68): Gap:51848
      Head: m8750  s4550
    0:m450 s650 1:m450 s650   2:m450 s650 3:m450 s650
    4:m500 s650 5:m450 s650   6:m450 s650 7:m450 s650
    8:m450 s1750 9:m500 s1750   10:m450 s1750 11:m450 s1750
    12:m500 s1750 13:m450 s1750   14:m450 s1750 15:m500 s1750

    16:m450 s650 17:m450 s650   18:m450 s650 19:m450 s650
    20:m500 s600 21:m500 s650   22:m450 s1750 23:m450 s650
    24:m450 s1750 25:m500 s1700   26:m500 s1750 27:m450 s1750
    28:m500 s1700 29:m500 s1750   30:m450 s650 31:m450 s1750

    32:m450
    Extent=66900
    Mark  min:450  max:500
    Space min:600  max:1750

**Using `irsend.sendNEC(0xFF02FD, 433)`**

    Decoded Unknown(0): Value:0 (0 bits)
    Raw samples(38): Gap:18088
      Head: m8850  s4550
    0:m500 s1750 1:m500 s650   2:m450 s650 3:m500 s650
    4:m500 s650 5:m450 s650   6:m500 s650 7:m450 s1800
    8:m450 s700 9:m450 s1800   10:m450 s1800 11:m450 s1800
    12:m450 s1800 13:m450 s1800   14:m450 s1800 15:m450 s650

    16:m500 s1750 17:m500
    Extent=43200
    Mark  min:450  max:500
    Space min:650  max:1800

EDIT: I forgot to mention: 0xFF02FD is the signal power/on/off button. If I change the 0xFF02FD to anything else (like 0xFF18E7 to make it yellow), the LED strip will just blink.

title: Sending NEC IR signals makes LED strip blink

Answers: 1

body: 32 kHz seems to be the winner. Now all my codes work! Damn, if I only had read that ONE SITE that showed it haha.


body:
I have a Linksprite RS232 v2 adapter (which uses a MAX232 chip), as per [this image][1]. I have soldered on the headers and tested the pins to make sure there are no solder bridges. I have set the jumpers so that D2 is set to TX and D3 to RX. However, I can't establish comms through the device using the Software Serial library, regardless of how I set the jumpers. (Real Term doesn't show me anything when a USB-to-Serial adapter is connected. However, if I change the baud rate to 9600, I get about 5 bytes of `0x00`, then nothing.)

If I disconnect the shield from the Arduino board then supply 5V to pin 2 or 3 (from an Arduino) and connect pin 5 of the DB/E9 to the Arduino's GND, I get output from both pins 2 and 3 (RX/TX) on the DB/E9 (regardless of which pin on the board is powered). The voltage between pins 2 and 3 on the connector differs by ~0.1V. Is this normal or is my circuit faulty? How do I test the continuity of the board/connector and diagnose and fix the fault?

In case it's of any relevance, I'm using an Uno with an SMD chip.

  [1]: http://linksprite.com/wiki/images/a/a6/SHD_RS232_V2_1.jpg

title: How do I Continuity Test/Troubleshoot a Linksprite RS232 V2 Shield?

Answers: 0


body:
I am trying to build an RC plane using an arduino UNO as the flight control board.

I found a code on the arduino forum for driving a 3 phase AC motor with an arduino.
http://forum.arduino.cc/index.php?topic=8642.0

I believe it will also work for brushless motors commonly used in RC airplanes.This will eliminate the need for an ESC (Electronic Speed Controller) which are pretty expensive.

Now I plan to use a single arduino board to communicate with the nrf2l01 rf receiver , control the servos as well as drive the brushless motor(mentioned above).

In each cycle of the code the arduino will be fetching data from the receiver,sending a pwm signal to the servos and setting which two phases of the brushless motor will be high and which one will be low.
Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino  fast enough to handle all this and it won't affect the speed noticeably.

title: Arduino UNO R3 as flight control plus brushless motor driver

Answers: 1

body:
> Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino fast enough to handle all this and it won't affect the speed noticeably.

This is very much an engineering question. How would one go about answering this?

One method is do a worst-case execution time measurement. Another method is to use control theory and estimate the minimum control frequency for the system (or sub-systems).

Let us assume (for this argument) that the required update frequency is 50 Hz (20 ms cycle time). That gives approx. 320.000 instructions (AVR @ 16 Hz) per control cycle.

The algorithm sketch above in your question is basically dominated by the time to receive the message. This depends on a number of factors; PLL start up, write message from AVR to NRF, transmission frequency, coding, etc, but also message loss and retransmission/acknowledgement. With 2Mbps and 5 byte address, 32 byte payload, and 2 byte checksum the transmission time is at least 300-400 us plus approx 100-200 us for the AVR/SPI to NRF communication. A total of 400-600 us which is well under the 20 ms.

What other design considerations are there? Motor interference on the communication, antenna design, range, protocol design, etc.

Cheers!


body:
Hey so basically I have my Arduino uno r3 setup with my RFID-RC522. I am looking to add this library to so I can use the examples alongside the ones I already have.
https://github.com/BoolLi/RC522_RFID_NFC_Utilities

I haven't been able to add them correctly and hope someone can help me out doing this. I currently have these ones already added and working correctly:
https://github.com/miguelbalboa/rfid

title: Adding Library to my sketchbook

Answers: 1

body:
1. Download https://github.com/BoolLi/RC522_RFID_NFC_Utilities/archive/master.zip
2. Copy the folder `RC522_RFID_Utilities` from the downloaded file to {sketchbook folder}/libraries. You can find the location of your sketchbook folder in the Arduino IDE at **File > Preferences > Sketchbook location**.
3. If you're using Arduino IDE 1.6.5-r5 or older restart the Arduino IDE. If using a newer version no restart is necessary.

The other three folders in the downloaded file are example sketches, not libraries. After installing the RC522_RFID_NFC_Utilities library following the instructions above you will be able to use them. You can store those folders anywhere you like but you should not put them directly under the libraries folder as this will cause warning messages about invalid libraries on every compilation. If you do want to bundle them with the RC522_RFID_NFC_Utilities library, as is customary, you can do this:

1. Create a folder named `examples` in {sketchbook folder}/libraries/RC522_RFID_NFC_Utilities
2. Copy the example sketch folders (NDEFFormattingExample, etc) from the downloaded file to the `examples` folder you created.
3. Restart the Arduino IDE if it's running.

The example sketches will now be accessible via **File > Examples > RC522_RFID_NFC_Utilities**.


body: I am building a quadruped robot, and I need to keep all four legs moving continuously and out of phase with respect to each other to produce a smooth gait and to prevent falling over. I wish to achieve this with 4 sets of 2 motors. Each set will move in the same way but not in sync. I have an Adafruit 16-Channel 12-bit PWM/Servo Driver - I2C interface - PCA9685 for this application. I have considered several implementations; delay () would be a poor choice because of the obvious delay between the current and next step in the gait cycle. I am also considering using ISR that will trigger when a certain time period passes, an estimated time to reach the desired position for example, but the interrupt method would not be much better than delay (). Another idea I have is to create a class that will receive the next position to move to for each leg and will continuously send the signal to the PWM driver. However, timing this would require some trial and error. Is there a conmon well-known method to send control signals with phase shifts?

title: What kind of control method in my code will allow me to control multiple servos with phase shifts

Answers: 0


body:
When you design an Arduino shield you want to make it compatible with a maximum number of shields that may be stacked with it on an Arduino (UNO). Considering the following two possible tradeoffs, which one would you consider the best:

- **Option A**: A shield that uses pins A0 and A1, where no other stacked shield can use those pins.
- **Option B**: A shield that uses SPI, where other stacked shields can only use pins 11, 12 and 13 in SPI mode.

Note: I'm asking this question for a project I'm designing called [Omzlo one][1]. It's an Arduino compatible board with builtin CAN bus networking. I'm hesitating between two prototype designs.

  [1]: http://omzlo.com/one

title: SPI or A0/A1: what is the best solution for pin allocation on an Arduino shield?

Answers: 0


body:
I am building a simple security system with my Arduino Uno. I have an `alarm()` function:

    void alarm() {
      tone(8, 3300, 200);
      delay(200);
      tone(8, 3000, 200);
      delay(200);
    }
When I call it in the `loop()` function like so:

    void loop() {
      alarm();
    }
the alarm sounds fine. I just want to be able to stop it. What I mean is, I want it to start the alarm (if it is off) when I call the `alarm()` function, then stop it when I call the `alarm()` function again. How can I do this?
**P.S. Can someone with over 150 reputation please make the `tone` tag?** I can't believe it's not here!

**Edit:** I tried the following code, but the alarm just kept going:

    bool alarmOn;
    void setup() {
      pinMode(8, OUTPUT);
      alarm(true);
      delay(5000);
      alarm(false);
    }

    void loop() {
    }

    void alarm(boolean call) {
      if (call) {
        alarmOn = true;
      } else {
        alarmOn = false;
      }
      while (alarmOn) {
        tone(8, 3300, 200);
        delay(200);
        tone(8, 3000, 200);
        delay(200);
      }
    }

title: Execute function until called again?

Answers: 1

body:
You can just have a variable that remembers whether the alarm is
supposed to be on or off. Let's call it `alarm_on`. Then:

    bool alarm_on;
    static void start_alarm() { alarm_on = true; }
    static void  stop_alarm() { noTone(); alarm_on = false; }

    void loop()
    {
        if (alarm_on) alarm();
        if (some_condition()) start_alarm();
        if (some_other_condition()) stop_alarm();
    }

For a better approach that allows you to sound the alarm without
blocking the whole program, see the [Blink Without Delay Arduino
tutorial](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay).

**Edit**: I just wrote (but did not test) a non-blocking version of this
alarm, based on a state machine and the timing technique from the _Blink
Without Delay_ tutorial. Here it is, as a class:

    class TwoToneAlarm {
    public:
        static const uint16_t HIGH_FREQ = 3300;
        static const uint16_t LOW_FREQ  = 3000;
        static const uint16_t TONE_DURATION = 200;

        TwoToneAlarm(uint8_t output_pin)
        : state(OFF), pin(output_pin) {}

        // Start the alarm.
        void start()
        {
            tone(pin, HIGH_FREQ);
            state = HIGH_TONE;
            last_tone_change = millis();
        }

        // Stop the alarm.
        void stop()
        {
            noTone(pin);
            state = OFF;
        }

        // Call this periodically to handle the tone changes.
        void update()
        {
            if (state == OFF) return;
            if (millis() - last_tone_change >= TONE_DURATION) {
                switch (state) {
                    case HIGH_TONE:
                        tone(pin, LOW_FREQ);
                        state = LOW_TONE;
                        break;
                    case LOW_TONE:
                        tone(pin, HIGH_FREQ);
                        state = HIGH_TONE;
                        break;
                    default:
                        break;
                }
                last_tone_change += TONE_DURATION;
            }
        }

    private:
        enum { OFF, HIGH_TONE, LOW_TONE } state;
        uint16_t last_tone_change;
        uint8_t pin;
    };

It could be used like this:

    TwoToneAlarm alarm(8);

    void loop()
    {
        if (some_scary_condition()) alarm.start();
        if (some_other_condition()) alarm.stop();
        alarm.update();
    }

Note that the whole program must be non-blocking (`delay()`-free),
otherwise the tone changes will not be done on time.

**Edit**: more about being non-blocking.

There is normally no reason for you to use `delay()` at all in your
program. The only reason for this function to exist is to help complete
beginners write their first blink-the-LED program. As soon as you start
writing anything non trivial, you should ban it from your vocabulary.
The Blink Without Delay tutorial is here precisely to teach you how to
get rid of `delay()` by using `millis()`.

In this particular case, however, the drawback of `delay()` may not be
too severe: if the alarm is sounding and you delay a tone change, you
may hear it as a glitch that breaks the rhythm of the sound. If the
delay is short enough, maybe up to 10 ms or so, you are unlikely to
notice it. Longer delays will be noticeable, and it's up to you to
decide whether you find them annoying or not.

It is possible to ensure a very steady rhythm despite the delays by
using interrupts, but this will cost you your 16-bit timer. Or you could
write your own implementation of `tone()` that does both the pin
toggling and the tone changes using a single timer. Any such option will
require you to learn about [low-level timer
programming](http://www.gammon.com.au/timers), which is significantly
more demanding than learning to use `millis()`.


body:
Functionality
-------------

I have written this code below for a buggy to continue moving forward until there is an obstacle which is <= 25cm both motors should stop.

Result
------

both motors stop when there is an obstacle which is <=25cm but the motors happen not to stop immediately when it comes across the obstacle please do find my code below is there something wrong with my code and how can I make it much better.

Code
----

    #define PING_PIN  12  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
    #define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

    //initializing left DC Motor
    const int in_1 = 2; // initializing the IN1 to Pin 2
    const int in_2 = 3; //initializing the IN2 to Pin 3
    const int EnA = 4;  //initializing pin 4 as pwm

    ////initializing Right DC Motor
    const int in_3 =5;  // initializing the IN3 to Pin 5
    const int in_4 = 6; // initializing the IN4 to Pin 6
    const int EnB = 7;  //initializing pin 7 as pwm

    // initialzing Ultrasonic sesor (Front view)
    const int trigPin = 8;
    const int echoPin = 9;

    //For providing logic to L298 IC to choose the direction of the DC motor
    void setup()
    {
        /// initialize serial communication:
        Serial.begin(9600);
        pinMode(EnA,OUTPUT);   //we have to set PWM pin as output
        pinMode(in_1,OUTPUT);  //Logic pins are also set as output
        pinMode(in_2,OUTPUT);
        pinMode(EnB,OUTPUT);   //we have to set PWM pin as output
        pinMode(in_3,OUTPUT);  //Logic pins are also set as output
        pinMode(in_4,OUTPUT);

        //--------------------------------------------------------------
        // Reading the signal from the sensor: a HIGH pulse
        //-----------------------------------------------------------------
        pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
        pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
        //pinMode(trigPin2, OUTPUT);// set the trig pin to output (Send sound waves)
        //pinMode(echoPin2, INPUT);// set the echo pin to input (recieve sound waves)
    }

    void loop()
    {
        int duration, Distance; // start the scan
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2); // delays are required for a succesful sensor operation.
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10); //this delay is required as well!
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);

        //---------------------------------------
        // convert the time into a distance
        //---------------------------------------
        Distance = (duration/2)/29.1;
        Serial.print(Distance);
        Serial.print("cm");
        Serial.println();
        delay(1000);
        if (Distance <= 25)
        {
            //Stopping Right and Left Motors
            digitalWrite(in_1,HIGH);
            digitalWrite(in_2,HIGH);
            digitalWrite(in_3,HIGH);
            digitalWrite(in_4,HIGH);
        }
        else {
            //Moving both Motors in a Foward motion - IN_1 = LOW , IN_2 = HIGH, IN_3 = LOW , IN_4 = HIGH
            digitalWrite(in_1,HIGH);
            digitalWrite(in_2,LOW);
            analogWrite(EnA,200); // Enablling the Right motor @ speed of 200
            digitalWrite(in_3,HIGH);
            digitalWrite(in_4,LOW);
            analogWrite(EnB,200);// Enablling the Left motor @ speed of 200
        }
    }

title: DC Motor's don't stop immediately

Answers: 3

body:
As some of the comments have mentioned, the `delay(1000);` is probably doing you in. What's happening there is the code does absolutely nothing but count 1000ms for that time, so if the obstacle comes within 25cm during that delay, nothing will happen until the delay is done counting and the if statement occurs.

If you still want it to serial print every second, but not have that effect of slowing your response, try a counting variable (I forget the actual name). It's like a flag that you count on, so for example, you could have `int printCount = 0;` and instead of the delay(1000);, you'd have

```
delay(1);
if(printCount > 999){
  Serial.println('Whatever');
  printCount = 0; //resets counter
} else{
  printCount++;
}
```

body:
As already stated, your problem is in the use of `delay()`, which
_blocks_ the program until the delay is over. When your program needs to
be responsive, you have to write everything in a _non-bloking_ manner.
The basics of non-blocking management of time are covered in the
[Blink Without Delay Arduino
tutorial](http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay), which I
strongly encourage you to read. Applying the technique of the tutorial
to your printing of the distance gives something like this:

    static uint32_t last_time_printed;
    uint32_t now = millis();
    if (now - last_time_printed >= 1000) {
        Serial.println(Distance);
        last_time_printed = now;
    }

I think the code is quite straightforward: you record the last time you
printed the value and, if it has been one second since last time, you
print it again.

You also have some other blocking calls in the section where you operate
the sonar. I would not worry too much about `delayMicroseconds()`: these
are really tiny delays, and your robot does not need to be _that_
responsive. I would worry about `pulseIn()` though: this function blocks
until it sees the end of the pulse, or until it reaches a timeout. The
default timeout is one second, which is way too large for this
application. Instead of relying on the default, you should specify a
timeout as a third parameter, as in

    duration = pulseIn(echoPin, HIGH, 50000);  // timeout: 50 ms

This would limit the range to about 8 m, which I think should be
more than enough.

Reading the sonar pulse in a completely non-blocking fashion is
possible, by using either an input capture unit or an interrupt, but I
guess it is not worth the trouble, as your robot can probably cope well
with being blocked for 50 ms.

body:
While I totally agree with the other answers on the issue of using a non-blocking timer, I would like to add another factor about motor braking from a purely "electrical" point of view.......

To "brake" a running DC motor, you need to short the two terminals. This will generate a back current in the coil which will reverse the magnetic field and stop the motor much faster than by just cutting off power to the terminals. This is not possible to implement using a Bi-polar H bridge motor driver like L293D. You need to use a MOSFET type H-bridge.


body: I am new to Arduino. For the project I am trying to do, I want to install the ESP8266 extension. But the additional boards manager URL option is missing from the Arduino IDE. What should I do to add the extension?

title: Additional boards manager option is missing from Arduino IDE

Answers: 3

body:
the URL is the following and the 1.8.2 IDE accepted it:
http://arduino.esp8266.com/stable/package_esp8266com_index.json

Good luck,
endre

P.s.: I found the answer/URL here:
https://arduino.stackexchange.com/questions/24391/no-response-to-at-commands/31297#31297

body:
You need to download and install a recent version of the Arduino IDE from:

http://www.arduino.cc/en/Main/Software

When you install the Arduino IDE using `apt-get` you get a very outdated and non-standard version, which does not have the Boards Manager feature. The reason for this is that the license documentation of the Arduino IDE does not currently meet the required standards for the package manager:

https://github.com/arduino/Arduino/pull/2703

body:
You stated in the comments that you are using version 1.0.5. This is a very old version. Go through you computer and make sure you uninstalled any old versions, then try to reinstall the ide.

Make sure you download from [arduino.cc][1], the official location to download the software.

  [1]: http://arduino.cc


body:
I am trying to connect an Arduino to a digital [accelerometer][1]. The Arduino receives commands from a mobile app and transmits over Bluetooth through hardware serial.
I also posted this question [here][2].

Code:

     #include < SPI.h >

    const int X8 = 0x06;
    const int Y8 = 0x07;
    const int Z8 = 0x08;

    /*
    bits
    1 0  mode 00: standby, 01: measurement
    5     1: spi 3 wire, 0: 4 wire
    4      self test
    3     2 glevel: 01 2g
    1 0  mode, 00 standby, 01 measurement
    */
    const int MODE = 0x16;

    const int STATUS = 0x09;

    //7 digital filter band width, 0 62.5 Hz, 1 125 Hz
    const int CONTROL = 0x18;

    bool isTesting = false;

    const int chipSelectPin = 7;

    void setup() {
        Serial.begin(9600);
        SPI.begin();
        pinMode(chipSelectPin, OUTPUT);

        //set up standby, spi 4 wire, 2g range,
        writeRegister(MODE, 0x04);

        //set up speed
        writeRegister(CONTROL, 0x00);

        delay(100);
    }
    void loop() {
        if (getSerial() == 't') {
            isTesting = true;
            writeRegister(MODE, 0x05); // 0000 0101- 0001 0101 0x15
            testing();

        }

    }
    void testing() {
        while (isTesting) {
            if ((readRegister(STATUS) & 1) == 1) {
                Serial.print((char) readRegister(X8), DEC);
                Serial.print("x");
                Serial.print((char) readRegister(Y8), DEC);
                Serial.print("y");
                Serial.print((char) readRegisterChar(Z8), DEC);
                Serial.print("z");
            }

            if (getSerial() == 'u') {
                isTesting = false;
                writeRegister(MODE, 0x04);
            }
        }
    }
    char getSerial() {
        if (Serial.available()) {
            char c = Serial.read();
            return c;
        }
        return 'x';
    }
    byte readRegister(byte thisRegister) {
        byte inByte = 0;
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        inByte = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inByte;
    }
    char readRegisterChar(byte thisRegister) {
        char inChar = 0;
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        inChar = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inChar;
    }
    void writeRegister(byte thisRegister, byte value) {
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(128 | thisRegister << 1);
        SPI.transfer(value);
        digitalWrite(chipSelectPin, HIGH);
    }

The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data. The data received when the sensor is on a flat surface is:

>x  y   z
>
>5 -11 74
>
>4 -19 74
>
>2 -9 69
>
>0 -8 68
>
>7 -16 68
>
>7 -11 73

[![enter image description here][3]][3]

When the self test is run, the results are:

>-5 -20 122
>
>-4 -22 122
>
>-1 -20 123
>
>-4 -20 123
>
>-5 -21 121
>
>-3 -18 123
>
>-8 -22 127

From the data sheet: "When the self-test function is initiated through the mode control register ($16),
accessing the "self-test" bit, an electrostatic force is applied to each axis to cause it to deflect. The Z-axis is trimmed to deflect
1g."

[![enter image description here][4]][4]

Is the data correct? How is it interpreted? If the z data during self test is 1g, shouldn't it have the same magnitude as when it is on a flat surface?

I adapted to code to get the 10 bits of data:

    const int X10_LSB = 0x00;
    const int X10_MSB = 0x01;
    const int Y10_LSB = 0x02;
    const int Y10_MSB = 0x03;
    const int Z10_LSB = 0x04;
    const int Z10_MSB = 0x05;

    //[...]

    void testing() {
            while (isTesting) {
                if ((readRegister(STATUS) & 1) == 1) {

                    int xData = (readRegister(X10_MSB) << 8) | readRegister(X10_LSB);

                    // checks if bit 9 is 1 and sign extends
                    if ((xData & 512) == 512)
                        xData = (0b1111110000000000 | xData);
                    int yData = (readRegister(Y10_MSB) << 8) | readRegister(Y10_LSB);
                    if ((yData & 512) == 512)
                        yData = (0b1111110000000000 | yData);
                    int zData = (readRegister(Z10_MSB) << 8) | readRegister(Z10_LSB);
                    if ((zData & 512) == 512)
                        zData = (0b1111110000000000 | zData);

                    Serial.print(xData);
                    Serial.print("x");
                    Serial.print(yData);
                    Serial.print("y");
                    Serial.print(zData);
                    Serial.print("z");

                }

The outputs for 2g measurement is:
>4 246 -183
>
>5 245 -183
>
>5 245 -182
>
>6 245 -181

For the self test:
>252 -20 -134
>
>253 -21 -133
>
>253 -21 -135
>
>253 -20 -135

the values for 8 and 10 bits of data don't correspond. What am I doing wrong?

Update: I rewrote the code to get the 10 bits of data with the LSB bits fisrt as per a comment:

Code:

         int xData =(readRegister (X10_LSB));
            xData = xData | (readRegister (X10_MSB)<<8);
            xData = xData << 6;
            int yData =(readRegister (Y10_LSB));
            yData = yData | (readRegister (Y10_MSB)<<8);
            yData = yData << 6;
            int zData = (readRegister (Z10_LSB));
            zData = zData | (readRegister (Z10_MSB)<<8);
            zData = zData << 6;

            xData /= 64;
            yData /= 64;
            zData /= 64;

The results for the sensor when on a flat surface:

>0 -4 71
>
>4 -11 70
>
>5 -13 70
>
>2 -12 70

The results when self-test is applied:

>-2 -19 123
>
>-2 -19 122
>
>-4 -20 122
>
>-3 -21 122

Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

  [1]: https://www.parallax.com/sites/default/files/downloads/28526-Freescale-MMA7455L-Device-Documentation.pdf
  [2]: http:// forum.arduino.cc/index.php?topic=465471.0
  [3]: https://i.stack.imgur.com/vyewv.png
  [4]: https://i.stack.imgur.com/ECEJQ.png

title: How to get and interpret digital accelerometer data?

Answers: 1

body:
> The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data

you are using it in 2g mode, so you have only 8bit of data.

> The data received when the sensor is on a flat surface is:

this is correct. You have a 8bit range (256 value, from -128 to +128) that map a range from +2g to -2g. So we have 256lsb/4g = 64lsb/g.
Motionless, the lenght of the gravity vector (sqrt(x*x+y*y+z*z)) must be close to 64. Of corse you need some offset and non-linearity calibration but the data seems fine.
Also if you look at the piece of datasheet you posted in table "Sensitivity", you will see they call the LSB "count", and they are in the range we calculated!

>When the self test is run, the results are:

again this is correct, if your sensor is flat in way the Gravity apply on the Z; what you see is the normal gravity (64) summing up to the self-test offset (64), giving you a nice ~128

>I adapted to code to get the 10 bits of data:
>
>Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

to use 10bit, you must set the full scale range to +-8g. If you look at the piece of datasheet you posted, table "Output Signal", you see how many bit are avaiable for each range.
If you think about it, how does the sensor know if you want to read 8 or 10bit? (remeber the DS say you must read the low register BEFORE high register!) if you read only 8bit, you would be loosing the 2msb, one rapresenting the sign and the other the most important bit that can change your result by 2^9=512
btw also you first 10 bit conversion is wrong as you flip the bit for 2's complement, but does nothing to the value bit.
The solution with bit shitf of 6 follow by divising is working but a bit strange to see. I would go for something more "standard" like

    int xData = readRegister (X10_LSB) | (readRegister (X10_MSB) << 8);
    if (xData | 0b0000 0010 0000 0000){ //if negative
        //keep 9 bit raspresenting the value and multiply by -1 to keep the sign
        xData = (xData & 0b0000 0001 1111 1111) * -1;
    }


body:
I recently bought a MPU 6050 that I plan to use with a drone. However I face some difficulties now because the MPU is not giving me steady results.

The results (pitch, roll, yaw) i get are not consistent. If I for example keep the chip stable on a table the value keeps increasing/decreasing even though it is not being touched/moved.

I also seem to get different results if i restart it even though i use it at the same angles.

Is something off with my code or is there anything else I need to do in order to fix this issue?

Appreciate any help I can get! :)

Here is my current code:

    #include <Servo.h>
    #include <Wire.h>

    int gyro_x, gyro_y, gyro_z;
    long acc_x, acc_y, acc_z, acc_total_vector;
    int temperature;
    long gyro_x_cal, gyro_y_cal, gyro_z_cal;
    long loop_timer;
    int lcd_loop_counter;
    float angle_pitch, angle_roll;
    int angle_pitch_buffer, angle_roll_buffer;
    boolean set_gyro_angles;
    float angle_roll_acc, angle_pitch_acc;
    float angle_pitch_output, angle_roll_output;

    void setup() {

    Wire.begin();
    Serial.begin(9600);

    setup_mpu_6050_registers();
    for (int cal_int = 0; cal_int < 2000 ; cal_int ++){

    read_mpu_6050_data();
    gyro_x_cal += gyro_x;
    gyro_y_cal += gyro_y;
    gyro_z_cal += gyro_z;
    delay(3);
    }

    gyro_x_cal /= 2000;
    gyro_y_cal /= 2000;
    gyro_z_cal /= 2000;
    loop_timer = micros();

    }

    void loop(){

    read_mpu_6050_data();

    gyro_x -= gyro_x_cal;
    gyro_y -= gyro_y_cal;
    gyro_z -= gyro_z_cal;

    angle_pitch += gyro_x * 0.0000611;
    angle_roll += gyro_y * 0.0000611;

    angle_pitch += angle_roll * sin(gyro_z * 0.000001066);
    angle_roll -= angle_pitch * sin(gyro_z * 0.000001066);

    acc_total_vector = sqrt((acc_x*acc_x)+(acc_y*acc_y)+(acc_z*acc_z));
    angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;
    angle_roll_acc = asin((float)acc_x/acc_total_vector)* -57.296;

    angle_pitch_acc -= 0.0;
    angle_roll_acc -= 0.0;

    if(set_gyro_angles){
    angle_pitch = angle_pitch * 0.9996 + angle_pitch_acc * 0.0004;
    angle_roll = angle_roll * 0.9996 + angle_roll_acc * 0.0004;
    }
    else{
    angle_pitch = angle_pitch_acc;
    angle_roll = angle_roll_acc;
    set_gyro_angles = true;
    }

    Serial.println(angle_pitch_output);
    Serial.println(angle_roll_output);

    while(micros() - loop_timer < 4000);
    loop_timer = micros();
    }

    void read_mpu_6050_data(){

    Wire.beginTransmission(0x68);
    Wire.write(0x3B);
    Wire.endTransmission();
    Wire.requestFrom(0x68,14);
    while(Wire.available() < 14);
    acc_x = Wire.read()<<8|Wire.read();
    acc_y = Wire.read()<<8|Wire.read();
    acc_z = Wire.read()<<8|Wire.read();
    temperature = Wire.read()<<8|Wire.read();
    gyro_x = Wire.read()<<8|Wire.read();
    gyro_y = Wire.read()<<8|Wire.read();
    gyro_z = Wire.read()<<8|Wire.read();

    }

    void setup_mpu_6050_registers(){

    Wire.beginTransmission(0x68);
    Wire.write(0x6B);
    Wire.write(0x00);
    Wire.endTransmission();

    Wire.beginTransmission(0x68);
    Wire.write(0x1C);
    Wire.write(0x10);
    Wire.endTransmission();
    Wire.beginTransmission(0x68);
    Wire.write(0x1B);
    Wire.write(0x08);
    Wire.endTransmission();
    }

title: MPU-6050, why is pitch, yaw and roll data not being consistent (value keeps getting higher/lower when it is stable)?

Answers: 0


body:
Following [this thermistor tutorial][1] i used 1k thermistors (and resistors) instead of 100k as in video.

 1. What difference does it make?
 2. What about 10k thermistors?
 3. Is it good idea to use 1k/10k/100k potentiometer instead of resistors to tune up readings?

  [1]: https://www.youtube.com/watch?v=-_XkGju35MI

title: What difference makes resistance of thermistors?

Answers: 3

body:
Skip to the end to get the easy answer!

Your choice of thermistor and bias resistor values depends on the following:
1.  How much current do you want to spend?
2.  How do you want the thermistor resistance to compare with the wiring resistance?
3.  How much filtering do you need?
4.  What kind of linearization do you want to apply?

1.  A lower value thermistor will pull more current than a higher value one.  More current means less battery life but also affects (2) and (3) below.

2.  For a given system wiring resistance, increasing the thermistor resistance reduces the measurement error due to the wiring. If your thermistor is 100 ohms (25C nominal) and your wiring is 1 ohm, then you would have a 1% error at 25C.  For an NTC (Negative Temperature Coefficient) thermistor, as it gets hotter and it resistance decreases, the wiring error  increases because the wiring represents a greater percentage of the total resistance.

3.  Filtering a resistive sensor in front of an ADC can be done by simply putting a capacitor across the ADC input.  As your sensor resistance increases, the size of the capacitor required decreases for the same cutoff frequency.  Even if filtering is not needed, be sure to check the ADC input impedance requirement as sample and hold circuits need their minimum AC input impedances to be satisfied as well as the DC input currents:  Too much sensor impedance does not go well with too high ADC input current.

4.  Unless you are using a platinum RTD with its linear response curve, your thermistor resistance vs temperature curve is going to be logarithmic where each end of the curve will be asymptotic.   This means you will get good resolution around the 25C reference temperature but at one end you'll get very little resistance change for a large change in temperature and at the other end you'll get a lot of resistance change for very little change in temperature.  By putting a resistor in parallel with the thermistor you can flatten out the curve to fit your measurement needs.

All this being said, your best bet is to put the thermistor curve into a spreadsheet and adjust the values until you get current consumption you can live with with a curve that gives you the information you need.  See this example for a 10K NTC sensor with linearization (Either the RT/R25 or RT-vs-Temp values are almost always listed in the data sheet for each thermistor):  [Spreadsheet for this graph][1]

[![enter image description here][2]][2]

  [1]: https://www.sugarsync.com/pf/D3258881_07979653_8498214
  [2]: https://i.stack.imgur.com/YkIWp.png

body:
The standard way to measure a resistive sensor is to make a voltage
divider with the sensor and a fixed resistance between Vcc and GND, like
this:

    Vcc
     │
     Rb
     │
     ├─── analog input
     │
     Rx
     │
    GND

where Rx is the resistance you want to measure and
Rb is a known bias resistance. The only unknown is the choice
of the bias resistance.

The simple rule of thumb is to choose a bias resistance close to the
typical values of the resistance you want to measure, as this will
optimize your measurement resolution. More specifically, the _relative_
measurement resolution, which could be stated as the number of ADC steps
you get per percent change in resistance, is maximal when Rx
= Rb, and decreases only slowly as Rx gets
further from Rb.

Now, one could argue that the _relative_ resistance resolution is not
always the best performance metric. You may want to maximize the
_absolute_ resistance resolution instead, or maybe the _absolute
conductance_ resolution. Each of these choices would lead to a different
choice of bias resistor. For the case of a thermistor, however, the
choice is pretty clear: the resistance varies almost exponentially with
temperature, which means that the _absolute_ temperature variations are
practically proportional to the _relative_ resistance variations. If you
want to use temperature resolution as a metric, you could go through a
tedious calculation only to find out that the optimal Rb is
darn close to Rx.

In short, if your thermistor is 1 kΩ at 25 °C, and you will
use it near 25 °C, then a 1 kΩ pullup will give you the best
temperature resolution.

Now, measurement resolution may not be the only issue you care about,
and you may want to sacrifice some of it in order to improve something
else. For example:

* Current consumption: a 1 kΩ thermistor in series with a 1 kΩ
  pullup will draw 2.5 mA (assuming Vcc = 5 V), which
  could rise to near 5 mA if it gets really hot. If you are running
  off battery power this could be an issue.

* Self heating: in that 1 kΩ + 1 kΩ configuration, the
  thermistor will dissipate 6.25 mW. I've seen the datasheet of a
  typical thermistor stating a thermal dissipation constant of
  7 mW/K. This means the measurement current would heat the
  thermistor to 0.9 °C above ambient temperature, which you would
  need to take into account in your temperature calculations.

Both of these issues would be mitigated by using a larger value for
Rb, only at the cost of measurement resolution. Switching to
a 10 kΩ thermistor would mitigate these issues without sacrificing
resolution.

body:
**Related:**

- [Selecting bias resistor for thermistor](https://electronics.stackexchange.com/questions/51908/selecting-bias-resistor-for-thermistor)
- [Choosing the correct thermistor](https://electronics.stackexchange.com/questions/187561/choosing-the-correct-thermistor)

---

I was trying to figure this out myself and was going to ask a question to verify my results. Since this question is so close, I'll just post my results as an answer and comments/votes can help me figure out if it's correct!

I've been going by this tutorial on [Adafruit](https://learn.adafruit.com/thermistor/using-a-thermistor) which, unfortunately, doesn't talk about *why* they use a 10k Ohm thermistor paired with a matching fixed/bias resistor.

So we're on the same page, here's the circuit used (voltage divider, pic taken from the second related answer above):

![therm volt divider](https://i.stack.imgur.com/OBgFE.png)

The formula used to get from resistance to temperature (taken from the Adafruit guide, which uses the [Steinhart-Hart equation](https://en.wikipedia.org/wiki/Thermistor)):

![wiki stein-hart](https://wikimedia.org/api/rest_v1/media/math/render/svg/3830f0ce29b9a3c827727585e7f3d444d9f4377b)

Here's the full code used to find the temperature based on the voltage divider created by the fixed/bias resistor and the thermistor:

    int pin_therm = A0;    // analog read pin
    float reading;         // hold thermistor resistance
    float stein;           // hold calculated temp

    int res_fixed = 10000; // 10k fixed resistor
    int res_therm = 10000; // 10k thermistor
    int therm_nom = 25;    // nominal thermistor temp
    int therm_b = 3950;    // thermistor B coefficient

    reading = analogRead(pin_therm);
    reading = (1023 / reading) - 1;
    reading = res_fixed / reading;

    // apply the S-H equation
    stein = reading / res_therm;    // (R/Ro)
    stein = log(stein);             // ln(R/Ro)
    stein /= therm_b;               // 1/B * ln(R/Ro)
    stein += 1.0 / (25.0 + 273.15); // + (1/To)
    stein = 1.0 / stein;            // Invert
    stein -= 273.15;                // convert to C

My aim is to measure around 150-250C, and I was curious what my resolution was after seeing very specific, "steppy" values when watching serial output. For example, as temps rose I'd see values like 202, 211, 222 but nothing in between.

I used [`R`](https://www.r-project.org/) to send all possible ADC values of 0-1023 through the equation to find the corresponding calculated temperature.

In my case, I modified the code above for the [Honeywell 135-104LAG-J01](http://www.mouser.com/Search/ProductDetail.aspx?qs=F1jq4PciTHurZ9eV%2bdokRQ==) thermistor I was using (T = 25C, B = 3974). Using the rule of thumb to match the fixed resistor, here's what I get with 100k Ohms, showing ADC values for 150-250C. It revealed that this setup would only give me ~5 readings over 200-250C!

[![100k-therm-100k-fixed][1]][1]

Going back to the math, it looked like I could drop the fixed resistance for better resolution. Here is the same 100k thermistor, but comparing the resolution obtained with 22k, 47k and 100k fixed resistors:

[![100k-therm_22k-100k-fixed][2]][2]

Using a lower fixed resistor, I have substantially more data points in my range of interest! We can simply compare the ADC ranges that make up this 150-250C span: ~20 for 100k and ~80 for 22k.

I'm not really worried about current consumption, but since it came up in the other answers, we can also increase the thermistor nominal resistance. Here's a plot breaking down by thermistor (100k - 1M) and matching fixed resistor (same 22k-100k values). I've removed the dots to make it less busy and the gray "mini-plot" titles are the thermistor values I looked at:

[![therm-vs-fixed][3]][3]

Lastly, to spare you from having to calculate the min vs. max ADC ranges covering the desired 150-250C range, here's a simple bar plot showing how many steps we get in this range.

[![therm-vs-fixed-steps-compared][4]][4]

So, with a 1M Ohm thermistor and 22k fixed resistor, we could have ~0.5C resolution in this high range (100C span divided by ~200 ADC steps).

---

I echo the suggestion of John Taylor to plot things out, but in my case, the [datasheet](http://pdf2.datasheet.su/honeywell fenwal/135-104lag-j01.pdf) *didn't* list the key values required for his spreadsheet. I think spelling out the Adafruit code and putting my `R` code at the end can help understand how to do this (approximated) in order to compare temperatures of interest vs. ADC steps which cover it.

---

As a last aside, I ran into the mention of "source impedance" on one of the related questions. I'm not an electrical engineer, but some answers suggest that there may be a time delay issue with reading ADC values when the circuit resistance is very high:

- [Required output impedance for ADC input?](https://electronics.stackexchange.com/questions/107741/required-output-impedance-for-adc-input)
- [Input impedance of Arduino Uno analog pins?](https://electronics.stackexchange.com/questions/67171/input-impedance-of-arduino-uno-analog-pins)

That said, since I'm measuring high on the temp scale, an NTC thermistor will have less than max resistance. We're also helped by the fact that the equivalent resistance is:

`1/((1/R_fixed) + (1/R_therm))`

So, even with a 1M thermistor an 100k fixed, our equivalent resistance at room temperature is:

`1/((1/1000000) + (1/100000)) = ~91k`

This will only reduce further at higher temps, but I thought I'd mention it for the sake of thoroughness!

---

Here's the R code used to generate the multi plot covering 100k-1M thermistors vs. 22k-100k fixed resistors:

    ## for plotting
    library(ggplot2)

    ## R kept wanting scientific notation, e.g. 10e5
    options(scipen=10)

    ## range for ADC reading
    inputs <- 0:1023

    ## create all combos of fixed resistor, thermistor, and ADC values
    combos <- expand.grid(res = c(22000, 47000, 100000),
                          therm = c(100000, 250000, 500000, 1000000),
                          adc = 0:1023)

    ## make sure it's sorted the right way
    ## also, give it a unique identifier per combo
    combos <- combos[order(combos$therm, combos$res, combos$adc), ]
    combos$grp <- paste0(combos$res, "_", combos$therm)

    ## calculate the temps for each thermistor/fixed res combo
    dat_lst <- lapply(unique(combos$grp), function(grp) {

      temp <- combos[combos$grp == grp, ]
      res <- unique(temp$res) / ((1023 / inputs) - 1)
      stein <- res / unique(temp$therm);
      stein <- log(stein);
      stein <- stein / 3974.0;
      stein <- stein + (1.0 / (25.0 + 273.15));
      stein <- 1.0 / stein;
      stein <- stein - 273.15;

      temp$temp <- stein

      return(temp)

    })

    ## combine results
    data <- do.call(rbind, dat_lst)

    ## some factor re-labeling to make plots more readable
    data$res <- factor(data$res,
                       levels = c(22000, 47000, 100000),
                       labels = c("22k", "47k", "100k"))
    data$therm <- factor(data$therm,
                         levels = c(100000, 250000, 500000, 1000000),
                         labels = c("100k", "250k", "500k", "1M"))

    ## reduce to only values in our range of interest
    data <- data[data$temp > 150 & data$temp < 250, ]

    ## the plot itself
    p <- ggplot(data, aes(x = adc, y = temp, colour = as.factor(res),
                group = grp)) + geom_line()
    p <- p + scale_x_continuous("adc value")
    p <- p + scale_y_continuous("calculated temp, C")
    p <- p + facet_grid(therm ~ .) + theme_bw()
    p <- p + scale_colour_discrete("fixed resistor")
    p

    ## to save it out
    png("./therm-vs-fixed.png", res = 200, width = 1600, height = 900)
    p
    dev.off()

  [1]: https://i.stack.imgur.com/J3ywb.png
  [2]: https://i.stack.imgur.com/d2gDk.png
  [3]: https://i.stack.imgur.com/aFPa5.png
  [4]: https://i.stack.imgur.com/RlzUT.png


body:
I recently bought [this][1] LED Strip. I got the 5M 3528 300LEDs SMD RGB Non-waterproof ones. However, I am not sure how to use them. On the strip there is four wires. I have tried supplying power to the wire that says it needs power and then I put ground to each of the other wires, but that only turns on a colour. How do I make it so I can choose what colour to use (Wiring, Code, etc.)?

  [1]: http://www.ebay.com/itm/1M-5M-30-60-144-LED-WS2812B-5050-RGB-LED-Strip-Light-Addressable-FS-/322040909995?var=&hash=item4afb2250ab:m:mkeWFwy2GkxLZNpd-1JGBKA

title: How to drive a strip of 12 V no-addressable LEDs?

Answers: 1

body:
**EDIT:** I'm sorry, I misunderstood! I assumed your LEDs were the 4pin serial version, whereas it makes more sense to me that they are the 6pin analog version. I must've brushed over the part where you said you grounded the colored wires and got that corresponding color.

You will provide 12V to the Power wire. To light the strip Red, you'd ground the Red wire, ground Blue for Blue, etc. Ground Red and Blue to light Purple, mixing colors etc etc.

So what if you wanted teal? or maybe a different shade of green? You'll need a way to generate PWM on the R, G, and B pins. Basically if you have an 80% duty cycle on Blue, that means it's only grounded 80% of the time. This corresponds to 80% brightness of the blue LEDs, then you could mix that with say 60% red and 10% green, or whatever you wanted to get a full 16 million colors. This is most easily accomplished with a microcontroller, and so I'll provide schematic and code tips for the simplest solution: an Arduino.

## Schematic

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/TmTpO.png)

<!-- End schematic -->

I chose Pins 9, 10, and 11 of the Arduino because they are all PWM; you can choose any PWM pins you want (denoted by ~ or # usually). Just reflect those changes in the sketch.

Arduino pins are also only capable of sinking about 40mA if I remember correctly, so you'll need to control some MOSFETs with the PWM. I find you can't go wrong with the IRFZ44N, but that's just what I've had available to me.

## Arduino Sketch

How you control it is up to you; sensors, potentiometers, networked, bluetooth, constant fade pattern, there's a slew of options. So this code will tell you the necessary functions, but from there it's a matter of programming and integration of whatever else you want.

    void setup(){
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);
    }

    void loop(){
      //255 -> 100%   ;   0 -> 0%
      analogWrite(9, 255); // turn red to 100%
      analogWrite(10, 0); // turn green to 0%
      analogWrite(11, 128); // turn blue to 50%
    }

If this doesn't work, please let me know and I'll fix it. I forget if analogWrite is okay with being called in a simple, unrestrained loop over and over, and I also forget if Arduino pins have internal pull-downs
  [1]: https://github.com/adafruit/Adafruit_NeoPixel


body:
I used this cheap impulse power supply, and it worked on Arduino with prototype board for some short time, but then it stopped while I felt a burning smell. Is "impulse" a wrong type of power supply for Arduino board?

[![Questionable PSU][1]][1]

*On that board I had 0,96" OLED display (0,08W) connected, 3 LED's, 2 thermistors, 1 buzzer. All is working fine while powered by USB cable from laptop.*

  [1]: https://i.stack.imgur.com/NjzSH.png

title: Is it wrong power supply?

Answers: 1

body:
A DC power supply with the right voltage is okay, also that one. You did connect it to the barrel jack ?

The most likely reason is that your Arduino board draws too much current for the voltage regulator on the Arduino board. Suppose you have an Arduino Uno with a servo motor or a lot of leds and they require 500mA. The voltage regulator would heat up with (9V-5V)*500mA = 2 Watt.
Can you find the voltage regulator on the Arduino board ? You can check if it is getting to hot by holding your finger on the voltage regulator. If you can keep your finger on it, then it is okay.
The voltage regulator should reduce the current too prevent that it gets too hot, but it is not hard to blow the voltage regulator despite that.

The DC power supply could be bad quality and could have an output voltage that is too high or has voltage peaks, or there is a leakage current from the mains. Do you have another power supply ?

I use a good quality and certified DC power supply of 7.5V. In the photo I see all the right certification labels, but I don't know if they are real.

What was connected to your Arduino board ? If nothing was connected, then you are in trouble, and it could be faulty DC power supply or a bad Arduino board.


body:
I have an Arduino Pro Mini as an ISP programmer with the ArduinoISP sketch running on it (19200 baud), and an addition in boards.txt that has a 'Standalone ATMEGA328 8MHz Internal' entry that specifies 8MHz and a bootloader file, along with some other things.

 I'm trying to upload a simple blink sketch to an ATMEGA328 (not 328p, though the issue persists with that board as well) with no external components (internal clock)

## The Problem

I can flash the bootloader no problem. I can also upload code the first time just fine. The problem is when I try to upload any different code _after_ the first time, it gives a verification mismatch error at a seemingly random byte, complaining that 0xsomebody != 0xsomeotherbyte (also seemingly always different). This usually causes the sketch the stop working, and the LED to behave erratically.

## IDE Verbose Outputs

[Verbose output for burning the bootloader](http://pastebin.com/AT6mDvFm)

[Verbose output for first upload of simple sketch: basically Blink.ino](http://pastebin.com/t05eQ3hC)

[Verbose output for second upload of modified sketch: changed first delay to 1200](http://pastebin.com/SR0nfunn) (side note: uploading an identical sketch doesn't give the verification mismatch error)

[Verbose output for sufficiently different sketch (four digital writes, ie heartbeat example)](http://pastebin.com/TAPp2aQd)

## The Sketch

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

    void loop() {
      digitalWrite(6, HIGH);
      delay(1100);
      digitalWrite(6, LOW);
      delay(400);
    }

## Bootloader Files

This is the boards.txt entry that I'm using:

    ##############################################################

    atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

    atmega328bb.upload.protocol=arduino
    atmega328bb.upload.maximum_size=30720
    atmega328bb.upload.speed=19200

    atmega328bb.bootloader.low_fuses=0xE2
    atmega328bb.bootloader.high_fuses=0xDA
    atmega328bb.bootloader.extended_fuses=0x05

    atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
    atmega328bb.bootloader.unlock_bits=0x3F
    atmega328bb.bootloader.lock_bits=0x0F

    atmega328bb.build.mcu=atmega328
    atmega328bb.build.f_cpu=8000000L
    atmega328bb.build.core=arduino:arduino
    atmega328bb.build.variant=arduino:standard

    atmega328bb.bootloader.tool=arduino:avrdude
    atmega328bb.upload.tool=arduino:avrdude

I've added this entry to `Users/me/Local/Arduino/packages/arduino/hardware/avr/1.6.17` as well as `Program Files(x86)/hardware/arduino/avr`

Here's the [HEX file](http://pastebin.com/7Qkp2CYi) for the bootloader incase that's useful as well

## The Programmer

Here's a schematic of the programmer:

[![Schematic-Programmer][1]][1]
[![ISP-Header][2]][2]

The solder jumper 'CAP1' is soldered closed.

And the connections to the ATMEGA328

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/8ABK2.png)

<!-- End schematic -->

And lastly, a photo of the setup: [![PCB-Programmer][3]][3]

Thanks in advance

  [1]: https://i.stack.imgur.com/zu2t4.png
  [2]: https://i.stack.imgur.com/AT59h.png
  [3]: https://i.stack.imgur.com/MTXIA.jpg

title: Standalone ATMEGA328: Verification mismatch on random byte on -subsequent- uploads only

Answers: 1

body:
I got some help from someone today. I oversaw a small detail when using the Arduino IDE with an ISP programmer: Hold shift when uploading to target the MCU at the end of the line rather than the MCU in the programmer.

So yeah, I hold shift when clicking upload and everything works great now. Sometimes it's the simplest things you'd never expect.


body:
## TARGET ##

The task I have taken as a challenge is to make a GPS-guided robot incorporated with features like Arduino for programming, ultrasonic sensors for obstacle avoidance and a GPS module to specify the way points location (from starting point to end point).

This robot should be able to avoid both static and moving obstacles while moving to its end point assigned from the GPS. I have found the robot  manoeuvring around both static and moving obstacles to be a bit challenging. I was wondering if there is an effective obstacle avoidance algorithm that I can use.

I will appreciate it if I could get some helpful suggestions and insights.

title: Obstacle avoidance algorithm

Answers: 2

body:
**The problem**

Given an unknown graph (or just world), a robot/person should be able to find a way between two points.

Pathfinding is often done on a known world, this [website][1] allows you to check out the different algorithms, which very much look like what you want to achieve.

Since you mentioned moving obstacles, you may also look at collision avoidance algorithms. But it depends on if the moving obstacles themselves also avoid collisions. To be able to avoid moving obstacles, you'll have to be able to know their location, direction and speed, to be able to calculate where you would collide (and how to avoid it). But usually, just braking whenever they get too close may just work (maybe even drive backwards if they get even closer).

**The approach**

So, we've got a startpoint and an endpoint. Our initial plan would be to travel straight from start to end, since this is obviously the shortest path.

But it would be ideal if there wasn't an obstacle, and for us to verify our approach, we'll just think of an obstacle. Let's say there is a wall right in front of you, what are you going to do? You can't see where it ends (I believe your robot doesn't), so you're just going to walk around it, you could choose a random way, (left or right, maybe even backwards)

**What algorithm**

Basically you want to get to the endpoint, so you're going to have an algorithm that has some kind of "fitness" based on how close you are to the endpoint.

You could:

 - Brute force: Try every single route, until you've found the way.
 - Right hand rule: [I've heard that][2], in mazes, if you always hold your right hand against the (right) wall, eventually you'll get to the end.
 - Greedy algorithm: Just move towards the point, if you can't go any furhter, choose whatever seems to get you closer. If nothing is getting you any closer, choose the route that moves away the least.
 - Heuristic algorithm: Move one way, until choosing another round will be more likely to be a solution, then choose to go down another lane. Until this one seems to be leading you away.
 - Search algorithm, like breadth first or depth first search, [check this video][3]

Just try some of the algorithms, to see which one works best. Or try to determine/explain why one algorithm is/should be better than the other.

  [1]: https://qiao.github.io/PathFinding.js/visual/
  [2]: https://en.wikipedia.org/wiki/Maze_solving_algorithm
  [3]: https://www.youtube.com/watch?v=bIA8HEEUxZI

body:
In a real world scenario, your robot would know its start point and end point but due the limited range of its sensors (radar/ sonar/ visual) and the inability to "see" around corners, it would never be able to plan a full route at the very start of its journey. It would need to start the journey, detect obstacles as it moved and then re-calculate its path as it proceeds to its destination.

[![Robot must avoid obstacles in its path and reach 'G'][1]][1]

There is a very simple weighted index algorithm called the '*Bubble Rebound Algorithm*' to accomplish this type of maneouvering developed by IOAN SUSNEA, VIOREL MINZU and GRIGORE VASILIU.

Be aware however, that this is NOT a 'Maze Solving' algorithm. It is only meant for avoiding obstacles.

But first I suggest you take a look at [my blog post][2] about the python simulation I wrote using this algorithm. This will help you understand what is going on and give you a broad idea about how the problem is solved.

I also made two very important modifications (which I have described in the blog) to the algorithm that help the robot actually reach a destination.

On the blog post you will find a link to the source code hosted at codeskulptor and a YouTube video demonstrating the algorithm at work.

  [1]: https://i.stack.imgur.com/pbXlq.png
  [2]: https://bayesianadventures.wordpress.com/2015/08/31/obstacle-avoidance-for-clever-robots/