text:
How to convert string to long?
There is String.toInt(), but no String.toLong() or the many other variations. Do I have to resort to atol(String.c_str()) or is there a better way to convert a String to a long?

Using atol(String.c_str()) looks OK to me. If there was a String.toLong() it would be written that way anyway.
In fact, looking at the code for String.toInt() that's exactly what it does:
long String::toInt(void) const
{
    if (buffer) return atol(buffer);
    return 0;
}

So the answer is: use String.toInt().

Interesting. I wonder why they didn't just call it toLong()??

So the answer is: use String.toInt().
Probably not, as this is the definition of a String method:
long String::toInt(void) const
The real work is:
atol(buffer);
ASCII to long.


text:
Is this a USBasp I can use with Arduino?
I bought the following USBasp off of Aliexpress.

The Arduino UDE doesn't recognize it. When I try to run avrdude with it, it says:
avrdude -cusbasp -Pusb -patmega328p
avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

Looking at the USB enumeration, it says:
USBHID:
  Product ID:   0xc8b4
  Vendor ID:    0x03eb  (Atmel Corporation)
  Version:  1.00
  Speed:    Up to 1.5 Mb/sec
  Manufacturer: zhifengsoft
  Location ID:  0x14200000 / 8
  Current Available (mA):   1000
  Current Required (mA):    100
  Extra Operating Current (mA): 0

Looking online, I see one blog post (http://www.sciencetronics.com/greenphotons/?p=938) about a device with the same VID/PID, and it says it can be reprogrammed but is not clear how to do it.
In particular, I know there is a jumper that I need to set to put it in self-programming mode but I can't figure out where to put this jumper. Once the jumper is in, I understand I just match the SPI pins and program it using the firmware.
Can someone help?

That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.
That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How to connect GPS to IMU?
I'm planning to connect GPS to IMU, Is't possible ? I tried my best to find an article that can help solving my curiosity.  How can i connect GPS and MPU to arduino uno?

Is not really connecting GPS to IMU, is more like you read GPS values, read IMU values and after apply what is called a sensor fusion algorithm.
One of the most common used sensor fusion algorithms is called Kalman filter (the Extended Kalman Filter more likelly). However, if you do not have some basis on control theory you may have more trouble in applying it.
here is a good example of use of this kind of sensors and fusion algorithms. It is also very commonly used in drones or autonomous vehicles.
The implementation will be specific to what you are trying to do.

thank you so much ! :) But how can i connect them to arduino ?

@GeorginaPattinson it depends on your sensor models. For instance this from Adafruit uses serial (Example tutorial). The most modern IMU digital combos usually use I2C/SPI interfaces (Example of MPU9150)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Measuring The Distance Using GPS programmed with Arduino
Who among here have tried measuring the before and after distance traveled using gps? I'm going to use the code from TinyGPS library's distance_between command without constant value of latitude and longitude,
like this:
static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002

I want to see that the first GPS latitude and longitude results is used as reference point.
How will I apply it on my code so that I could be able to get the distance I traveled? Please help me.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
 /*
   This sample code 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 = 4, TXPin = 3;
 static const uint32_t GPSBaud = 4800;

  // The TinyGPS++ object
TinyGPSPlus gps;

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

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

     Serial.println(F("FullExample.ino"));
     Serial.println(F("An extensive example of many interesting     TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. "));                    Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars     Sentences Checksum"));
     Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
           Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
}

void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
  printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  printInt(gps.location.age(), gps.location.isValid(), 5);
  printDateTime(gps.date, gps.time);
  printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
  printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
  printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
  printStr(gps.course.isValid() ?        TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

  unsigned long distanceKmToLondon =
   (unsigned long)TinyGPSPlus::distanceBetween(
     gps.location.lat(),
     gps.location.lng(),
     LONDON_LAT,
     LONDON_LON) / 1000;
     printInt(distanceKmToLondon, gps.location.isValid(), 9);

     double courseToLondon =
    TinyGPSPlus::courseTo(
     gps.location.lat(),
     gps.location.lng(),
     LONDON_LAT,
     LONDON_LON);

   printFloat(courseToLondon, gps.location.isValid(), 7, 2);

   const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

   printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

   printInt(gps.charsProcessed(), true, 6);
   printInt(gps.sentencesWithFix(), true, 10);
   printInt(gps.failedChecksum(), true, 9);
   Serial.println();

   smartDelay(1000);

   if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
   }

  // This custom version of delay() ensures that the gps object
  // is being "fed".
  static void smartDelay(unsigned long ms)
  {
  unsigned long start = millis();
  do
  {
   while (ss.available())
    gps.encode(ss.read());
    } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
     {
   if (!valid)
   {
    while (len-- > 1)
    Serial.print('*');
    Serial.print(' ');
    }
    else
    {
   Serial.print(val, prec);
   int vi = abs((int)val);
   int flen = prec + (val < 0.0 ? 2 : 1); // . and -
   flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
   for (int i=flen; i<len; ++i)
   Serial.print(' ');
   }
   smartDelay(0);
  }

 static void printInt(unsigned long val, bool valid, int len)
 {
  char sz[32] = "*****************";
  if (valid)
  sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
   sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
  }

  static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
  {
  if (!d.isValid())
   {
   Serial.print(F("********** "));
   }
   else
   {
   char sz[32];
   sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
   Serial.print(sz);
    }

    if (!t.isValid())
    {
    Serial.print(F("******** "));
    }
    else
    {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
    }

    printInt(d.age(), d.isValid(), 5);
    smartDelay(0);
    }

    static void printStr(const char *str, int len)
    {
    int slen = strlen(str);
    for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
    smartDelay(0);
    }

This is where those dreaded maths classes come in.
You know - the ones where no one paid attention because you thought "Where in the real world would I ever want to know this stuff?" Well, right here is were you would want to know this stuff.
The distance between two points on a 2D plane (i.e., a map) can be looked at as two vertices of a right-angled triangle.

Going from Start to Finish you travel X degrees across the globe and Y degrees up or down it.  So you can calculate the number of degrees between the two points with simple pythagoras' theorem:

In C it's quite easy to do those calculations.  You can find X and Y by subtracting the two longitudes and scaling it for the logitudinal circumference of the Earth where you are. You can do the latitudes in a similar way:
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0

24901 is the circumference of the Earth at the equator, and 24860 is the circumference of the Earth going through both poles. Both are in miles, so the result will also be in miles. The numbers are different for the two directions because the Earth is not a perfect sphere. It is somewhat flattened at the poles, and is called an oblate sphere.
It doesn't matter which one you subtract from which since, when you square them, they will become positive anyway:
float X2 = X * X;
float Y2 = Y * Y;

Then you can get the square root:
float Distance = sqrt(X2 + Y2);

So now you know how to calculate it without relying on some function in some library. It only takes a couple of lines of C code and you don't have to then know just how to use this unknown function provided by a library, and the theory will stand you in good stead for future similar projects.
Oh, and the code in full, in case you want it:
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0
float X2 = X * X;
float Y2 = Y * Y;
float Distance = sqrt(X2 + Y2);

This is good but along different lines of latitude, the distance isnt the same for a given angle, even for a perfect sphere. 15 degrees near the poles is shorter than 15 degrees near the equator. I think he should calculate arc length to get X using ((long2 - long1)*2*pi*Earth radius*cos (lat1)) / 360 and Y can be gotten similarly, except the cosine shouldnt be present

@Majenko Thanks for sharing your brilliant idea, but I already tried doing it, and unfortunately that won't work since we knew Earth is not perfectly spherical. What I am trying to know is how can I find the distance following the technical form of the Earth. Please see stated above.

D'oh, you're quite right. I had totally overlooked that. I will update the answer in the morning.

If you're going to use the circumference, then 2*pi shouldnt be present in the equation; its already a part of the circumference

@TisteAndii It's early yet and I haven't had my first sip of coffee.  Again, quite right.

Ah, unfortunately coffee isnt a thing here :(

I have been always frustrated from the missing double (64bit) type in Arduino world and hence the problem with properly calculating GPS distance, bearing and destination point.
The following library uses Float64 & Math64 libs and also adds some fast and very fast implementations of trigonometric functions and fast and regular versions of GPS GPS distance, bearing and destination point.
Feel free to use it - and any help in improving it is welcome !
https://github.com/vtomanov/Gps64


text:
If I use a biasing circuit for a signal going into an analog input pin, will it affect the ADC operation?
If I have a single 100Hz AC signal biased by two 1 M-ohm resistors (as per schematic below), and then output to an Arduino UNO analog input pin, with the UNO sampling at around 1 kHz using delays, would there be any issues with the ADC result?

(Source of schematic: http://tinyurl.com/ycprqsdx)
From the Atmega328P's spec sheet (the UNO's microprocessor) it recommends an output impedance of 10 k-ohms or less, as shown below.
If I used the pair of 1 M-ohm resistors as a biasing circuit and then deliberately slow down the sampling with delays (i.e.: in loop, do analogRead, then delay, then do analogRead, etc.), would it still be okay?

It will give bad results. You're not slowing down the sampling, you're taking samples at a longer interval - a very different thing.
The Arduino uses a Successive Approximation ADC. That uses a clock to control the output of a DAC and compare that voltage with the incoming voltage stored in the S&H capacitor.
In order for the S&H capacitor to get charged to the correct level it has to be connected to the GPIO pin long enough. Since there is only one ADC and 6 analog input pins, it goes through a MUX first.
The delay that needs increasing is the delay between the pin being connected to the capacitor and the capacitor being connected to the ADC.  This is called the acquisition time.
The analogRead() function does these basic operations in sequence:

Connect the SHC to the GPIO pin through the mux.
Wait
Disconnect the SHC from the GPIO and connect it to the ADC
Clock each bit from the comparator to the result registers.

Putting a delay between each analogRead would just delay the connecting of the SHC to the GPIO pin, not increase the time it's connected to the GPIO pin.
You would have to manipulate the ADC registers to do your own sample timing.  Or, just reduce your output impedance.

Thanks for the clarification between sampling interval and taking samples at a longer interval. I guess I can also reduce the output impedance with an op-amp-based buffer.

Yes, you could. Or replace the 1MΩ resistors with 10kΩ ones.

My concern with doing that is that the 100 nF with 10kΩ would effectively make a high pass filter cutting off at ~159 Hz; for my application, I do need those lower-frequency components too.

Increase the capacitor to compensate then?

Right, got it. So my previous 100 nF with 1 MΩ can be replaced by a 10 uF with 10 kΩ.

Yup. T=RC, so increase C and decrease R and T stays the same.

Adding capacitance to the input will help compensate for the high impedance but it also forms a low pass filter. For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz. That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino with Figaro TGS sensor
I am going to use few Figaro TGS sensors, which including TGS2600, 2602 and 2620 with my Arduino. I referred to the datasheet and found that these sensors need more than one voltage source. May I know the correct way to connect them to my arduino? (Arduino Mega or Uno probably)...(beginner here)

Please update your question with links http://www.figarosensor.com/products/entry/tgs2600.html , http://www.figarosensor.com/products/entry/tgs2602.html , http://www.figarosensor.com/products/entry/tgs2620.html and write the voltages that each one needs. What have you read in the datasheet that makes you think that more than one voltage is needed ? I can not find that in the datasheets.

It needs 5V for the heater and 5V for the detector circuit. What makes you think that is two different voltages? Does 5 not equal 5 in your universe?

Opps...I made a stupid mistake...So for http://www.figarosensor.com/products/2602pdf.pdf (TGS2602 datasheet), sensor pin 3 and 4 simply connected to the voltage source and pin 1 and 2 simply to the ground (pin 2 with load resistor)...am I right?

Yes, correct. The sensor requires an accurate 5V. That means when you use only a USB cable to power the Arduino and the sensor, the voltage can vary a lot and the result will be unreliable.

Maybe I can use a 5V voltage regulator

I think I will use a 9V barrel jack adapter as my power supply...for more stable readings from my sensor

By the way, I found some information online states that if using 9V barrel jack adapter as my power supply, the use of 5V pin on arduino might overheating the voltage regulator built in...Any suggestion on better way as my power supply? ( I think 9V battery does not provide enough current for the sensors)


text:
Arduino with sensor
I am new to arduino and sensor. I am going to do a project related to E-nose to detect children breath odor. I wanted to use few sensors including
Figaro TGS2602, TGS2600, TGS825, TGS2620 and TGS2180 together with arduino. May I ask is it possible for an Arduino Uno or Mega to support all these 5 sensors at one time?

No (Can't)! If your signal threshold values and your step value are not the same, you can't read them all from an analog input. Analog sensors show distorted values in frequency oscillations, which increases the cost of the power supply, so you can solve this event with an additional battery (i.e. AC-DC reducers are not healthy in analog circuits and require complete isolation).

They are all analog sensors, so yes - you have 6 analog inputs on an Uno and 5 analog sensors, so you have one spare analog pin to do something else with if you want.

Thanks for the answer!!! By the way, is it logic if I use these 5 sensors for my breath odor detector project? Because from what I know some contents in breath might not match the sensitivity for these sensors. I have been told that research project might not necessary to have positive results. I just curious what result these 5 sensors bring if I use it.

All the datasheets for those devices have pretty graphs detailing the sensitivity. If that matches up with your requirements then they will work. If it doesn't then they won't.


text:
Gas Sensor output voltage to concentration
I am using figaro tgs gas sensor (2600, 2602 and 2620) to sense breath from human. What I obtained is the output voltage. However, I would like to convert the voltage to concentration in ppm? Since these gas sensors can sense more than one gas. Is there any way?? Thanks.

I would like to convert the voltage to concentration in ppm?
Is there any way??

the datasheet for those devices would have the answers for you. Generally, you read the datasheet BEFORE deciding on using them or not. not that otherway around.

This is one of the datasheet. I have calibrated it using the clean air factor in datasheet and got the Rs/R0 ratio. However, from there, I not sure how to find the concentration for each gas.

The conditioning is 7 days. Turn it on with all wires connected and wait 7 days. Then you have to calibrate it with a known concentration of the gas that you want to measure. You might also use the data from the datasheet, for example from the "sensitivity characteristics" graph. A single sensor detects multiple gasses, and there is no way to tell which gas it is. If you combine more than one sensor, you might distinguish a few different gasses, but that is not in the datasheet. I think you have to use a known concentration of a gas and collect the data from all sensors.

Thanks for the reply. I refer to https://jenslabs.com/category/electronics/ketosis-detector/ and http://sandboxelectronics.com/?p=165  For the first link, I not really sure where the value got to convert from resistance ratio to ppm...The second link use the gradient in the datasheet for each line and generate the ppm value from ratio got. Can it be use?

The TGS2600, TGS2602 and TGS2620 are not designed to breath on. The TGS822 (in the first link) is. In the datasheet is a graph of ppm versus Rs/Ro. The most common (and also cheapest and poor quality) are the "mq" gas sensors. You can find examples for ppm when you search for: arduino mq gas sensor ppm

But 2600, 2602 and 2620 also show the Rs/Ro versus ppm graph. I can obtain the Rs/Ro ratio, will it means if I use the same method shown in the link I can get the concentration as well?

I think that is specific for the TGS822. Every sensor might have the same shape of the curve, but for the TGS822, the calculation is split into two parts. A calculation for the resistance below 3600Ω and a calculation above that. I don't know if the 3600Ω can be used for other sensors. The overall accuracy is not very good, perhaps a simple calculation will do.

If you want to measure concentrations of individual gases you would have to separate them and detect them separately using a chromatography column. In the case of gases this is known as gas chromatography (GC) and for liquids it's LC, with the most popular one being HPLC (high performance liquid chromatography, or sometimes called high pressure liquid chromatography). This is actually a really fun thing to do as a project and I stumbled on this question because I want to make my own GC using the sensor you mentioned.
The principle is fairly simple. Most modern GCs have a carrier gas, usually an inert gas like nitrogen or helium, at a steady flow rate and it passes through a column. You inject your sample into this carrier gas flow and then your sample also passes through that column.
Most columns are packed with a material like silica gel or long alkanes (usually around 18 carbon atoms). Silica has more affinity for polar compounds (like alcohols) while alkanes have more affinity for non-polar compounds like butane, hexane, etc.
If you have a mixture of compounds, like in human breath or lighter fuel, they pass through that column at different rates depending on affinity for your stationary phase (the column) and also size of the molecules (heavier molecules like hexane pass through it more slowly than the lighter propane just due to size).
At the end of the column you get the gases coming out separately, depending on the quality of your separation with the ones being less retained by the column coming out first.
A small problem with this is that the separation takes time and can take up a lot of time depending on conditions. Most GCs operate at about 200 degrees Celcius to increase the speed but also to make sure that everything actually is in the gas phase.
For a hobby project I just want to do it at ambient temperature first using lighter gas (which I know is a gas at room temperature) and for a column I will use bentonite clay, which they used back in the old days before silica and it's cheap. Kitty litter is made from bentonite clay as well so it's easily available. As a carrier gas just normal air using for example an aquarium pump or other small membrane pump.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Passing struct from main.cpp to a class
Sorry if this question been posted but I couldn't find the one that matches my issue. I couldn't pass my struct values from the main file to a class. Any ideas? I got this:
error: no matching function for call to 'ODriveArduino::SetParam(R_motor_params&)'

Main.cpp:
#include ODriveArduino.h
ODriveArduino odrive(Serial1);

struct L_motor_params{
 int axis=1;
 float vel_Gain= 2.5f/10000.0f ;
 float pos_Gain= 40.0f;
 float vel_Int_Gain= 0.0f/10000.0f;
};
struct R_motor_params{
 int axis=0;
 float vel_Gain= 2.75f/10000.0f ;
 float pos_Gain= 40.0f;
 float vel_Int_Gain= 0.0f/10000.0f;
};

void setup() {
  struct R_motor_params M;
  odrive.SetParam(M);
}

ODriveArduino.h:
class ODriveArduino {

private:

    struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
    };

public:
    ODriveArduino(Stream& serial);

    // Commands
    void SetParam(struct motor_Params M);

 }

ODriveArduino.cpp:
#include "ODriveArduino.h"
template<class T> inline Print& operator <<(Print &obj,     T arg) { obj.print(arg);    return obj; }
template<>        inline Print& operator <<(Print &obj, float arg) { obj.print(arg, 4); return obj; }

ODriveArduino::ODriveArduino(Stream& serial)
    : serial_(serial) {}

void ODriveArduino::SetParam(struct motor_Params M){
  Serial1 << "w axis" << M.axis << ".motor.config.pos_gain " << M.pos_Gain << '\n';
  Serial1 << "w axis" << M.axis << ".motor.config.vel_gain " << M.vel_Gain << '\n';
  Serial1 << "w axis" << M.axis << ".motor.config.vel_integrator_gain " << M.vel_Int_Gain << '\n';
}

you have 3 struct types motor_Params, R_motor_Params, L_motor_Params, but you want the L and R to be variables of type motor_Params

@Juraj R_motor_Params and L_motor_Params have slightly different values. I want to pass them to SetParam. I figured, to do that, I need to have an identical struct in ODriveArduino.h so that SetParam knows what to expect. Obviously that didn't work. I'm not sure what I'm missing.

motor_params L_motor_params; creates a variable of type motor_params1 named L_motor_params

It looks like you're trying to implement polymorphism without implementing polymorphism.
What you have done is create three completely independent structures and assumed that they will all work together just because they are the same size, with similar names, and fields named the same. That's not the case. They are all completely separate.
Instead you want just one structure but to use it multiple times to create different variables:
// from ODriveArduino.h, but move *outside* the class
struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
};

// in your code
struct motor_Params left_params = {
    1, 2.5f/10000.0f, 40.0f, 0.0f/10000.0f
};

struct motor_Params right_params = {
    0, 2.75f/10000.0f, 40.0f, 0.0f/10000.0f
};

// later
  odrive.SetParam(left_params);


text:
Ethernet socket impedes adding shields
I just bought a KEYESTUDIO W5500 Ethernet Arduino without realizing that the Ethernet socket on the board impedes adding any additional shields to the device because:

Horizontally the socket runs right up next to the shield connector sockets
Vertically the socket is a good 1/4 inch higher that the shield connector
sockets

Is there a good solution for extending the shield connector sockets vertically so that they clear this Ethernet socket?

what shield do you want to put up? you do not have much free memory for more libraries

@Juraj The main shield I want to add is a screw terminal I/O card. But it's the mechanical clearance I am concerned about, not the memory

Reverse the order of the shields: Uno | Terminal I/O | Ethernet?

@JRobert The board has built in Ethernet - there is no Ethernet shield

Oops, missed that. Back to extra headers!  :)

Plug some of these into the Arduino headers to add extra space.
They come in different lengths and can be cut to the required number of pins.
They also come in different pin lengths.
Google long tailed pin headers.

After googling a bit I found Arduino Stackable Header Kit which is more descriptive of what I want.


text:
ArduCam ESP8266 and (Not-Mini) OV2640 Camera Module interface?
I bought ArduCam ESP8266 and a OV2640 Module. However it is not the mini-version. At the time it didn't seem like it was necessary.
I might have made a big mistake here.
The board has 8 female pins specifically for the camera module. But the OV2640 module has 20 male pins. A mini-version of the same camera leaves 8 pins, and has a nice interface.
I might have to send this back and get that one, but I want to know if it's possible to simply use this one and wire it up with certain pins instead?
Links to the two products to be specific:
http://www.arducam.com/camera-modules/2mp-ov2640/ (Camera)
http://www.arducam.com/arducam-esp8266-uno-board-arduino-camera/ (Board)
Thanks for your help,
Fred

No, you can't "mix and match" like that. The 8-pin header has I2C and SPI on it for a "cooked" video interface. The 20-pin interface has the "raw" camera CSI interface.
The difference is, the mini version has its own small video processor and FIFO chip on it which processes and buffers the video image allowing you to take a picture then slowly stream that data back through to the slow Arduino at a speed it is comfortable with. The non-mini version doesn't have that and relies on the host controller board having enough power to process a live CSI video signal, which the Arduino cannot do.

Okay. Thanks for the info.
From the data sheets I understand what you mean now. I'm going to have to send this back then...
I was wondering about the rest of the pins of the board. I see they are linked to certain elements of the 8-pin header. Would the board still have some pins (say 3) free for extra PWM motor controllers?
It seems pins such as D4 D3 may not be used, but I'm not 100%...
Thanks,
Fred

It looks like they have a lot of pins doubled up on that board. I'd be surprised if you could really use the Uno-format headers for anything much TBH. That's the problem when you choose the wrong chip for the job. That board should have been made with a completely different chip on it so that it had enough pins to actually provide the GPIO it purports to provide. It's really not clear from their pinout diagram which pins can be used for PWM, and quite unclear that you only have a fraction of the actual GPIOs that it looks like you have. Even within the Uno footprint headers themselves ...

... there is a massive amount of pin duplication. You would probably be better off interfacing the Arducam Mini manually with a more capable board, such as a Mega2560, which has more pins available so you don't have any doubling up. After all, it's only 8 wires to route, and that 8-pin header isn't anything special.

I have just done a count: you have a massive 11 GPIO in total on that board. 6 are used by the 8 pin header. 1 is used by the SD card. That leaves a grand total of 4 GPIOs that are of any possible use - GPIO0 or GPIO1 (depending on board version), GPIO2, GPIO3 and GPIO15. That's less than useful really - and only one analog input as well. As I say, better off using a more capable board and interfacing things like the camera, WiFi, etc manually.

Lets say I didn't use the SD card. And that I wanted to two 3 servos and two motors. Doesn't that require 5 GPIOs left? Aren't all GPIO's PWMs?
What would happen if I tried to use the GPIOs for something?
Another options is to just get another small ESP8266 Dev board like Wemos, which is relatively cheap. Another battery I guess but maybe easier?

I think the ESP8266 does purely (timer based) software PWM. I would be tempted to add a real Arduino into the mix for your hardware interfacing. Use the ESP8266 purely for the WiFi and the camera, and as a "master controller". That then interfaces to a real Arduino through some serial protocol of your choice (I2C maybe?) to perform real hardware PWM and give you lots more GPIO available. Kind of like an IO-expander-on-steroids.

In the end I bought another board - nodeMCU Esp with motor break out. It does 2 DC motors and a bunch of servos, as well as a stepper. So I Think it's a lot better. I'll have to see about integrating it into something like you said later too.


text:
Nick Gammon's Hex Converter Error
I'm trying to add a bootloader hex to Nick Gammon's Atmega Board Programmer sketch, and I can't seem to get a hex file to convert.
I need to convert "Arduino-usbserial-atmega16u2-Uno-Rev3.hex", but that wasn't working so I thought I'd try converting one that's already used in the sketch, "Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex", but that's not working either. I've followed the instructions from http://www.gammon.com.au/bootloader
I've tried it using Wine and Paralells. Clicking the copy button when using Wine causes the program to stop responding.
Here is a screenshot of the error:

Thank you

Why do you need to do this? Normally you don't need to reflash the Atmega16U2 chip.

I work at a university and I'm making a shield that plugs into the top of dead Arduinos the see if they can be fixed with a simple re-flash of the chips, which is usually the fix. I used your sketch to put the Atmega16U2 chips into DFU mode, but it still requires me to connect the Arduinos to a computer to finish off the fix. It'd just be easier to put the working hex file on the chip in the first place.

I have another sketch which uploads a hex file from a SD card. The size of the full file for the Atmega16U2 may not fit into the bootloader programmer PROGMEM. However you could easily reflash the entire chip using the hex-uploader sketch. In fact you probably don't need the bootloader on the Atmega16U2 - because that is only used for entering DFU mode.

I can't reproduce that.
My apologies - I couldn't quite read the error message in the screen dump. What you got was:
Don't know end address for 0
Please add to table: end_addresses
Run-time error
World: smaug2
Immediate execution
[string "Immediate"]:96: Cannot continue
stack traceback:
        [C]: in function 'error'
        [string "Immediate"]:96: in function 'process'
        [string "Immediate"]:134: in main chunk

The relevant error is the first line. That file has code for address 0 - which is not part of the bootloader. It tries to detect bootloader addresses, and zero is not one of them. Looking at the start of the file I see this:
:1000000090C00000A9C00000A7C00000A5C000006B
:10001000A3C00000A1C000009FC000009DC0000060
:100020009BC0000099C0000097C0000048C40000B9
:100030000CC4000091C000008FC000008DC0000003
:100040008BC0000089C0000087C0000085C0000090
:1000500083C0000081C000007FC0000002C100001A
:100060007BC0000079C0000077C0000075C00000B0
:1000700073C0000071C000006FC000006DC00000C0
:100080006BC0000069C0000067C0000065C00000D0
:1000900063C0000061C000001201100102000008EE
:1000A0004123430001000102DC0109023E0002017C
:1000B00000C0320904000001020201000524000111
:1000C0001004240206052406000107058203080027
:1000D000FF09040100020A000000070504024000B5
:1000E00001070583024000010403090432034100B3
:1000F00072006400750069006E006F002000280027
:100100007700770077002E006100720064007500B0
:1001100069006E006F002E0063006300290000007C
:10012000000011241FBECFEFD2E0DEBFCDBF11E033
:10013000A0E0B1E0ECEAFFE002C005900D92A6312C

In particular the format is:
 :10 0000 00 90C00000A9C00000A7C00000A5C00000 6B
  ^  ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^
len  addr TT   data                          sumcheck

So this file includes code for the Atmega16U2 as well as the bootloader.
My sketch is not designed to program non-bootloaders (it is a bootloader programmer after all).

Scroll down that page for how to reprogram the Atmega16U2 chip.
The bootloader programmer sketch (as published) will put the bootloader onto the Atmega16U2. Then follow the instructions on that page, or on this page, below, for entering DFU mode and uploading the main part of the code (not the bootloader part).

Entering DFU mode
If you have just flashed the bootloader using the bootloader programmer sketch then it should enter DFU mode, visible because the pin 13 LED flashes rapidly.
If not, enter DFU mode by shorting together Reset and Ground briefly with a screwdriver or similar. They are the two left-most pins visible in the image above, nearest to the Reset button and below the hole on the board.
(Don't keep them shorted, just a brief touch should do it).

Once in DFU mode, you should see it appear as an Atmel USB device, if you type lsusb (on Linux):
$ lsusb
...
Bus 003 Device 092: ID 03eb:2fef Atmel Corp.
...

A Uno which is not in USB mode might look like this:
$ lsusb
...
Bus 003 Device 090: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
...

(or not appear at all if there is no firmware on it).
If you are using Ubuntu or similar you can obtain the DFU programmer as follows:
 sudo apt-get install dfu-programmer

You can obtain the code for the firmware from here:
http://gammon.com.au/Arduino/Arduino-atmega16u2-Uno-firmware-Rev3.hex
(RH-click and "save as" to put a copy on your hard disk).
Assuming you place that firmware in the current directory of your terminal window, you can now flash the code as follows:
sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

You should see a message like:
Validating...
4034 bytes used (32.83%)

Now you can unplug the USB cable, plug it back in, and the USB interface should be back to factory settings.
For other operating systems, such as Windows, you should be able to get a copy of the DFU programmer from:

https://github.com/dfu-programmer/dfu-programmer
http://dfu-programmer.github.io/

Why am I getting the same error message when I try and convert Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex, the same used in your bootloader programmer sketch?

Being a combined file it would start at address zero as well. I would have stripped out the low-order bytes from the .hex file, leaving only the bootloader part.


text:
Digital Potentiometer and Motor Speed Controller
I'm trying to get a Chinese 20A DC Motor Speed Controller working with a MCP42100 Digital Potentiometer. The analogue potentiometer supplied was 100kOhm. I have programmed my arduino with the following code:
#define DATAOUT     11
#define DATAIN      12       //not used
#define SPICLOCK    13
#define SLAVESELECT 10
#define NOTEON      9
int potValue = 255;
float potInputValue;

void SPIInitialize()
{
  byte clr;
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK, OUTPUT);
  pinMode(SLAVESELECT, OUTPUT);

  digitalWrite(SLAVESELECT, HIGH); //disable device

  SPCR = (1 << SPE) | (1 << MSTR);
  clr = SPSR;
  clr = SPDR;
  delay(10);
}

char SPITransfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1 << SPIF)))   // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

//--- MCP42100 code

byte SetPot(int address, int value)
{
  // Slave Select set low to allow commands
  digitalWrite(SLAVESELECT, LOW);

  // 2 byte command
  SPITransfer(0x10 + address);   // 0x10 = 'set pot' command
  SPITransfer(value);            // Value to set pot

  // Release chip, signal end transfer
  digitalWrite(SLAVESELECT, HIGH);
}

//--- Application code

void setup()
{
  SPIInitialize();          // Initialize the SPI interface

  Serial.begin(9600);
  delay(25);
  Serial.println("Type a resistance between 0-100 kOhms above.");
}

void loop()
{
  if (Serial.available() > 0) {
    // read the incoming byte:
    potInputValue = Serial.parseInt();
    float potValue = (potInputValue / 100.0) * 255;
    Serial.print("Value: ");
    Serial.print(potValue);
    Serial.print(", Resistance: ");
    Serial.print(potInputValue);
    Serial.println(" kOhms");
    SetPot(1, potValue);
  }

}

Here is a picture of my setup:
Currently at a resistance of 0 kOhms the motor runs at full speed, as it should do and this is how it reacts with the analogue potentiometer. At a resistance of 100 kOhms, the motor (in this case a computer fan) still has enough juice to spin, until I stop it with my finger, but then it doesn't spin without a little push. With the analogue potentiometer, at 100 kOhms the motor received no juice to spin.
Here is a link to the speed controller: http://www.ebay.co.uk/itm/301366805277?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
The speed controller appears to use a 555 timer.
What am I doing wrong with the digital potentiometer to make it so it doesn't behave the same way as the analogue potentiometer?

You haven't told us anything about the motor controller or what sort of inputs it expects, or given us a schematic, so I don't see how anyone could really answer this.

I'd suggest using a motor driver board that was explicitly designed to be interfaced with from a MCU - rather than trying to jury-rig this one. Alternately, you could use a DAC on the middle wire of the potentiomter, instead of trying to use a digipot.

The MCP42100 does not appear to be an appropriate digital pot for this application.
Without a schematic of the motor controller it is hard to tell, but a good guess would be that the digital pot is seeing voltages higher than the supply voltage you are feeding it, and higher than the maximum supply voltage of the digital pot (5.5V; 7.0V abs max). I don't see a voltage regulator on the motor controller board, nor would one be necessary for a low-end design. Probably just a PWM using a 555, as you say.
To make this work you probably need a different type of digital pot - one that can accept logic level inputs and has a higher supply voltage (12V + some margin). You also typically actually have to feed it the higher supply voltage (and be careful that nothing shorts and ruins the micro board).
Otherwise the input protection networks on the digital pot conducts more current than you would expect.

I'm not sure such a digipot exists, and a DAC is probably a better choice anyway.

Hi, @NickJohnson. I don't think a DAC (other than maybe a 4-quadrant multiplying DAC that can accept a 12V reference) will work. This kind of circuit generally uses the pot resistance to actively charge and discharge a capacitor- it does not simply accept a control voltage. Such digital pots certainly exist (eg. AD5290) and there are others from AD and Maxim.

If you look at the MCP42100 data sheet http://www.microchip.com/, on page 4 you will see the details for your unit. Notice that the actual resistance will be in the range of 70k to 130k.
So the reason that you are getting different results is (probably) due to your having a digital pot with a resistance somewhat lower than the physical pot you used.


text:
How to store u-blox coordinates (lat, lng) values in doubles? [TinyGps++]
I use a u-blox gps with my arduino. I can successfully write out the value of a coordinate (lat, lng) like this: Serial.println (gps.location.lat(), 8); but when I try to store the value with all the decimals it returns 8.00 instead of the correct coordinate + all of the 8 decimals.
This is my code:
#include "TinyGPS++.h"
#include <SoftwareSerial.h>
SoftwareSerial gpsconnection (4,3);
TinyGPSPlus gps;

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

void loop()
{
 while (gpsconnection.available())
 {
   gps.encode(gpsconnection.read());
 }

 //this works and returns 8 decimals
 Serial.println (gps.location.lat(), 8);
 Serial.println (gps.location.lng(), 8);

 //but if i try to store it like this:
 double latcord = (gps.location.lat(), 8);
 double lngcord = (gps.location.lng(), 8);

 //it returns 8.00 on both the "latcord" and "lngcord" which is the wrong coordinate and also it doesnt return 8 decimals
 Serial.println (latcord);
 Serial.println (lngcord);

 //if i try to convert the value to a string and then back to a double like this:
 double lat = gps.location.lat();
 String msgLat =  String(lat, 8);

 double thelat = atof(msgLat.c_str());

 //with this i get the correct first two numbers out but only 2 decimals after, not 8 decimals as it should be.
 Serial.println (thelat);

}

Note, accuracy of floats and doubles is the same on Arduino: 25 bits max, or about 7.53 decimals

You forgot the , 8 from your println that specifies that it should print 8 decimal places. Instead you seem to have added it to the end of an assignment which makes absolutely no sense whatsoever.
double latcord = gps.location.lat();
double lngcord = gps.location.lng();

Serial.println(latcord, 8);
Serial.println(lngcord, 8);

ah ok so i cant store the value (with the 8 dec) straight to a double, i have to give the dec afterwards. got it! thanks

Floats and doubles don't have a fixed number of decimal places, that's not how they work.


text:
clear Arduino as a global variable in Matlab
I'm trying to use Arduino in Matlab. cause I used Arduino in some function I had to define Arduino as a global variable.
clc,clear,close all;
global a
a = arduino();
.
some functions
.
clear a

at the end of my code I clear the variable but as I run the code again this error appear:
Failed to open serial port (user COM) to communicate with board Uno. ...
 Make sure there is no other MATLAB arduino object for this board.

I guess the global function can't be clear by clear command so I tried clear all instead clear in the last line. It works perfect as I run it again and again but as you know this is Matlab tips for clear all command
Using clear all causes MATLAB® to recompile previously cached code,
and can decrease performance.

I've tried delete(a) so the result was:
Error using arduino/delete
Cannot access method 'delete' in class 'arduino'.

any help would be appreciated.

What does contain the global variable a = arduino(); ?

cause it's recall in all sub functions. like writePWMDutyCycle(a,E1, 0);

sub functions use local value by default and save in separated location in matlab. one way is use a as an input argument for all of function. but i'm looking for another solution.

In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html
In your case should be: clearvars -global a;


text:
Servo/Motor for barrier gate
I am working on a small project that will need to check for proper UPC's then if validated, lift a barrier gate to move along cardboard boxes. The Arduino comes in with the gate lifting. I have this barrier gate working with a very small servo that came included with the Arduino Starter Kit, but this could not hold the weight that might be pushing up against it with a longer arm. Has anyone had any experience with something like this or could someone direct of a power supply/servo combo that would be up to the task? These boxes could weigh up to 20 pounds.
Thanks!

You may find Robotics Stackexchange  useful for questions like this.

This is really not an Ardunio question.  Keep in mind also, that a system strong enough to do what you want is also potentially hazardous to people working on or around it, so you will probably end up needing to pay more attention to making it safe than you do to making it actually work.

You may purchase a servo motor with greater torque.
You may find both DC as well as AC servo's. If you are using it in a real industrial scenario I would suggest you to use the AC, as you may not have to convert the ac power to DC and these motors will need real high current. So it would be better if it works on the main voltage. I did find PANASONICs ac servo as google search result.
If you have problems with integrating the greater torque motor to your current system let me know i can help you out.

You could look at larger DC gearmotors such as automotive power window or power door motors and use limit switches for position sensing. To power this you would need a 12V power supply capable of at least 5 amps.


text:
RC-oscillator calibration in real time
This pesky watchdog RC oscillator is at the limit of its 10% tolerance already at room temperature. i was looking to bringing it to more like 5% (it stems from an internak 128 kHz RC oscillator) and the whole -40 ... 125 deg Celsius operating range. Can this reliably be done by reading the temperature of the MCU and applying an algorithm ? Any such working algorithm ?
The calibration is actually the adjusting of the number of cycles (of say, 125ms) the watchdog will run for. i.e. for 12.5 seconds I would run the watchdog timer 100 times, nominally. How do I temperature-compensate the 100 figure ?

You could run a calibration routine whereby you run a timer at the same time as the watchdog timer and then compare the difference between the two... For example run the timer for 1 second and count how many times the watchdog interrupts in that period.

I think that just measuring the actual frequency at room temperature will be enough to calibrate to a reasonable amount. I don't think you'd get much more precision using temperature dependent calibration. If you want more precision I'd suggest adding an RTC. For example the DS3231.

We've been using the WDT delta as a temperature sensing method:
https://thecavepearlproject.org/2019/02/25/no-parts-temperature-measurement-with-arduino-pro-mini-to-0-005c-or-better/
Point being that once you have those calibration constants, you could use them use them to correct for WDT variation. OR you might be able to get away with a much shorter  interval than the 1sec we use, with the micros reading as your WDT correction factor more directly.

"The other big limitation is that you can only do this trick on a voltage regulated system, because RC oscillators are affected by the applied voltage," - this is a nice finding from that article, good thing I have ditched the WDT; otherwise it seems to be concerned with that Silabs temperature sensor.

Your description is pretty detailed but you've missed to tell, which device you are talking about.
I assume you are talking about the ATmega 328P in an Arduino Uno.
AFAIK you can only calibrate the so called Calibrated internal RC oscillator, which is used for the main operations.
You cannot calibrate the Internal 128kHz RC oscillator from the watchdog.
I think you might have some overhead from your sleep/wake cycles.
Instead of sleeping 100 times to get from 125ms to 12.5s you could sleep for 8s + 4s + 0.5s. Thus sleeping only 3 times. Which might save you some battery life.


text:
Arduino IDE compiling for non-arduino AVR boards
Using:

Arduino IDE 1.8.2
the board manager from https://mcudude.github.io/MiniCore/package_MCUdude_MiniCore_index.json
an ATmega168P MCU in TQFP

I was able to run my code successfully by modifying the file
[ardunoIDE]\hardware\arduino\avr\variants\standard\pins_arduino.h
building and then flashing the MCU with avrdude.
Is there any way to have Arduino IDE build system pick its pins_arduino.h file from somewhere else ?

Yes, MiniCore is a self-contained hardware package. After installing MiniCore select one of the MiniCore boards in the Arduino IDE's Tools > Board menu and the Arduino IDE will automatically use the pins_arduino.h file included with MiniCore. There is no need to modify any file in the Arduino IDE folder or any other folder.

Arduino IDE does not use the pins_arduino.h file included with MiniCore. Can you give me its path on your installation so I can at least check it is there ?

Do this:
Select a MiniCore board from the Tools > Board menu, File > Examples > AVR C code examples > Blink, Sketch > Show Sketch Folder, Navigate up 4 folder levels to the 1.0.3 folder. The pins_arduino.h file used for MiniCore boards is located under that folder in the variants/standard folder.


text:
Porting code from Arduino IDE to other IDEs - expected code size reduction
Could I realistically be expecting some 25% - 50% code size reduction if I abandoned Arduino IDE's framework and moved to something more rudimentary such as AVR Studio ? I am using the EEPROM, Timer1 and Wire libraries whereas my own code is about 700 lines of code.

You don't need to abandon the Arduino IDE.
Let me quote from my forum post about sketch sizes.

Introduction
Every now and again this subject pops up on the Arduino forum. Why does it take 1000 bytes to blink an LED? Why, oh why? It is obviously very bloated, eh?

Example: blink
Let's check that claim first.
The "blink" sketch, as shipped with the IDE (and stripped of comments) is:
int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  digitalWrite(led, HIGH);
  delay(1000);
  digitalWrite(led, LOW);
  delay(1000);
}

Compiled:
Binary sketch size: 1,084 bytes (of a 32,256 byte maximum)

OK, over 1000 bytes to "blink an LED".
Well first, as someone on the Arduino forum humorously pointed out, it doesn't take 2000 bytes to blink two LEDs!
int led1 = 13;
int led2 = 12;
void setup()
{
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop()
{
  digitalWrite(led1, HIGH);
  delay(1000);
  digitalWrite(led1, LOW);
  delay(1000);

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

That takes:
Binary sketch size: 1,140 bytes (of a 32,256 byte maximum)

So the overhead for the second LED is only:
1140 - 1084 = 56

So you could argue that it only takes 56 bytes to blink an LED (providing you are already blinking another one).

It does more than blink
The first relevant rejoinder here is that the example sketch does more than blink an LED. Rather importantly, it also waits for a second between turning the LED on and off (the "delay" function call).
If we remove that, the sketch is somewhat smaller:
int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  digitalWrite(led, HIGH);
  digitalWrite(led, LOW);
}

Code size:
Binary sketch size: 882 bytes (of a 32,256 byte maximum)

So we saved 202 bytes by not doing a delay. This isn't totally unreasonable, as doing delays requires the library to configure a timer, and have code to check that timer.

The pins numbers are variables
The code in the Blink example uses (wrongly in my opinion) a variable to hold the pin number (13) when a constant would do. And if you use a constant there is a library called
digitalWriteFast that generates more efficient code.
#include <digitalWriteFast.h>

const int led = 13;
void setup()
{
  pinModeFast(led, OUTPUT);
}

void loop()
{
  digitalWriteFast(led, HIGH);
  digitalWriteFast(led, LOW);
}

Code size:
Binary sketch size: 470 bytes (of a 32,256 byte maximum)

Now we are down to 470 bytes to "blink an LED".

We can use port manipulation
If all we want to do is blink the LED, we can omit using setup and loop, and go straight into using the processor registers. For example:
int main ()
  {
  DDRB = bit (5);
  while (true)
    PINB = bit (5);
  }

That blinks pin 13, believe it or not*. And now it only takes 178 bytes:
Binary sketch size: 178 bytes (of a 32,256 byte maximum)

* very rapidly indeed

Interrupt vectors
Well, you may be thinking "Pfft! Still 178 bytes. Why not 10 bytes?"
The answer to that lies in the way the hardware works. The Atmega328P has 26 interrupt vectors, at the start of program memory. Each one is 4 bytes (it jumps to a handler for each interrupt). So 26 * 4 = 104 bytes.
Thus there is an unavoidable overhead of 104 bytes in any piece of code. (Unless you know in advance you aren't going to use all those interrupt vectors, but this is rather specialized).
You can see these vectors if you add handlers for them:
EMPTY_INTERRUPT (INT0_vect)
EMPTY_INTERRUPT (INT1_vect)
EMPTY_INTERRUPT (PCINT0_vect)
EMPTY_INTERRUPT (PCINT1_vect)
EMPTY_INTERRUPT (PCINT2_vect)
EMPTY_INTERRUPT (WDT_vect)
EMPTY_INTERRUPT (TIMER2_COMPA_vect)
EMPTY_INTERRUPT (TIMER2_COMPB_vect)
EMPTY_INTERRUPT (TIMER2_OVF_vect)
EMPTY_INTERRUPT (TIMER1_CAPT_vect)
EMPTY_INTERRUPT (TIMER1_COMPA_vect)
EMPTY_INTERRUPT (TIMER1_COMPB_vect)
EMPTY_INTERRUPT (TIMER1_OVF_vect)
EMPTY_INTERRUPT (TIMER0_COMPA_vect)
EMPTY_INTERRUPT (TIMER0_COMPB_vect)
EMPTY_INTERRUPT (TIMER0_OVF_vect)
EMPTY_INTERRUPT (SPI_STC_vect)
EMPTY_INTERRUPT (USART_RX_vect)
EMPTY_INTERRUPT (USART_UDRE_vect)
EMPTY_INTERRUPT (USART_TX_vect)
EMPTY_INTERRUPT (ADC_vect)
EMPTY_INTERRUPT (EE_READY_vect)
EMPTY_INTERRUPT (ANALOG_COMP_vect)
EMPTY_INTERRUPT (TWI_vect)
EMPTY_INTERRUPT (SPM_READY_vect)

Now the start of the object code is:
00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__vector_1>
   8:   0c 94 52 00     jmp 0xa4    ; 0xa4 <__vector_2>
   c:   0c 94 53 00     jmp 0xa6    ; 0xa6 <__vector_3>
  10:   0c 94 54 00     jmp 0xa8    ; 0xa8 <__vector_4>
  14:   0c 94 55 00     jmp 0xaa    ; 0xaa <__vector_5>
  18:   0c 94 56 00     jmp 0xac    ; 0xac <__vector_6>
  1c:   0c 94 57 00     jmp 0xae    ; 0xae <__vector_7>
  20:   0c 94 58 00     jmp 0xb0    ; 0xb0 <__vector_8>
  24:   0c 94 59 00     jmp 0xb2    ; 0xb2 <__vector_9>
  28:   0c 94 5a 00     jmp 0xb4    ; 0xb4 <__vector_10>
  2c:   0c 94 5b 00     jmp 0xb6    ; 0xb6 <__vector_11>
  30:   0c 94 5c 00     jmp 0xb8    ; 0xb8 <__vector_12>
  34:   0c 94 5d 00     jmp 0xba    ; 0xba <__vector_13>
  38:   0c 94 5e 00     jmp 0xbc    ; 0xbc <__vector_14>
  3c:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_15>
  40:   0c 94 60 00     jmp 0xc0    ; 0xc0 <__vector_16>
  44:   0c 94 61 00     jmp 0xc2    ; 0xc2 <__vector_17>
  48:   0c 94 62 00     jmp 0xc4    ; 0xc4 <__vector_18>
  4c:   0c 94 63 00     jmp 0xc6    ; 0xc6 <__vector_19>
  50:   0c 94 64 00     jmp 0xc8    ; 0xc8 <__vector_20>
  54:   0c 94 65 00     jmp 0xca    ; 0xca <__vector_21>
  58:   0c 94 66 00     jmp 0xcc    ; 0xcc <__vector_22>
  5c:   0c 94 67 00     jmp 0xce    ; 0xce <__vector_23>
  60:   0c 94 68 00     jmp 0xd0    ; 0xd0 <__vector_24>
  64:   0c 94 69 00     jmp 0xd2    ; 0xd2 <__vector_25>

The "real" code has to start at 0x68 (decimal 104) which is where the reset vector takes us (the first vector).
So now, our code is really 178 - 104 bytes of useful code. That's 74 bytes to blink an LED.
However even some (most) of that is overhead, generated by the C compiler to initialize global variables, call class constructors, etc. Let's test that by blinking two LEDs.
int main ()
  {
  DDRB = bit (5);  // pin 13
  DDRB |= bit (4);  // pin 12

  while (true)
    {
    PINB = bit (5); // pin 13
    PINB = bit (4); // pin 12
    }
  }

Code size:
Binary sketch size: 186 bytes (of a 32,256 byte maximum)

Eight bytes difference. So really, you can blink an LED in 8 bytes. That is the bottom line. And you can do it in the Arduino IDE.

The libraries are designed to make things easy
The fact is that the default behaviour of the Arduino libraries is to simplify things for beginners. Thus they do some things which take up a bit of memory;

You can pass variables to pinMode and digitalWrite. Not just constants. Thus, at runtime, code has to convert the variable value to an actual processor port.
You get an automatic set-up of Timer 0, so you can use millis(), micros(), and delay() function calls.
You get Timer 1 and Timer 2 set-up, so you can do PWM output easily.

So you are trading off program space, to an extent, for ease of use. But if you want to code around it, as I did above, you can trim that program space right down.

Tests on an Arduino Uno board type, IDE 1.0.5.

I think I'll give that a go, sounds promising. I have alrrady tried commenting out all the digtal-Read/Write calls from my own code with little gain though. So I shall have to brush off those libs a bit.

Note that using just assembly (no interrupts, no C runtime) you can blink an LED in 12 bytes, including the delay.

No doubt, but I was talking about what could be achieved with the existing IDE. I suspect the OP isn't interested in coding all his stuff in assembly. :)

If you like the Arduino IDE, you also can do the following:

Do not use the library functions, but use registers directly.
The compiler is smart enough that it does not link functions you do not use with your executable/binary.
Optimize your code by

Checking if you can simplify algorithms
Remove unnecessary statements
Remove global variables (maybe move them to locals if you can)
Reduce or remove text strings.
For globals (but also to reduce SRAM) minimize memory sizes of variables, e.g. use uint8_t instead of integers, especially when using arrays of them.

If you use library functions, optimize them:

Simplify library functions if you use them (by 'paying' less portability for example)
By removing functionality that you do not need

Other tips (not necessarily answering your answer but things to keep in mind);

Use another Arduino which has more memory (Mega/Due)
Switch to another type of microControllers with more memory/flash

I have managed some 33% downsizing, hurrah!
Adding to the current answers: the biggest reduction came by ridding the floating points. I have come across the answer here and put avr-objdump to good use. That's how I have had the shock of my life (no hardware FPU built into these $1 MCUs :-o) and also that is how you can see other offenders sneaking into your binary image.
HTH

Very good idea to do that. Regardless of IDE, doing floating-point maths when you don't need to will lead to a lot of bloat. Also don't be tempted to use long long (64-bit integers) which the hardware certainly doesn't support. The compiler and linker do optimize rather aggressively, but they can't optimize away something that you are using (eg. floats). They may optimize away parts of a library that you don't use.

Also avoid the string class and use F for printing strings.

@jantje Right, but my code comes with no strings attached :)

Could I realistically be expecting some 25% - 50% code size reduction ...

code size has nothing to do with the ide, but compiler, compilers used, and libraries / routines used.
in general (which means that there are lots of exceptions) you will see a size increase when porting to an non-arduino environment.
with that said, many of the arduino functionalities are not that well implemented so you can save code size if you roll your own functionally equivalent code.


text:
TWI Wire.setClock() on non arduino AVR MCU issue
Using an Atmega168P - programmed by means of avrdude with the .hex file generated by Arduino IDE.
The following code sets the 8 MHz Atmega's TWI interface to just 15.625 kHz:
  Wire.begin(); // Initiate the Wire library
  Wire.setClock(100* 1000);
  delay(10);

While this one doubles it to 31.25 kHz:
  Wire.begin(); // Initiate the Wire library
  TWBR = (F_CPU/(100*1000) - 16)/2;
  TWSR &= 0b11111100;
  delay(10);

Looking to get 100 kHz clock. What am I missing ?

Calculations are int (16-bits) by default. Try 100*1000L. Or better define F_TWI as 100000L and use TWBR = ((F_CPU/F_TWI)-16)/2;

@MikaelPatel That was it! You may want to turn that into an answer as well, thanks.

You get 100kHz with just Wire.begin(), because that is the default. The Wire.setClock has limits (I don't know the limits) but 50kHz to 200kHz should work: Wire.setClock(50000L) to Wire.setClock(200000L). I hope you are not trying to compile 16MHz code for a 8MHz ATmega chip. If there is no 8MHz ATmega168P in the menu, you should create an entry in boards.txt.

Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100*1000L. Or even better:
#define F_TWI 100000L

and use:
TWBR = ((F_CPU/F_TWI)-16)/2;

or:
Wire.setClock(F_TWI);

Cheers!


text:
Arduino Zero: Enable RTTI
I need dynamic casts for my project, I'm getting:
error: 'dynamic_cast' not permitted with -fno-rtti

It appears that RTTI (run-time type information) is disabled with the fno-rtti compiler flag.
How do I change this?

We'll need to see your code in order to help.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/

It apparently is true that “RTTI (run-time type information) is disabled with the fno-rtti compiler flag”; however, looking at compiler.c.flags and compiler.cpp.flags in platform.txt, no fno-rtti compiler flag is set, suggesting that gcc sets it by default.
One way to turn off fno-rtti is adding a -frtti flag into the appropriate flags string in platform.txt.  As a side effect, this will affect all sketches subsequently compiled, rather than only those that need dynamic casts.
Note, on a microcontroller, a more-appropriate way to deal with the problem is getting rid of the need for dynamic casts, via function overloading.
Edit 1: On Linux, typical file paths to platform.txt are like /opt/arduino-1.6.3/hardware/arduino/avr/platform.txt or /opt/arduino-1.8.0/hardware/arduino/avr/platform.txt.  I don't know the location on OSX.  However, a command like locate *avr/platform.txt should reveal its location.  (If locate is a new install on your system, first run updatedb, which may take a while.)

Do you know where the platform.txt file is on OS X? Perfect answer, thanks!

@CodySmith, see Edit 1

This does not entirely solve the problem for those wishing to use rtti. This does not enable the linker to complete the compile of a simple sketch with dynamic_cast in it. What are the steps to get that aspect working. (I know there are people who say it shouldn’t be done, but I’m curious and have some ideas I’d like to test). I have drawn a blank as to how to complete this process. (Sorry this should have been a comment)


text:
Arduino Zero timer setup
Where would I find information on how to configure the Arduino Zero's timers?
Because this...
  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 150;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV256 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

Is completely indecipherable and highly error prone.

BOTTOM UP
The arduino Zero uses an Atmel samd21 µController. This video explains how to program the samd chips in a bottom up fashion, or at least how to gather all required information to do so. In case the video doesn't work anymore, i'll briefly rephrase it here. The main steps are:

Figure out the required registers by reading the data sheet
Consult the Atmel Software Framework(ASF) to figure out the corresponding data structures
Setup your sketch inside the arduino IDE

The bottom up process can be very time consuming, because you are searching a needle out of an haystack like, the datasheet and the ASF. So you need to tackle all the tiny bits before building the whole thing.
TOP DOWN
For some situations it is better to look for a working example program and try to figure out how its done. For this i recommend the arduino github repository. It is a very good resource for figuring out how arduino uses the ASF and helps me tune certain functions.
The top down process therefore allows to decompose a large working function into its smaller parts and dig into the interesting parts. However, it requires something to work with at the start which is not always available.
INDECIPHERABLE
Some code examples aren't understandable from the start. Once you know what the code is doing, i recommend splitting up the large pieces like this register and bit modification section into smaller ones. Extract these sections into functions with self explanatory names, and if done correctly you can get rid of the comments.
Hope this helps ;)

Where would I find information on how to configure the Arduino Zero's timers?

Try the datasheet.
What you showed there is fairly typical, may be on the primitive side for chips of its kind.
More power comes with more complexity.

So am I correct to assume that these low level registers are just exposed in the Arduino sketch? I assume some of the timers are already configured by Arduino for internal uses, such as delay(), where would I find that config?


text:
Multiple power supply for arduino controlled dc motor
I’m working on a project where I want to control a motorized fader with an arduino.  I have a dual H-Bridge board to control the motor, but the thing is that it is a 10V motor.  I’m thinking of using a secondary power supply on the H-Bridge to power the motor with a proper voltage.
So here is where my lack of electrical knowledge comes into play.  My H-Bridge has the following connections: a set of +/- poles to provide the power to the motors, 4 motor control pins (2 per motor to control their direction) and 4 motor power pins (2 per motor).
If I was using the Arduino as the power source for the DC motor, I would connect the +5v rail to the + terminal ot the H-Bridge and the Gnd rail to the - terminal, which would, in turn act as the ground return for the control pins.
If I am to use an external power supply, how do I wire it properly so I don’t blowup the arduino or the h-bridge?  I’m guessing that my secondary power supply will be connected to the +/- poles of the H-Bridge and the the - pole will also get connected to the Gnd rail of the arduino?
Is that correct?

Possibly, but it's ultimately not possible to say without the documentation of this motor shield.

@ChrisStratton It’s not an arduino shield, it’s a generic H-Bridge board.  I’ll try to find more documentation, but it’s relatively hard to find the paperwork for stuff bought on ebay ;)

To an extent, then it's not really an Arduino question.  The Arduino should have a common ground with the compatible-signal-voltage "digital" side of a motor driver it commands.  What happens on the power side is a question about the details of the motor driver circuit, not an Arduino question.  Without documentation you may need to do some visual/continuity reverse engineering from the data sheet of the driver IC or raw circuit topology if it is made of discrete FETs.

The board is based on a L298N chip...  ill dig further.

According to the datasheet on the L298 IC the connections you described should be right. First I would recommend to connect 10v to the + and - rails and measure the voltage on the logical inputs if it is 0 or lower than 3v than that should be ok to connect an arduino. Also now you can connect an additional 5v power supply with an the -5v connected to the - rail on the board and try to connect the +5v volts to the inputs and measure the voltages on the output (or connect an motor) if everything is ok you can try to connect your Arduino.


text:
RGB Led strip pot control burned my arduino?
I made this exact build on my Arduino, with the following differences:

I'm using Arduino Nano
Transistors I use are 2N2222A
I'm running everything on 12V except Arduino, I use LM317 to feed Arduino 6v

Here's the build:

Here's what happened. First, it started to get strange voltage, arduino would light up even when disconnected from power. After that, Arduino kind of got fried, when I connect it to USB, nothing happens. I can give it 6v to VIN and ground it with the rest, but turning potentiometers only dims the onboard LED of the Arduino and that's it.
Now I'm going to go and pick up a new nano, however, I'd prefer not to fry that one, so figuring out why this one burned would be nice.
PS. The image shows RGB LED instead of RGB LED Strip because 123d doesn't have strip component.

No base resistors?

Nothing according to the original build, should there be any?

Yes, otherwise the transistors can draw too much current for the Arduino to handle.

Would you suggest anything specific? Arduino should be able to throw 20mA on those outputs, transistors are running on 12v, while Arduino is on 6

That depends on how much current your LED strip needs per channel.

Any ideas how to figure it out? There are zero marks on the strip itself. No make and model, no specs

How many LEDs on your strip?

Theres 12 leds total, 3 per segment

220Ω should be fine

So i did try the resistor and arduino keeps burning up. One thing i noticed: if i wire pots directly to + arduino gets really hot really fast. If i wire them to arduino 5v pin, it gets hot slower, but still does. Im confused

Then you must have something seriously messed up with your wiring.

Power everything from the same source. Keep grounds common. Check your wiring. Fritizing is a poor way to show your connections.

First, as Majenko said, you need resistors between the arduino output pins and the transistor bases. Start at something like 330 Ohm.
Second, what is the value of the potentiometers? If it is too low you would be drawing too much current from the 5V pin to the ground.
Third, you should power the arduino with at least 7V, assuming you power it through the Vin pin or the power jack. 6V is considered too low.
I assume the pins connected to the potentiometers are initialised as inputs. Otherwise, it would be possible to burn your arduino by having them source/sink too much current (i.e. by turning the potentiometers to one end or the other).

I just figured 6v safe, but I'll increase it to 7. I did start with 330 and went all the way up to 1k resistors without results. The pots are 4.7k trimmers, original design said 10k, but I had none at hand. They are hooked to A5 and A6 which are initialised as inputs yes

Although 6V is generally considered too low (you are applying it to pin Vin or the power jack, right?) this would not explain the arduino burning, so pls don't try with another arduino unless you find a plausible explanation for this. It may seem a silly question, but have you double- and triple-checked all your connections?

The trimmers are fine. At 5V they will draw around 1 mA each, which is really unimportant toward the 200mA limit.

Yeah vin is connected to 6v and gnd to power supplu ground. I did, only thing left is to recheck the wires for broken ones (i had one that beep on continuity test but didnt work) and breadboard itself i see nothing else that can be an issue, since my circuit is correct

Looking at the datasheet for the 2N2222A at http://www.onsemi.com/pub_link/Collateral/2N2222A-D.PDF
The 2N2222A base will draw 50 ma at 2volt.  You are giving them more than that.
The maximum allowed output from the Arduino is 40ma.
So check the 2N2222A's they are probably burnt out as well as the Arduino.
Next time put in a limit resistor of 1k to the 2N2222A bases.
Try pulling out the 2N2222A's and see if your Arduino powers up ok.


text:
Arduino(s) not resetting on Serial connection lost / re-established - why?
it seems that I accidentally found a way to make my two Arduino nano clones run without resetting on serial connection close/reconnect. On one hand, this behavior is much closer to the desired behavior and on the other hand it feels hackish, because I don't know the cause yet.
The devices are still able to be flashed with new firmware
I assume that it has to do with the usage of socat as proxy for the devices in question. The described behavior was first observed after playing with socat. The command that finally worked for me:
/usr/bin/socat -s -d /dev/ttyACM3,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1 PTY,link=~/.pyduin/ttyACM3.tty,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1

An Arduino Uno with the exact same firmware/treatment does not show the same bahavior.
Any ideas what had gone wrong? And how to restore the default FTDI behavior?

What you have done is to disable the "HUPCL" signal that is sent when the port is opened/closed.
You can turn the signal back on with:
$ stty -F /dev/ttyACM3 hupcl

And you can turn it off again with:
$ stty -F /dev/ttyACM3 -hupcl

HUPCL means "HangUP on CLose".

Yes, that was the cause. Thanks. Btw, is it safe to use it as a proxish feature? I mean the arduino does not reset on reconnect and there are tons of guys in the internet asking for that feature.


text:
3x3 LED Matrix with less pins
I'm building an audio cable tester/soldering station.  XLR cables have 3 pins and they can be wired in a few ways depending on what you want to do.  The basic cable is connected 1 for 1 and I want to make a system to verify if each pin is connected to the good ones on the other connector.
Picture the male and female connectors side by side.  The 3 pins on the male connectors will be connected to 3 digital outputs and the 3 pins on the female connector will be connected to 3 digital inputs.  That way, I can turn one of the outputs High and check my 3 inputs to see where that pin on the male connector is wired on the female connector.  Then I can walk the remaining outputs and find out how the rest of the cable is wired.
That part is all good, I can output the wiring via the Serial.print() command and the result is good.  The thing is that I would like to show the result with LEDs.  It brings me up to 9 LEDs in a 3x3 matrix.  I can use 9 outputs to show the result, but it seem like there could be a much better way.
The two solutions I see are the following:

Buying addressable LEDs and interface them with my Uno
Use 6 outputs, one for each row and one for each column.  Each row represents one pin on the male connector, each row represents one pin on the female connector.  So while I walk my 3 pins I can turn on the corresponding row and columns, then turn off that row and go to the next one, turn on the corresponding columns, etc.  I feel like this would work, but I'm wondering if the LEDs will flicker or if the refresh will be fast enough not to be noticeable.

What would you suggest?  Am I on the wrong track with solution #2?  Is there another way that does not require that many outputs?  I'm already up to 12 IO pins taken with #2 and 15 with #1.  It seem like a lot for such a simple build...

Option #2 can definitely work, it is based on a widely adopted side effect of human vision called Persistence Of Vision, abbreviated with POV, which is used in Television, LED cubes and many other display devices.
You SHOULD notice no flickering if you manage to keep a refresh rate above 24 FPS (Frames Per Seconds or full refreshes), but not all human being are the same, that's why we tend to aim at 60 or 100 FPS to ensure flickering is not perceivable by anybody.
What you WILL notice though is a reduced brightness as each LED will be turned on only for a fraction of time.
So, naming your pins as COL1 to COL3 and ROW1 to ROW3, you can refer to the following schematic:

simulate this circuit – Schematic created using CircuitLab
You can further extend your option #2 by using an external IC, commonly referred as LED drivers: not something you need unless you get short of outputs.

Thanks a lot for that.  The LED driver shouldn't become necessary with this project, but I'll keep it in mind for future stuff.  I already ordered a few adressable LEDs just to play with them eventually, but in that case, I don't need RGB anyway.

It might be most cost- and time-effective to use an SPI-interfaced MAX7219-based 8x8 LED module.  These cost a couple of dollars.  Typically they include an 8x8 array of single-color LED chips, mounted under a cover.  The MAX7219 handles LED multiplexing and allows software control of brightness as well as resistor control.
To represent 9 items in a 3x3 arrangement, you could use 4 LEDs per item, so that rows 1 and 2; 4 and 5; 7 and 8 represent rows of items, with LED rows 3 and 6 remaining blank; and similarly for the columns.
Note, with four output lines you can control 12 LEDs, multiplexed via “charlieplexing”.  But the time and cost of setting that up probably would be somewhat more than just using a MAX7219 module.

I might expand my project eventually to do other connectors (some of them have 8 pins to check) so if I get there I'll get the 8x8 led matrix.  I've read about charlieplexing already, but being pretty new to electronics I got a bit lost.  I've been coding for a long time, so that part is not hard at all for me.  The rest is still a work in progress, but it's very exciting!


text:
NodeMCU powered with battery and use WiFi
I'm running a project with a nodeMCU DevKit and my project runs smooth if I run it connected through the usb wire to the computer.
I need to run my project using battery and I tried with a ICR14500 battery (3.7V and 700mAh). I connected the battery to the Vin pin but the NodeMCU doesn't send the data to the cloud.
When I run it with the battery I have detected some random behaviour, some times the led on the ESP8622 is blinking continiously and the total board power consumption is around 130mA!
Any idea what can be happening?

connect it to the 3V pin to bypass the LDO on VIN. A 3.7v  Vcc is ok: barely within spec...

This is a good approach, I will try this. My project is ported from another implemented with a D1Mini and I have realised that the LDO in the D1Mini is the TR9013 which has a voltage dropout maximum of 250mV. On the contrary the LDO on the NodeMCU is the NCP1117 and it has a output dropout around 0.9V at 100mA.

@dandavis a full lithium battery is 4.2 Volt. I think this is far out of spec.

You  need to use a voltage regulator with a lower dropout.

@Gerben:  touche; I forgot 3.7!=3.7. a hybrid buck+boost set to 3.3 and connected to "3V" would be ideal in this precarious situation; minimal heat, forgiving input voltage (ex: 3.8-12).

In order to reduce the voltage to 3V maybe a diode could be added to drop the battery voltage from 3.7 to 3V

Or use a zenner diode to clamp the voltage to within spec.

I'm voting to close this question as off-topic because it is about the ESP8266 hardware but about neither Arduino hardware nor Arduino-based development on alternate hardware.

If your battery is fully charged it’ll supply abount 4.2V.
The ESP should be able to handle up to 4.7V fine (according to this forum post), except that it’ll draw more current. So there’s no immediate need to go through the regulator.
If you’re battery-powering and want to use deep sleep, also consider using a different regulator with a lower quiescent current (e.g. MCP1702), otherwise the AMS1117 is already drawing at least 4mA.
Blinking and non-operation of the ESP is a sign for errors during boot, e.g. causing boot loops, typically caused by unstable power-supply, e.g. insufficient voltage or that the power supply cannot fulfill the peak current requirements (abount 200mA for the ESP).
My suggestion to be failsafe: just connect two batteries is series (7.4V nominal) and go through a 3.3V regulator.

It seem to be a problem with onboard regulator such as AMS1117.
ESP are really sensitive to power instability.
For every of my project i need to put capacitor on alimentation to prevent bugs.
I think you dont have enougth voltage to work properly with your regulated input.
To correct this issue you should put two battery to get 7.5 volt on the regulated input.
Another solution is using 3.3v input to pass trought the regulator.

Yes!! this is what was happening!

ESP8266 require 3.3v input.  Some boards require 5V (from USB) and have regulators on.  How do you know that supplying 3.7v to Vin will work?
As to the high power consumption I would suspect it might be the WIFI transmitting.

The NodeMCU have a regulator built in (the NCP1117) and It has a minimum input voltage of 3.5V. Anyway I'm going to try with another battery because it could be voltage drop when the ESP8266 tries to communicate through WiFi

@rdiaz82: all my nodeMCUs have an AMS117, which wants 4.75v min. less==instability

I am sure my NodeMCU requires 5V power, not 3.7V, and the high power consumption is related to Wifi - a notoriously high user of power!
This is why many battery driven ESP8266 related projects contain sleep mode stuff, to attempt to significantly reduce power consumption.

The vin pin will work with anything above 5v as it goes via ams1117 to drop it to 3.3, to provide 3.3v directly connect to pin which says 3v directly on nodemcu lolin board

It's actually not 5v, though 5v is sufficient; but the point you are making has already been made several times.  How does your answer improve on those of nearly three months ago?

For the deep sleep problem maybe you should try with lower time value such as 10 second for example. For me it's a problem with the duration .
I've never seen this kind of problem on my project but try with lower value and tell me what you got !

Yes! 15 minutes in production, in test I'm using 1 minute xD

Why have you added a second answer, when you could have edited and updated your existing answer?


text:
NodeMCU power consumption measurement and DeepSleep
I'm working on a project using a nodeMCU using a ICR14500(3.7V and 700mAh) battery and I'm experienced some issues when I try to estimate the total current consumption. Firstly I experienced some problems with the power supply (here is the previous question NodeMCU powered with battery and use WiFi) but this problem is now solved.
At this moment if I measure the current consumption connecting the amperimeter in serie between the battery and the nodeMCU input voltage pin I see a current consumption of 140mA continiously (ignoring the deep sleep mode) and I experienced some strange behaviours in my NodeMCU, even the code doesn't work. If I remove the amperimeter from my set up all works smooth and my source code works perfectly.
In order to validate my amperimeter I modified a usb cable and I added the amperimeter in the middle of the wire and I measured the current consumption powering me nodeMCU from the computer and I saw a current consumption of 80mA when the code is run and 14mA when the device is in deep sleep. This behaviour seems the expected one.
Are there any colateral effect measuring the battery current consumption which I haven't considered?

Make sure the battery is fully charged. That might be enough, so the burden-voltage described by Majenko isn't a problem.

An ammeter is basically a small resistor in series over which the voltage drop is measured. That resistance will play a part in the effective output impedance of your power source (battery).
This increased impedance will reduce the overall amount of current the battery can provide before the voltage drops to an unacceptable level.
For instance, I just did a crude measurement of the resistor used for the 200mA range of one of my DMMs and came up with a value of 1.2Ω. At 140mA that would give a voltage drop of (V=IR = 0.14 × 1.2) 0.168V. That's 0.168V that your NodeMCU won't be seeing. Add to that the fact that the WiFi will be creating peaks of current usage up to, say, 500mA (probably less, that's just a wild guestimate), the voltage drop will increase to (0.5 × 1.2) 0.6V. From a battery giving 3.7V nominal that would plummet to 3.1V as seen by the NodeMCU.
Depending on what kind of power regulation you are using that will most likely cause brown-outs of the power and the MCU will reset or crash.
When powered by 5V that 0.6V drop would not be as noticeable, since 4.1V is still well above what is needed to power the chip and the voltage regulation can still work properly.
So how can you measure the current with the battery? Well, there's two options:

Use a much smaller resistance (0.1Ω, for example) and measure the voltage across it - then use Ohm's Law to calculate the current.
Add a large electrolytic capacitor to the input of the NodeMCU after your current measurement to act as an energy source for sustaining the peaks of current required by the WiFi. By big I mean something like 3300µF:

simulate this circuit – Schematic created using CircuitLab

A very good explanation, I hadn't experienced issues due to the ammeter internal impedance. The idea of the filter using the capacitor is very good.  Thanks!!

The NodeMCU has an on-board voltage regulator, that needs excess voltage to supply the 3.3V. So if the voltage for the regulator is too low, the voltage for the ESP8266 may become too low too or it can’t draw enough current as it needs.  (During boot or wifi operation it’s drawing up to 200mA peak current). If that happens, it’ll be stuck in the boot process, in which it’s drawing the 140mA.
So, when you’re running from battery, be sure to power the 3.3V supply of the board, not the 5V input that goes through the regulator first.
When your battery is fully charged it’ll give 4.2V, which may just be enough for the regulator still. With the ampmeter in between it’ll definitely be too low.
Note that with the NodeMCU board you’ll never get the advertised 20μA deep sleep current of the ESP due to the onboard voltage regulator (unless you modify the board).

authors: Виктор Ткачук


text:
ESP8266 blue led stays stays on
I have found a similar qustion to mine but there was no good response.
I've connected my ESP8266 to Arduino UNO.
Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).
I used AT+IPR=9600 command to change it.
After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor.
Note: I connected the esp8266 through a voltage regulator and a power source and both gave the same problem. My firmware is supposed to be updated so I don't think that it is the issue.
Could anyone please help me?

You have changed the baudrate. Try to match up your UNO's baudrate with your new baudrate. Unmatching baudrates will indeed cause gibberish. Maybe the "updated firmware" is actually the problem, since the device isn't responding well, try to re-update the firmware (when you know which baudrate it is).

Did you change the firmware? I think Baud rate can be changed only if you flash it with newer version of the firmware.

Yes I changed the firmware. The problem is that when trying to change the baud rate back it is not accepting any AT commands even though I tried with different baud rates.

as mentioned by paul, have you tried to reupload the firmware ? I found  Nodemcu Flasher to be the easiest way to upload the firmware. Also create your self a simple flashing setup like this one. It is worth making if you plan to use ESP8266.


text:
How to measure water turbidity with arduino
I would like to measure water turbidity in the sea. The sensor does not need to measure it in an accurate way, I just need to know if water is clear or very turbided. I know that there could be used a light scatter but I do not know what kind of sensor should I use. Could anyone help how to measure turbidity?

http://uk.farnell.com/ams/tsl257-lf/sensor-light-voltage-converter/dp/1226886
is a good one according to http://forum.arduino.cc/index.php?topic=299993.0
But it might be easier to buy a COTS sensor, its a bit more expensive but much easier.  http://www.aliexpress.com/item/Turbidity-Testing-Sensor-Module-Suite/1903197650.html?spm=2114.01010208.3.17.OSVwdj&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_9868_10005_10006_10034_10021_507_10022_10020_1000020_10018_10019,searchweb201603_8&btsid=6dbcca61-3e0a-4e34-9359-a6c26b268509
BTW for everyone else Turbidity is the amount of muck in the water, so it would be no good looking at the crystal clear waters off the UK coast :)

Thanks, do you think that there could be find any datasheet or part number of this chinesse COTS turbidity sensor?

You could try and ask the seller.  There are quite a few that sell similar units, ask them all and take the average of the responses as closest to the truth.  From the pictures and experience of similar looking sensors you seem to have both an analog and digital connections.  The digital could be in or out, in is usually the signal to make a reading, out is usually just condition sensed / not sensed.
The Sensor looks to be the same as a IR Tachograph sensor, but the receiver board is a bit more complex.  Generally the sellers are really helpful.

I used an array of cheap light dependent resistors hermetically sealed and used a torch. For dark water, it clearly shows a lower value than for cristal water. It is kind of a binary sensor, but I was proud of my basic invention!


text:
Getting RTK-precision GPS with arduino devices like NavSpark?
In trying to learn how to create a reasonably precise 3d model of my (very hilly) property, I stumbled across a product called Navspark, which appears to be a $22 arduino-compatible development board, with an RTK-capable (and RTKlib-compatible) GPS chip.
The idea with RTK is that a reference-position base-station transmits its positional error to a mobile unit, giving the mobile unit cm-level precision relative to the position of the base station. The error calculation is computationally intensive, but apparently within the capabilities of a Pi.
Is it actually possible to build an RTK-capable mobile/base pair using low-priced equipment like this?  Can you link a howto or project example?

The $22 Nacsparc ( http://navspark.mybigcommerce.com/navspark-arduino-compatible-development-board-with-gps/ ) doesn't appear to do RTK compatible GPS info.  For that you need the $80 NS-RAW : http://navspark.mybigcommerce.com/ns-raw-carrier-phase-raw-measurement-output-gps-receiver/

How about the http://www.navspark.com.tw/tutorial-4 tutorial?  It seems to indicate you need a couple of the more capable $80 NS-RAW units with carrier-phase info rather than the less capable $22 NAV-SPARC plain GPS units.
The RTK system doesn't transmit only its positional error, (which it knows from external information) but also communicates the phase information for the particular channels, and then the RTK software re-calculates the positions of both using common sets of satellites and the phase info.  With the same framework, it knows the relative positions accurately, and with assumptions about the location of the base station, it can correct mobile station
This isn't an arduino problem, unless you are asking about porting RTKlib to something arduino.

It appears that NavSpark uses the same Venus 822A microcontroller as the NS-RAW, and some random blog article I read seemed to be saying that it was therefore capable of RTK.  Somehow missed their tutorial links, thanks.


text:
Arduino IDE crash when I connect Blend Micro
I recently bought Blend Micro and I am setting up Arduino IDE to start using it, but after installing the required libraries and the Blend Micro drivers, the IDE suddenly crashes without any visible error whenever I plug the blend micro to my PC. If it is already plugged in, the ide won't even start up. This was not happening before I installed the drivers. I don't know if it's relevant but blend micro was connected to my pc during the drivers installation. I have already looked for a way to solve this on Google without relevant results.
I am using Windows 10 with Arduino IDE 1.6.12
I would really appreciate any help with my problem, thank you in advance.

Reboot the PC, try an other one, try a different USB port, try uninstalling the IDE and reinstalling it...

I have already tried all those 3 things and they did not work...

I count 4 things there...

Yes, I did all 4, the 3 was a typo

The final solution to my problem was to download the latest arduino hourly build. There is probably a bug in the stable version that has been solved in the hourly build.

you should try to run the arduino from the consolle, on windows digit cmd on the search bar and the command promp program should appear.
Well, then you should navigate in out arudiono folder: digit cd "XXX" where XXX is the arduino executable location (something like c:/program files/blabla), you can copy paste it from the folder explorer.
then write arduino_debug.exe and you should see on the terminal the error appear; with that we may find the issue.

arduino_debug.exe may provide more information.

@per1234 fixed, thanks, I use win only to play so im a bit rust on that side xD


text:
Read data from arduino once only serial communications (jSSC)
I am trying to get the UID of RFID from Arduino to netbeans. I was able to display it to a textfield, but once another rfid was scanned, it is displayed together with the UID from the prev scan. How do I stop Arduino to send data so the only thing displayed in the textfield was the first UID scanned.
Here is Arduino code:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522

    //mfrc522.PCD_DumpVersionToSerial();    // Show details of PCD - MFRC522 Card Reader details
    //Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
  String code = "";
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
  for (byte i = 0; i < mfrc522.uid.size; i++) {
      code += String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" :" ");
      code += String(mfrc522.uid.uidByte[i], HEX);
  }
  code.toUpperCase();
  Serial.println(code);
  mfrc522.PICC_HaltA();
}

Only the first card scanned or the current card being scanned?

the first scanned

I'm voting to close this question as off-topic because the problem is with the PC code, no the Arduino

Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.
The fault is with the receiving java code, pump test data into that to see what is wrong.