text:
How do I print multiple variables in a string?
Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?
Currently I do something like this:
Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

Is there a better way to do this?

An idea, but I don't know if it would work, is some modification of this... Again, I don't know if this is supported on Arduino: http://stackoverflow.com/questions/804288/creating-c-formatted-strings-not-printing-them

ardprintf is a function that I hacked together which simulates printf over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.
It can be called similar to printf. See it in action in this example:

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

void loop()
{
  int l=2;
  char *j = "test";
  long k = 123456789;
  char s = 'g';
  float f = 2.3;

  ardprintf("test %d %l %c %s %f", l, k, s, j, f);

  delay(5000);

}

The output as expected is:
test 2 123456789 g test 2.30

The function prototype is:
int ardprintf(char *, ...);

It returns the number of arguments detected in the function call.
This is the function definition:
#ifndef ARDPRINTF
#define ARDPRINTF
#define ARDBUFFER 16
#include <stdarg.h>
#include <Arduino.h>

int ardprintf(char *str, ...)
{
  int i, count=0, j=0, flag=0;
  char temp[ARDBUFFER+1];
  for(i=0; str[i]!='\0';i++)  if(str[i]=='%')  count++;

  va_list argv;
  va_start(argv, count);
  for(i=0,j=0; str[i]!='\0';i++)
  {
    if(str[i]=='%')
    {
      temp[j] = '\0';
      Serial.print(temp);
      j=0;
      temp[0] = '\0';

      switch(str[++i])
      {
        case 'd': Serial.print(va_arg(argv, int));
                  break;
        case 'l': Serial.print(va_arg(argv, long));
                  break;
        case 'f': Serial.print(va_arg(argv, double));
                  break;
        case 'c': Serial.print((char)va_arg(argv, int));
                  break;
        case 's': Serial.print(va_arg(argv, char *));
                  break;
        default:  ;
      };
    }
    else
    {
      temp[j] = str[i];
      j = (j+1)%ARDBUFFER;
      if(j==0)
      {
        temp[ARDBUFFER] = '\0';
        Serial.print(temp);
        temp[0]='\0';
      }
    }
  };
  Serial.println();
  return count + 1;
}
#undef ARDBUFFER
#endif

**To print the % character, use %%.*

Now, available on Github gists.

Nice idea, although I felt it could be more minimalist, so I rewrote this version to one without buffering. Anyone interested can check out the gist: https://gist.github.com/EleotleCram/eb586037e2976a8d9884

I wouldn't normally put two answers to a question, but I only just found this today, where you can use printf without any buffer.
// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

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

    // Set up stdout
    fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
    stdout = &serial_stdout;

    printf("My favorite number is %6d!\n", 12);
}

void loop() {
  static long counter = 0;
  if (millis()%300==0){
    printf("millis(): %ld\tcounter: %ld (%02X)\n", millis(), counter, counter++);
    delay(1);
  }
}

This still has the floating point limitation.
I thought I would do a little testing on this, and it works quite well. I added a better test to the loop with formatted output.

Oh man, that's cool. printf is a whole lot safer than sprintf. It gives you format strings for free, which is great. Cool trick. Thanks. (Voted)

One question: In your serial_putchar function, why not make the return statement return !Serial.write(c);? Isn't that cleaner than a trinary operator for inverting the sense of a boolean return value?

That's a good point and I like it. The code wasn't mine and I pasted it as I found it.

Thanks for the serial_putchar function. It works a treat. :-) Can you fix the floating point limitation?

I only use this for debugging but:
int a = 10;
int b = 20;
Serial.println("a = " + String(a) + " and b = " + String(b));

what is String$?

LMFTFM (Let me fix that for me).

This is probably not better, just different.
You can use the String object for output. These objects allow concatenation and support automatic typecasting.
Serial.begin(9600);
String label = "Var";
const byte nValues = 3;
int var[nValues] = {36, 72, 49};

for (int i = 0; i < nValues; i++) {
    String stuff = label + i + ": ";
    Serial.println(stuff + var[i]);
}

Obviously it's important to be careful of memory limits. Lots of concatenations and other string operations in one place can use a surprising amount of space.

@PeterR.Bloomfield Absolutely true! That's the reason why I mentioned that this variant isn't better ;)

I usually used Tabs to make things line up better in the Serial. Having things line up like I do allow the arduino to fire as fast as possible while being able to notice certain changes in the variables.
Try something like this:
Serial.println("Var 1:\tVar 2tVar 3:");
Serial.print("\t");
Serial.print(var1);
Serial.print("\t");
Serial.print(var2);
Serial.print("\t");
Serial.print(var3);
Serial.println();

Or something like this:
Serial.print("Var 1:");Serial.println(var1);
Serial.print("\tVar 2:");Serial.println(var2);
Serial.print("\tVar 3:");Serial.println(var3);

Honestly, I do the same ("\t" and "\n") and normally avoid the code-bloating String object bells and whistles.

@KlausWarzecha, I rarely give the variable name as they're in nice columns. Also make it easier to see random print outs that don't match this syntax

I am newbie in Arduino world, but I recently found that this is just a regular C++ (without exceptions and probably polymorphism). But you still can enjoy templates. So my solution is to use following templates:
void myprint(void)
{
  Serial.println("");
}

template<typename ...Args>
void myprint(const uint64_t & val, Args && ...args)
{
  serialPrintUint64(val);
  myprint(args...);
}

template<typename T, typename ...Args>
void myprint(const T & t, Args && ...args)
{
  Serial.print(t);
  myprint(args...);
}

....

// somewhere in your code
myprint("type: ", results.decode_type,
        "\t value: ", results.value,
        "\t addr: ", results.address,
        "\t cmd: ", results.command);

Nice thing here is that it does not use any extra memory and extra processing here.

One possible solution is:
Serial.println((String)"Var 1:" + var1 + " Var 2:" + var2 + " Var 3:" + var3);

The above solution from Iain increases code size.

I like this method and I use it a lot. I'm giving you a plus 1.

The usage will depend of the data type of your variables.
If they are int, it would be %d or %i
If they are string, it would be %s
Wrapper for printf
You can change the limit based on your requirements
#include <stdarg.h>
void p(char *fmt, ... ){
    char buf[128]; // resulting string limited to 128 chars
    va_list args;
    va_start (args, fmt );
    vsnprintf(buf, 128, fmt, args);
    va_end (args);
    Serial.print(buf); // Output result to Serial
}

Source: https://playground.arduino.cc/Main/Printf
Usage examples:
p("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3); // strings
p("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3); // numbers

ESP8266
Its built-in in Serial class of the framework. No need for additional library or function.
// strings
Serial.printf("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3);
// numbers
Serial.printf("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3);

More details about formatting tips on the printf format reference page : http://www.cplusplus.com/reference/cstdio/printf/
\n is the escape sequence for the line feed.

Escape sequences are used to represent certain special characters within string literals and character literals.

Source: http://en.cppreference.com/w/cpp/language/escape
[EDIT]
- As @Juraj mentioned, it's not available on most of the AVR modules. So I added ESP8266 mention and a printf wrapper for common AVR modules

this is not true. there is no Serial class. printf would be in Print class, but it is not in the most used AVR package

@Juraj you are right, I've only tested it on ESP8266 which have it (link) and thought it was from arduino core. Will update my answer accordingly

for the p function I would add one more downvote if it was possible.

this is an old question and I can\t judge the old answers because I don't know what was available in 2014. but now there are libraries for wrapping a Print stream in a Print stream with printf implementation.

I usually (painfully) stick with multiple lines of Serial.print but when it becomes convoluted I go back to sprintf. It's annoying in that you have to have an available buffer for it.
Usage is as simple (??) as:
char buffer[35]; // you have to be aware of how long your data can be
                 // not forgetting unprintable and null term chars
sprintf(buffer,"var1:%i\tvar2:%i\tvar3:%i",var1,var2,var3);
Serial.println(buffer);

A word of warning though, it doesn't (by default) support floating types.

sprintf is a horrible abomination. Not type safe, easy to overrun your buffers, etc, etc. It's a tool from the 1960s. That said, I use it too, but it is not for the faint of heart....

To avoid overrun, use snprintf... BTW most of the moder IDEs (NOT the Arduino IDE) will check the string format against the provided variable types, and will throw a warning.

Using Streaming.h, in place of
Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

one can write
Serial << "Var 1:" << var1) << " Var 2:" << var2 << " Var 3:" << var3 << endl;

The definition of << in Streaming.h in effect translates that into a series of ordinary Serial.print() calls.  That is, << is syntactic sugar, implemented without increasing code size.
If you don't have Streaming.h installed, get Streaming5.zip from arduiniana.org.  Unzip it in your libraries directory, for example in ~/sketchbook/libraries.  Add the line #include <Streaming.h> within sketches where you use << as a stream operator.
Base-conversion specifiers _HEX, _DEC, _OCT, and _BIN are provided, as well as a _FLOAT function (with number of decimal places) and endl.  For example, to print latitude and longitude values in a form like "Your coordinates are -23.123, 135.4567” one could write:
Serial << "Your coordinates are " << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

This could also be written as
Serial << F("Your coordinates are ") << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

which would keep the longer string in PROGMEM instead of bringing it into RAM.
Note, Streaming.h  doesn't build any strings as such; it just delivers the text of its <<-arguments to a stream.  A PString class at arduiniana can build strings from stream inputs, if strings instead of streamed output are desired or needed.

From http://playground.arduino.cc/Main/Printf
I observed this is working fine on my mega2560
That's all it just worked, no need for vsnprintf_P or PROGMEM ...
#include "Arduino.h"
void local_printf(const char *format, ...)
{
static char line[80];
va_list args;
va_start(args, format);
int len = vsnprintf(line, sizeof(line), format, args);
va_end(args);
for (char *p = &line[0]; *p; p++) {
    if (*p == '\n') {
        Serial.write('\r');
    }
    Serial.write(*p);
}
if (len >= sizeof(line))
    Serial.write('$');
}

void setup()
{
Serial.begin(115200);
local_printf("%s:%d: %s\n", __FILE__, __LINE__, __PRETTY_FUNCTION__);
}

void loop()
{
static int count=0;
local_printf("%s:%d: %s %d\n", __FILE__, __LINE__, __PRETTY_FUNCTION__, count++);
delay(1*1000);
}

// src/main.c:24: void setup()
// src/main.c:30: void loop() 0
// src/main.c:30: void loop() 1

Why would anyone want to do this instead of just using printf() itself?

I've been using PrintEx for years, and it works great.  See enter link description here

I also have been using PrintEX for years and I agree is almost bulletproof.  However, you should know that the Teensy 3.x/4.x MCU's from Paul Stoffregen' store (https://www.pjrc.com/store/teensy32.html) have Serial.printf built into their TeensyDuino package.  Teensy 3.2s are as cheap as, or cheaper than  Arduino's and run MUCH faster as well.  I have dozens of these MCU programmed into various projects around the house and have had very few problems with them.


text:
Button state changing randomly
I have a push button wired to my Arduino but it seems to be triggering randomly.
I have one pin of the button connected to pin 2 on the arduino and the other connected to ground.
void setup() {
    Serial.begin(9600);

    pinMode(2, INPUT);
}

void loop() {
    Serial.println(digitalRead(2));
}

I expect it to print 1 continuously and go to 0 when I press the button down but sometimes it shows 0 even when I don't touch it.

When a button is connected in that configuration, the input is what's called floating, meaning it's not a 0 or a 1. When the button is pressed, it is connected to ground, so that's definitely a 0, but when it's not pressed down, we don't know the value of the pin.
Pull Up Resistor
We need to include what's called a "pull-up" resistor to pull the signal up to a logic 1 when the button is not pressed.

Image from Sparkfun
What this means is when the button is not pressed, the Arduino reads a logic 1. When the button is pressed, the current flows through the resistor to ground and the Arduino reads a logic 0.
Internal Pull Up Resistor
The Arduino also has internal pull up resistors so you don't necessarily have to add an extra component to your circuit. There are a couple of ways to use this.
You used to have to do it like this:
pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

Now we can do it simply in one line:
pinMode(pin, INPUT_PULLUP);

This enables the 20k pull up resistor on that pin. The input will no longer be floating when the button is not pressed.
Note: This only works when the other end is connected to ground.

It's worth noting that the same idea works for pull-down resistors too; i.e. the resistor normally pulls the pin low, but pressing the button brings it high. Obviously it has to be external though, as there's no internal pull-down on standard Arduinos.

I dunno if you evencheck arduino stack exchange now but I am unable to understand the pin diagram. I have push button, with one end having 5V, and the other end having my wire connected to arduino and a 20k Ohm resistor which is connected to ground. Still I am getting random value when the button is not pressed. When it is pressed, I always get 1

There are several possible reasons random values are seen at micro controller inputs when connected to switches. Here are two:

Missing pull up or pull down resistor when using a SPST switch.

Micro controller inputs should not be allowed to float. This can lead to unexpected input states. Instead, inputs should be connected to ground or the micro controller's positive voltage supply usually either directly or though a resistor. It is common to use a pull up resistor when using a SPST switch connected to ground. Or a pull down resistor when using a SPST switch connected to the micro controller's positive voltage supply. Not all micro controllers have pull up or pull down resistors built internally. Some only have one or the other. In these cases an external resistor may be required. Some thought should be given to using micro controllers that do have built in pull up or pull down resistors. The actual resistance value of these built in resistors does vary (may not be carefully controlled). This is fine for the majority of cases. However, if a specific value is needed, it may be best if external resistors were used instead.

Long wires between the micro controller and the switch.

Longer wires are more likely to develop unexpected currents due external electrical noise. It is possible wires are long enough and the environment they are in electrically noisy enough to develop currents that will change the voltage across a pull up or pull down resistor. And, in turn, change the value of the micro controller's input. The higher the resistor value the more likely this will happen. However, the lower the resistor value chosen the more power needed when the SPST switch is closed. This is usually a concern when operating on batteries. There are many aspects to mitigating the effects of electrical noise. And will take us off subject. Instead, if long wires are necessary, consider using a "brake-before-make" SPDT switch which will connect the micro controller's input pin directly to ground or the micro controller's positive supply voltage. This will require running 3 rather than 2 wires to the switch.
Last words: Take care not to connect pull up resistors or switches to voltages higher than the micro controller's positive supply voltage! Some Arduino boards regulate higher voltages to lower voltage before supplying power to the micro controller. For instance, an Arduino board that runs from the 5 Volt USB power source may have a micro controller which actually runs at 3.3 Volt. In such a case, use the 3.3 Volts supplied to the micro controller when connecting a pull up resistor or switch.

Added this answer as the existing answer does not cover long-wires/electrical-noise inducing unexpected results and the use of SPDT switches instead of a SPST switch with a pull up resistor.

source: Stack Exchange

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

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

sort: votes


text:
What are (or how do I use) the power saving options of the Arduino to extend battery life?
For solar & battery powered projects, decreasing power consumption is a necessity.
I know a little bit about using a timer and interrupt to put the microcontroller into sleep when it isn't doing anything.
I have also read that you can disable some peripherals to further save power.
Here is a page explaining these: Power Saving Techniques
My question:

What other techniques are there to save power?
Are there any libraries that make using these AVR features easier?

Note: I wanted to point out that, even though my answer was accepted, the reader (you) should really read Anindo's answer first if you really want to save energy with any Arduino board. Once you address those items in your design, then you should read my answer and worry about how to set the MCU into low power mode.
Having said that, there are several techniques to make an Arduino save power. I'll list a few and then point you to a page that explains them all in more detail.

While the controller isn't doing anything important (between one read of a sensor and the next, for example), you can put the controller into one of the sleep modes below, with the command set_sleep_mode (SLEEP_MODE_PWR_DOWN). Next to each mode is the approximate power consumption of each mode.

SLEEP_MODE_IDLE: 15 mA
SLEEP_MODE_ADC: 6.5 mA
SLEEP_MODE_PWR_SAVE: 1.62 mA
SLEEP_MODE_EXT_STANDBY: 1.62 mA
SLEEP_MODE_STANDBY : 0.84 mA
SLEEP_MODE_PWR_DOWN : 0.36 mA

Disable brown-out detection (the circuitry that turns off the controller when low voltage is detected).
Turn off ADC (analog to digita conversion)
Use the internal clock

Then, when you put the controller to sleep, you need to use one or more mechanisms below to wake up the controller and do something with it:

Wake up with a signal
Wake up with a timer

This is a summary I made from -

Nick Gammon's article: Power saving techniques for microprocessors.

That article applies mostly to ATmega328P, but the technique applies to other Arduino compatible controllers as well. As TheDoctor said well, you will need to check the datashet to make sure your controller suports any of those techniques and how to do it more precisely.

Thank you for referencing my page www.gammon.com.au/power. Employing all techniques mentioned on it should enable you to consume around 100 nA (0.1 µA). Other techniques which can have a big impact are to run at a lower frequency, and a lower voltage. Plus what Anindo Ghosh said about not using voltage regulators. I made a Temperature and humidity sensor - battery powered which employs a lot of these techniques, which is still going strong, after a couple of years on batteries.

@NickGammon - To be fair, I think your excellent article deserved a better reference, so I edited my answer to that extent. Thank you for the great article - very clear and complete! And welcome to Arduino.SE. It's good to have you here.

Realistically, the biggest power waster on an Arduino board is the linear voltage regulator on it.

As long as the microcontroller on the board, the LEDs, or any other peripherals, draw current, the linear regulator wastes power equal to difference between supply and board voltage x current drawn.
So, a first fix would be to disconnect the power indicator LED on the board, and not use any of the other LEDs as far as possible.
Second, supply the board with as low a voltage as possible that is just sufficient to power the on-board regulator.
On the original designs, the voltage regulators used do not boast low quiescent current. This means even with nothing drawing power within the board, the regulator itself wastes a fair bit of power all the time it is on.
An easy fix is to replace the on-board regulator with an LDO (low drop-out linear regulator) rated for extremely low quiescent current. Parametric searches on various vendor sites will yield likely substitutes.
Even with the above steps, the Arduino board does not provide a mechanism to set the LDO into low-power mode, if the LDO chosen supports this. Power efficient designs typically use a "sleep mode" pin on voltage regulators to save a fair bit of energy - not an option here.

Even with all possible power saving modes and tricks applied at the microcontroller level, the Arduino simply is not designed to be an ultra-low-power device out of the box. Having experimented with several non-trivial applications, I have found that the best that is realistically achievable is some 10% to 30% power saving depending on application, since the voltage regulator and the LEDs are going to consume the rest anyway.

supply the board with as low a voltage as possible that is just sufficient to power the on-board regulator Or supply 5V through a hacked USB cable.

You could read through the 200-page datasheet, and then mess with some confusing bit shifts and registers, but I recommend this library: http://playground.arduino.cc/Code/Enerlib
Also, if you're using an Uno or any one with a usb-to-serial chip, you could disable that or remove it.

You should read through the data-sheet no matter what you're doing.

Once your project is working and you need to deploy to "production" environment, you can opt to replace the Arduino with a bare meta ATMega328 or any of the ATTiny family chips. This will get rid of all the power eaters on the Arduino board you don't need.
I found:

Arduino board of 9V block battery - 56 mA
ATTiny85 bare on 8 MHz without sleep modes etc - 10 mA
ATTiny85 bare on 8 MHz in sleep mode - 0.03 mA

Some more information
Program an ATtiny with Arduino
ATTiny files for Arduino IDE

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


text:
Best practise when dynamically updating sketch
I am currently working on a project that uses an Arduino Mega 2560 board along with the Arduino GSM shield to connect to the internet and send/receive SMS messages.
As part of my project, I want to be able to update the software that I am running dynamically. At a high level, I want to connect to my server, check if there is an update, if there is, download it and then overwrite the current sketch to run the new downloaded binary if the checksum of the downloaded binary is as expected (to avoid corruption).
Now, I am new to Arduino programming, so I figured I would ask a community of people with experience to determine the best method.
My current ideas are as follows:

Writing a custom bootloader - The sketch will have an update routine that downloads the new binary to a known location, and then performs a system reset. The bootloader will then overwrite the current sketch with the downloaded binary and then run the sketch.
Overwriting the sketch whilst running - I'm not sure of the viability of this method, but the overall method would be to write an update routine to the end of flash memory, and in this code simply overwrite all of the non-bootloader code with the new sketch.

Are these methods both viable, if so, is there one that would be preferable to another? If not, are there any known solutions to this problem?

The second solution looks like a second "bootloader" to me.. It's the best solution if you want to keep your arduino board "arduino compatible", otherwise the first one is the most clean

Possible duplicate of Updating the ARDuino code over GPRS

You won't be able to download the whole binary and test its checksum before flashing because RAM is so much smaller than flash. To do that, you'd need an external storage device to hold the new binary, and a custom bootloader to install it from the device.
Otherwise you'll have to load-and-flash, testing the checksum on the fly, and retry if you need to until you get a good reload. Can your device and its environment tolerate stopping for however long a couple of retry cycles might take? You can't recover if the process is interrupted once you start flashing; you can only move forward. Can it tolerate a conceivably long outage if communication goes down once the reload process has started?

Why could I not simply download the entire binary to external memory, calculate the checksum and then, if valid, copy it a word at a time to flash?

Depending on the size of the sketch, the Arduino Mega may have enough resources to hold your sketch in RAM, or else hold an extra copy in flash (perhaps not executable, if not linked for the holding address, but still hold).  Otherwise an external spi flash could be used.

@Shaktal - You could. That would be an instance of the example in my first paragraph. If adding an external memory device is acceptable to you, that would be an effective technique. You'd still need to provide a memory-device-to-flash boot-loader, but it solves the problem of getting a bad checksum or of losing communication during the download process, since you will not have to over-write any of the existing executable image until you have a complete and verified new one.


text:
Is there an Arduino Simulator or Emulator that runs on OS X?
Is there an Arduino Simulator or Emulator or cross-compiler to native Mac executable that runs directly under Mac OS X, and does NOT require a Windows or Linux VM or an active internet connection for running in the cloud?
There are previous questions here on similar topics, but they do not seem to address exactly this particular use case subset.

Is this not adequate? http://123d.circuits.io/

I am using the Wokwi Arduino simulator for a long time. It runs on all three platforms. Mobile, Windows OS, and macOS.
I have checked the working of the simulator in both Android and iPhone. Both give a good performance as well.

Arduino CodeBlocks plug-in has an Arduino simulator. Be carefull when setting it up and use full paths, it's easy to mess up, but works beautifully once done.


text:
Delay versus polling power consumption?
Does using the delay function use any less power than spinning in a polling loop on a timer?

Polling loop on a timer?

What would you mean with that? Power consumption is quite a logic thing I believe, every peripheral that's on will draw power. And every clock tick will consume a bit of power.
So to decrease power consumption one must deactivate peripherals or underclock/deactivate the clock. (Sleep modes)

Polling loop on a timer means having something like while(now>timer1){};  this is a very standard way of waiting for some period of time

That depends very much on how delay() was written (and how it will be written in the future!). There are "sleep modes", which will reduce the power consumption of the arduino - these are one of the best way to reduce power consumption. Delay() may or may not activate these. If not, there could be a replacement Delay() function that could do this.
If you want to reduce power, check out http://www.gammon.com.au/power - this is an excellent step-by-step tutorial on how to reduce power consumption from 50mA down to 288 µA

The delay functions just poll the time, till enough time has passed. So power usage should be identical.

The answer is probably "they are equal" because what the CPU is doing is less than 1% of power draw. In order to save power while waiting you can put the chip to sleep. Assuming you have an Arduino uno, this post contains sample code about sleeping and current consumption. http://forum.arduino.cc/index.php?topic=78430.0
Maybe explain what you are doing (what size battery you have) and we can add some advice about ways to save power

authors: Антон Видович


text:
Comparison of an Arduino's performance?
How does an AVR-based Arduino's CPU performance compare to a vintage PC (Apple II, PC-XT, TRS-80, et.al.)?
How many megaflops of number crunching can one get out of an AVR-based Arduino?

take a look here: http://forum.arduino.cc/index.php?topic=40901.0 There is reference to 30k float divisions per second, so it is 0.03MFLOPS. Also, this topic was brought up before, please google before asking: http://robotics.stackexchange.com/questions/535/how-computationally-powerful-is-an-arduino-uno-board

The topic wasn't searchable in this forum, and one can't seem to dup a Q across stackexchange sites without admin help.

this is not a forum and google searches across interwebs since 1998

OK, so I just ran some really old benchmarks on a LightBlue Bean (AVR 328p Arduino at 16 MHz).  The Bean ran the Byte Sieve benchmark slightly slower than a VAX 11/780.  The Bean also ran some of my old floating point computations about 2X faster than the 11/750 (this VAX model has no FPU to be fair to the AVR).  That puts the Bean's math performance at somewhere around 70 kFLOPs (with few divides in the mix).  A DEC VAX is several times faster than vintage 8-bit personal computers, an IBM PC-XT being roughly 1/3 to 1/2 a VAX "MIP" in benchmark performance, with an Apple II being slower still.

An 11/780??!? Those were the days :)


text:
Client or WiFiClient wrapper for adafruit CC3000 wifi
I have a CC3000 wifi module from adafruit that is working OK. Now, I am trying to use it together with an external service, which code requires me to pass a Client (from Arduino SDK) reference, but the Adafruit_CC3000_Client does not inherit from Client nor WifiClient.
I am looking for an appropiate wrapper, but unable to find one. Does anyone know about such wrapper?

write it yourself, extends the Client class and override its method to call CC3000 method :)

Yes, as I didnt get any answers, I have started to do so, but it is a little tricky, I will post the answer when I am able to get it working properly.

As I didn't get any answer, and further search for an existing solution failed, I decided to roll my own. The class header is very straightforward, I decided to go for single inheritance and composition of Adafruit_CC3000_Client:
class CC3000Client: public WiFiClient {
public:
    CC3000Client(Adafruit_CC3000& cc, Stream& stream=Serial);
    virtual ~CC3000Client();

    virtual int connect(IPAddress ip, uint16_t port);
    virtual int connect(const char *host, uint16_t port);
    virtual uint8_t connected();
    virtual int available();
    virtual void stop();
    virtual void flush();
    virtual int peek();
    virtual int read();
    virtual size_t write(uint8_t v);
    virtual size_t write(const uint8_t *buf, size_t size);
    virtual int read(uint8_t *buf, size_t size);
    virtual operator bool();

private:
    Adafruit_CC3000& cc3000;
    Adafruit_CC3000_Client client;
    bool peeked;
    int peeked_byte;
    Stream& stream;
};

The implementation is a bit tricky (or I didn't manage to find a better way), as the Adafruit client does not have peek() functionality, so this wrapper class have to implement it.
CC3000Client::CC3000Client(Adafruit_CC3000& cc, Stream& stre) :
        cc3000(cc), peeked(false), stream(stre), peeked_byte(0) {
}
CC3000Client::~CC3000Client() {
}

int CC3000Client::connect(IPAddress ip, uint16_t port) {
    client = cc3000.connectTCP((uint32_t) ip, port);
    peeked = false;
    if (client.connected())
        return 1;
    return 0;
}
int CC3000Client::connect(const char *host, uint16_t port) {
    uint32_t ip = 0;
    if (!cc3000.getHostByName((char*) host, &ip)) {
        stream.println(F("Couldn't resolve!"));
        return 0;
    }
    client = cc3000.connectTCP(ip, port);
    peeked = false;
    if (client.connected()) {
        return 1;
    }
    return 0;
}
uint8_t CC3000Client::connected() {
    return (uint8_t) client.connected();
}
int CC3000Client::available() {
    if(peeked)
        return 1;
    return (int) client.available();
}
void CC3000Client::stop() {
    peeked = false;
    flush();
    while (client.connected()){
        client.close();
        delay(10);
    }
}
void CC3000Client::flush() {
    peeked = false;
    while (connected() && available())
        read();
}
int CC3000Client::peek() {
    if (!peeked) {
        if (available()) {
            peeked_byte = read();
            peeked = true;
        } else
            return -1;
    }
    return peeked_byte;

}
int CC3000Client::read() {
    if (peeked) {
        peeked = false;
        return peeked_byte;
    }
    return (int) client.read();
}
size_t CC3000Client::write(uint8_t v) {
    return (size_t) client.write(v);
}
size_t CC3000Client::write(const uint8_t *buf, size_t size) {
    return client.write(buf, size);
}
int CC3000Client::read(uint8_t *buf, size_t size) {
    if(peeked){
        buf[0]=peeked_byte;
        peeked=false;
        return client.read(buf+1, size-1);
    }
    return client.read(buf, size);
}
CC3000Client::operator bool() {
    stream.println("Error, bool() not implemented");
    return true;
}

Both files are available here, if you are using biicode all you have to do in your code is to put an include like the following and run "bii find", that will also retrieve and install the cc3000 library:
#include "diego/ardunet/cc3000client.h"

I have used and tested it with a simple http_get call (also here) and with the temboo service, and it has worked OK for sending emails from a Gmail account from an Arduino Mega2560 connected to the CC3000. This temboo service uses via the SDK Client interface most methods of this wrapper, but the bool() operator and the CC3000Client::write(const uint8_t *buf, size_t size) method.


text:
Reading multiple bytes from *software* serial
I have Arduino Leonardo board operating lots of AC relays in quite noisy environment. USB works unstable, which sometimes causes the board to hang, so I decided to use secondary serial connection as "debug console":
  Serial1.begin(115200);
  .....
  .....
  if (Serial1.available()) {
    char ch = Serial1.read();
    if ( isalnum(ch) ) {
      switch (ch) {
        case 'M': {
          turnOn_pin_Motor();
          break;
        }
        case 'm': {
          turnOff_pin_Motor();
          break;
        }
        .......

My problem is that noise affects Serial1 the same way it messes USB (but at least it doesn't cause it to freeze). I'd like to use some sort of error checking to prevent Leonardo from acting on "phantom" commands. I could, for example, prefix each keyboard command my Arduino should receive with special symbol, maybe "!".
So I must be reading one char, checking if it is "!" and reading second character.
Unfortunately, I can't modify my code so it would use 2-character buffer and shift its contents as characters arrive, without locking the main loop while waiting for the next char. Any hints on what should I do in this case?

Serial1 on a Leonardo is not “Software Serial”, it’s arguably more “hardware” than Serial.
How does the noise on your serial port manifest? Are the characters injected truly random?

Yes, they are totally random: here is tiny example from my debug log (notice the garbage as the 'Inlet' valve turns off and the current inducted by AC coil messes with power supply): [3819448        void turnOff_pin_Inlet()]                                                 WкК•╧╠•я² [3819570        void checkTempSensors()]        DS18B20 on Door failed!

I've replaced today the wire connected to Serial1 (I've used piece of Ethernet Cat5 twisted pair patch cord) with Bluetooth dongle - it didn't help, I still see garbage in log and Arduino still acts weird - it receives "phantom" keypresses from "debug" console.

Providing a schematic of your circuit would help. The best way to solve your problem is to first try to reduce the noise, this has to be done electronically.

As @jfpoilpret mentions, investigate the cause of the noise. It is usually easier to fix the cause than to remedy the data corruption.

Noise bad enough to cause Serial to corrupt is likely to cause other problems on I/O. Fixing the commands won't fix other issues, and it's likely you system would fail in another way.

I've added decoupling caps everywhere I could, it reduced the problems but didn't fix them entirely. Probably I will have to physically separate relays and Arduino to two different boxes, and will add separate AC-DC power supply unit for relays. I'll also order relays with optocoupling instead of existing relay board.

Just to be sure, you also used flyback diodes on relays right? How do you command your relays: directly from Arduino pins, through a transistor, a Darlington, a MOSFET?

I have dedicated relay board - http://dx.com/p/202361 - it has flyback diodes. By mistake I've ordered 12V board, not 5V - so I am powering it from Vin pin of my Arduino - so it gets unregulated power supply. Relay board is not a problem - it is probably the 220VAC power lines being close to Arduino's 5VDC lines. Will need to spread them farther, as I wrote above. I'll need to figure out how to insulate 5V lines though - I believed using wires in twisted Ethernet cable would be fine, but it looks like I need to switch to some shielded cable.

Serial1 on the Arduino Leonardo is hardware serial, not software.
There are several ways to read in multiple bytes from Serial.
Instead of detecting Serial.available() (i.e. non-zero), change it to Serial.available() >= 2
if (Serial.available() >= 2) {
  for (int i=0; i<2; i++) {
    buffer[i] = Serial.read();
  }
}

Or you can leave it as it is, and read into the buffer one at a time.
static int bufferIndex;

if (Serial.available())
{
    buffer[bufferIndex++] = Serial.read()
}

You'll need to detect the contents of the buffer in another if statement, and also deal with the bounds of the index.
Honestly though, noise is your issue here - this is an example of an XY problem. There's nothing inherent in using a microcontroller with relays that should mean that serial won't work.


text:
How to communicate arduino with Matlab
I have been working on a project which deals with analysing data from sensors to matlab. How do i establish this communication. Please help me

Presumably you need to find out how to do serial-port communication from matlab.  It's not clear that this is the best stack exchange site for that part of the problem, though the arduino part of message creation/parsing could best fit here.


text:
Arduino GPRS (GSM) shield (SIM900) no long pins
I have bought a SIM900 shield for an ordinary Arduino Uno board. The problem is that it doesn't have long pins on the bottom side, making it impossible to click on mu Arduino Uno.
The shield I have is this:

As you can see, there are identical pin spaces next to the red and yellow plastic female pin things. Can I just solder new pins in the free spaces and will it work like that?
I notice that the yellow and red plastic female pin holders on my board are on the free spaces in this picture. I supposed I can just use the adjacent foles to solder long pins so I can use it for my Arduino?

It might be wisest to send it back, since it's not functionally an "Arduino Shield" without those.  You could modify it, but if you have to do so to even try to use it, what will you do if it turns out not to work?

Good point... I haven't come around to soldering the pions on yet. However, it took 2 months to receive the package, I am not going to send it back to China... We'll see what happens :).

Yes, you can.
There is two methods of making shields stackable:

Use the quite hard to source extra long pinned headers to go right through and down (such as these https://www.adafruit.com/products/85) , or
Use separate headers and pins and (if you are using through hole) offsetting them.

Your shield uses the second method, but the descending pins haven't been populated.  By populating those pins you are just completing the build.

Thanks, then I will solder some pins to the board so I can stack it on top of my Uno :).

You'll have to clean out the holes first.


text:
Control/count rotations of a DC motor
Using an Arduino and an L293D IC, can I control the number of rotations a DC motor makes? Or can I only control the direction and speed of the motor?
I purchased a two-wheeled robot platform to learn Arduino programming and electronics. The platform is here: http://www.robotshop.com/en/dfrobot-2wd-mobile-platform-arduino.html
Each wheel is controlled by a DC motor. I followed Adafruit's tutorial (https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing) to control the motors with the help of an L293D IC.
Now I realize that I can't directly control the rotations of the motor. I can control the direction, voltage, and time of the rotation. For example: turn forward at 50% voltage for 500 milliseconds.
But that's difficult to translate into actual rotations. The speed of the motor varies according to voltage (like if I switch from 2AA batteries to 4AA's) and weight (adding sensors slows the motors down). Every time I change voltage or weight, I have to guess how much voltage/time causes a single rotation.
I think I should just buy stepper motors. Before I do that, I'll ask the community: Is there a way to control DC motors by rotations rather than time?

Other than with a rotary encoder?

I don't understand how to connect a rotary encoder to a DC motor. I see rotary encoder has a knob on it, and the three pins tell the Arduino how many degrees the knob has turned. But how would you tie that knob to the DC motor (or the wheel the motor turns)?

With gears, a belt, or a chain.

Or a shaft coupler, though that can require more precise alignment.  Steppers motors are generally not used for mobile robots as they are fairly heavy and power hungry for their power.  Depending on your resolution needs, you can also make your own optical or magnetic encoders, especially if you can work near the rim of a wheel. A quadrature system will give you 4 times the element resolution, so if you have a working diameter that can support 8 or 16 physical elements with two spaced sensors you can get a decent resolution (32 or 64 counts/revolution) for motion. See robotics.stackechange.com

Thanks for the advice. Would a question like this be more suited to robotics.stackexchange.com?

Or use a motor with built-in (gear and) encoder.

As you've discovered, there are a lot of variables involved, so you need some sort of feedback.  A popular way to do this is with an encoder, but depending on your needs, other kinds of sensors can make do.  For example, if your problem is keeping the robot going in a straight line, an electronic compass can help.  For a line following robot, the line sensors are usually enough.  Range sensors can track your distance.  You get the idea.

Stepper would be heavy and battery consuming, as Ignacio says.
Pololu makes an encoder for a wheel: http://www.pololu.com/product/1217, but obviously you can implement this in other ways too.


text:
How to use components that don't have a shield?
I recently started messing around with an Arduino and I have made a few "gadgets" using shields. I then wondered how I would go about using things I can't find shields for.
One specific thing I want to do is to be able to use the larger e-paper displays from Pervasive Displays (7'' and 10'') but a brief consultation with Google found no Arduino kits or shields. I then looked through the documentation of the timing controller for the 7'' display and found the information required to be able to use it (initiation, sending data to be drawn, opcodes, etc.). I then decided to check the Github repo for the examples for the 2'' displays and they seem to just do what the documentation says to do.
Is my observation naive here? Is it really as straightforward as following the documentation? No magic sauce?
Note: I don't have a clue how complex using the 7'' display actually is, I just used it as an example because I had just looked it up...

You discovered the secret of Arduino and its shields. Don't tell anyone black magic does not exist in Arduino-universe.

Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.
There are some common protocols for interfacing with devices, including SPI and I2C. From a quick peek at the driver interface sheet, it looks like they're using SPI. Well, your Arduino already supports that so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.
Note: It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.


text:
digital pin's current limit, ohm's law and DC motor
A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since V=RI, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance!

If you connect a motor to the Vcc pin, you are not connecting to an output! This is an input pin, for the processor's power... If your motor draw is OK for your power supply, then the motor will spin. If not, you will overload your power supply and (at best) the arduino will brown-out, probably rebooting repeatedly. You may as well just omit the arduino though. The point to watch with the 200mA limit, is 50mA x4 = 200mA so you can overload the chip with each output being individually fine..

The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a Totem Pole driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground.  Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.
The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible.  At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it will be notably less than the supply.
Connecting your motor to an ATmega pin is an extreme, far out of spec.  When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low.  Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage.  Finally, your motor will produce inductive kickback, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it.  Latchup is another possibility - a sometimes temporary condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a miniature space heater.
There really are no components on your typical Arduino board designed to directly control a motor.
Instead, for unidirectional control you should use a circuit with an NPN bipolar transistor, NMOS FET, magnetic relay, or solid state relay.  The latter are commonly available pre-assembled on shields.  With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.
For bidirectional control, look for a motor shield based on an H bridge IC such as the TB6612FNG or the less efficient bipolar L298 or L293/SN754410.  This basically puts a high current Totem Pole driver on each lead of the motor, allowing you to drive them high & low for one direction or low & high for the other.


text:
Reliably duplicate custom IR remote control with ATTiny85
This is something I'm struggling with for a while and fail to find solid solution.
The Arduino IR library provides method for recording arbitrary IR code and re-sending it. This gave me different results every time I recorded the IR remote, so I wrote a little code, based on interrupts, that try to record the IR rise/fall as accurately as possible.
I am working with ATTiny85 running at 8Mhz on internal oscillator.
Here is the code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(4,3);

const int dataSize = 40;
int data[dataSize];
int dataLength[dataSize];

void setup() {
  pinMode(0, OUTPUT); // 0 is IR receiver pin
  mySerial.begin(9600);
  mySerial.println("Start");
  attachInterrupt(0,IR_ISR,CHANGE);
  mySerial.println("Registered");
  sei();
}
volatile unsigned long prev = micros();
volatile unsigned long curr = -1;
volatile unsigned short index = 0;
volatile bool rising = true;
void IR_ISR()
{
  if (!rising)
  {
    dataLength[index] = micros() - curr;
    rising = !rising;
    return;
  }

  curr = micros();

  data[index++] = (int)curr-prev;

  prev = curr;
  rising = !rising;
}

void loop() {

  delay(5000);
  for (int i=1; i<dataSize; i++)
  {
    mySerial.print(data[i]);
    mySerial.print("(");
    mySerial.print(dataLength[i]);
    mySerial.print(")");
    mySerial.print("; ");
  }
  mySerial.println();
  index = 0;
}

Problem is that the milliseconds alter on each record of the remote control, here is an example of the output of 3 attempts of clicking at the same button of the remote control (I pasted only the first 5 IR modulations to avoid too much text, total is about 39):

Start
  Registered
14104(9496); 1184(672); 1184(616); 1160(656); 1176(672); ...
14096(9480); 1184(664); 1208(568); 1136(616); 1184(664); ...
14096(9384); 1216(576); 1136(616); 1184(664); 1208(560); ...

The format is: [microseconds from previous falling edge](microseconds from rise to fall);
As you can see, the results vary. According to the arduino.cc website, the micros() function has a 8 microseconds resolution on 8Mhz AVR's, but the difference between reads is bigger than that.
This is not reliable enough for me to solidly duplicate a remote control, and I'm looking for a resolution that will provide accurate results, as the magnitude of every deviation increases when the voltages are low (for example, with a 3v 2032 coin battery half discharged).

While the AVR is 8MHz, there is latency to service the ISR. Hence your observed differences.

This is true that ISR has some delay and does not provide real time values, but if what you say is correct, I should have measured the same deviation on every attempt, and this is not happening.

The exact duration of the pulses don't matter much. In your example, you see that in all three recorded samples that's
about 14000 (about 9400); about 1200 (about 600); about 1200 (about 600) etc.

What matters is that nowhere you have pulses of about 900 : in other words if the receiver detects a 672 pulse it will know that it's definitely a 600, not a 1200.
So if you send exactly those values, the receiver will recognize it.

That's an interesting observation; do you have a thumb rule about the rounding?

I use 412-712 for detect a zero, and 1187-2187 for detecting a one. 412-712 for the ir-burst between them. It looks like the remote is using the NEC protocol. I actually used excel to convert the raw data into a number, and to test if the boundaries were sufficient. I actually had to increase the boundaries a few times to catch the IR signal reliably. The values above are what I ended up with.

I used NEC remote for the post, but my intention is to reliably adjust to any custom protocol. Hence I am not sure that NEC values will suite me. Also, my final goal is to make the entire processing dynamically on the AVR itself, making it a real adjustable remote control, thus excel is not an option here :) I'll try to play with the rounding using code, see if that helps (if it will do the trick, I'll accept your answer).

Just sample n times the same code, and record the averages of pulse lengths. If you reemit that, you'll be sure you sent the same code. The way that code is interpreted by the receiver (NEC, rc-6, whatever) is irrelevant.

Eventually I decided not to use ATtiny85 since, even if using PROGMEM, it's just not up to the job of being a 'universal remote control', memory wise. But this is indeed the correct answer to my question.

I often see where people have problems with decoding IR signals from time to time, but very few say how they are attempting to do that? The first thing you really need to know is what is the carrier frequency? if you are using a TSOP IR DEMODULATOR, They come in several flavors and if you have the wrong one your results may not be all that rock solid.  There are one or two ways to determine this. have a digital storage scope and a fast photo diode (photo transistors are slow) which does no demodulation, just gives you raw IR . Once you determine your carrier frequency,  then purchase a IR demodulator TSOP that is closest to your carrier frequency, then your results will be more stable no doubt.


text:
DS18b20 Order of sensors on a cable
I have a string of 10x DS18b20 sensors on a single two wire line (parasitic power). Below is a table of the sensors, Where they are located on the wire, and in what order where they discovered.
Serial              Order on wire*   Order discovered
286305560100002c    1                7
28a158610100006a    2                3
28ad48610100006b    3                6
2851ae60010000ad    4                4
289b426101000089    5                8
28cd1161010000ce    6                5
2864026101000030    7                1
280c766101000026    8                2

I read this document on how the OneWire discovers sensors on the bus. https://www.maximintegrated.com/en/app-notes/index.mvp/id/187
My question: Is there a way to detect the order of the sensors on a wire?

I don't think so. There is nothing different between the different sensor, other than a minute difference in resistance in the wire, due to a longer length.

The discovery order is according to the search algorithm (which depends on the ROM/ID number). You can either put the sensors in order when you have their ID or use a mapping table in your sketch. The search algorithm does not determine the physical order of the sensors.

There is no way to detect position on the bus because all devices are connected in parallel. This is why a serial or "chain" wire, added to the newer devices, is required.
(To complicate matters, what is the "order of devices" - or even the meaning of "order" in a center-fed bus, or a circular, star, or other branched network? Order is just something we perceive when looking at an end-fed linear network. Electrons don't care. Think of a capacitor (unfortunately, the bus behaves like one but that's another story) with two plates, several centimeters square, and a dozen 1-wire devices connected from plate to plate. Now what is their order? Ow, my brain hurts! Let's go back to linear buses.)
The discovery order is a function of the set of binary device IDs on the bus. There are two ways I know of to come to know the physical ordering, both empirical (i.e., by observation):

Connect the set of devices one at a time, to a temporary bus such as a breadboard. With an Arduino, read the their IDs and tag them (human readable). With knowledge of the discovery alogrithm, or by running actual discovery on an Arduino with all devices connected, write down the IDs in the order they are discovered which is invariant for a given set of device IDs. Assemble your wired bus with the devices in this order.
(The reverse of 1 and quicker to build, and is what you've already shown in your question: Wire the bus. With a simple Arduino program, repeatedly sample all devices on the bus and report print their indices and temperatures (the indices will be in discovery order). One at a time, warm each device with your hand and notice which device index is affected. Write down the physical position (first, second, ...) and the index. This is the mapping table between position and index. Include it in your control algorithm.

So I would say that the DS1820 for professional use is useless!
There is no simple way to add or replace a sensor on existing temperature measuring appliance and to be sure about what are you measuring. Am I right?

@Satman Sometimes the sensors don't respond anyway, so what you might think as sensor 3 would become sensor 2 if sensor 2 didn't respond. I wouldn't say they are useless, but you would need to know the sensor ID (something you might find out on the bench) before deploying it into the field. Using the ID would be much more accurate anyway, because then you are certain that you got a certain sensor, and not just because it happens to be 5th in a chain.

what you can apparently do is use the User Data space set aside for the alarm and add an ID in there. I have not done this yet but am looking at this option as my sensor array has over 40 sensors in a line and ideally I would like the top one to be 0 and the last one in the chain to be 40.

I found this application note.
APPLICATION NOTE 4037
Regain Location Information by Leveraging the 1-Wire® Chain Function—A Simple Signaling and Protocol Method Determines Device Physical Location
https://www.maximintegrated.com/en/app-notes/index.mvp/id/4037

Note that 1) this technique is not applicable to DS18b20 and similar 1-wire devices; and the new devices - when using this capability - are not 1-wire any more, the chained signal requiring another conductor.


text:
How to use RS-232 sheild as software serial port?
I would like to be able to use a USB port at the same time as an RS-232 port with my Arduino Uno board. I unwittingly bought a shield that (I think?) overrides the USB port when it is mounted to the Arduino board:
http://www.dfrobot.com/wiki/index.php/RS232_Shield
Would anyone be able to give me any advice on how to connect the hardware so that I can have two serial ports accessible from my Arduino Uno? The format I was thinking was (Arduino => RS-232 Sheild):
GND => GND
5V => 5V
Digital Pin 2 => 232RXD
Digital Pin 3 => 232TXD
The accompanying code for initializing the serial port which I've written:
const int rxpin = 2; // pin used to receive
const int txpin = 3; // pin used to send
SoftwareSerial Serial_rs232(rxpin, txpin); // new serial port

Any ideas as to why this may or may not be a good method of using the hardware I have available for the purpose I had in mind?

GND => GND 5V => 5V Digital Pin 2 => 232RXD Digital Pin 3 => 232TXD

A better choice of board would be the Leonardo, since you could connect such a shield and use the USB port right out of the box. However, since you have the Uno, there is a solution.
From Arduino:

The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

It then goes on to reccomend the library AltSoftSerial.
Here is some example code from the link above:
#include <AltSoftSerial.h>

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() {
  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

It acts like a standard serial port, only you declare the connection as a variable first. This code is written for a board with an additional serial port, like you have.
All is good, except for one problem:
The problem is the shield is wired to connect to pins 0 and 1: the ones used by the USB adapter. The AltSoftSerial library uses pins 8 for TX and 9 for RX. (Note: You cannot use PWM on pin 10 on the Uno... it should still work as a digital pin.) In that case you would not attach the shield by plugging it into the Arduino, and you would wire it like this:

GND => GND | 5V => 5V | Digital Pin 8 => 232RXD pin 0 on the shield headers | Digital Pin 9 => 232TXD 1 on the shield headers

So then, you would be manually wiring the shield to the Arduino with jumpers. As long as it doesn't connect to any other Arduino pins I'm not aware of (it shouldn't besides maybe 13 for a LED or something like that), it should function like it would stacked and using pins 0 and 1.
Note: (Obviously) You cannot connect anything to the headers on the shield (You cannot connect to pin 5 and get a signal).

Thanks for the informative reply! Do you definitely advocate AltSoftSerial in place of the SoftwareSerial library then? Your hardware recommendation involving the Uno sounds great, but I'm unsure about why you've chosen the RX/TX digital pins on the shield, in favour of the pins labelled RS-232 on the wiki diagram?

@user_name I do think AltSS. would be the best choice: Arduino themselves said this library is better for simultaneous connections (see link in my post). For the second part, that should work as long as you don't stack them on top of each other. The reason is, both the USB adapter and the RS-232 use pins 0 and 1. By doing the wiring I said, you are "rerouting" them onto different pins on the Arduino. Just, most people don't have female jumpers needed to connect to the "232TX"/"232RX"... Remember use pins 8 and 9 and connect the TX and RX accordingly.


text:
SD.begin() fails second time
When I remove the SD card and try to open a file, I can detect the error properly.
But how do I detect that the card has been replaced after an error? My first thought was to call SD.begin() again but it appears that this function returns true exactly once and false thereafter.
Simplified example:
void setup() {
  SD.begin(pin); // called exactly once. Works.
}
void loop() {
  // stuff
}

But this does not:
void setup() {
  SD.begin(pin); // first time calling this function: works.
}
void loop() {
  delay(1000);
  SD.begin(pin); // always fails
}

I'd rather not reset the microcontroller just for this.

I'm looking for a SD.end() function somewhere. That is what you need, but I can't find anything in the reference.

I know this question is relatively old but still, if you wnat to run  SD.begin(chipselect); again first call if(root.isOpen()) root.close(); I added this to the library. This way SD.begin(chipselect) will return true if a card is present and false when it's not.

Are you talking about this fix?  AFAIK it's not been merged into master.  Still, a better solution than what I had before.  Thanks.

Update
A software reset, while inelegant, was much simpler to implement and debug than trying to add "retry" type functionality to SD.h. The other alternative would be to access SDFatLib.h or the other lower-level stuff (which SD.h is a wrapper for) directly, so if someone has that solution, I'll accept it instead of this one.
Original
Here is something, which is working well enough for me at the moment: does not reliably work:
bool SDState{false};
File LogFile;

bool trySDCard(void)
{
    // sanity check: maybe the SD card is actually here?
    LogFile = SD.open("test.txt", FILE_WRITE);
    delay(10);
    if (LogFile) {
        LogFile.close();
        return true;
    }
    int8_t counter{10};
    while (counter && !SDState) {
        SDState = SD.begin(TFT_CARD_CS);
        Serial.print(counter);
        Serial.print(" ");
        counter--;
        delay(100);
    }
    Serial.print("SD: ");
    Serial.println(SDState);
    return SDState;
}

void setup() {
    SDState = SD.begin(TFT_CARD_CS);
    Serial.begin(115200);
}

void loop() {
    // NB. Simplified a lot (exitMenuMessage(string) is my custom function defined elsewhere)
    switch (state) {
        case SD_RETRY:
            exitMenuMessage(trySDCard() ? "found SD card" : "no SD card");
            break;
    }
}

Seems to work Sometimes works if I insert the SD card while trySDCard() is running.


text:
Why is the regulator very hot?
We have an LED strip connected to output 6 and is powered by the Uno board itself.  Shouldn't be drawing too much current, only have 10 elements on the LED strip.  While this LED strip is connected to the Uno, I noticed that the regulator is getting very hot.
One thing we haven't done yet is to power the LED strips from an external source, which will be necessary since there will be many strips.  At the moment, the students are simply trying to debug their program with the small strip.

Most led strips draw a lot of current

How much resistance is present along with the LEDs?

How do you power the Arduino?

@jippie IIRC, the students are using one or both:  the USB input to the Uno, and sometimes the DC power in also, from an AC adapter.

What output voltage does the adapter supply?

Are you using a resistor in between the LEDs and pin 6?

I strongly suggest that you get a DMM and measure the current drawn by the board when powering the led strip. Google for ways to measure current with a DMM, as it can be tricky if you never done it before. Then, compare the value to those specified by the voltage regulator datasheet. The current should be within those values shown in the "Electrical Characteristics", and well below those from "Absolute Maximum Ratings".

How hot is "very hot"?  Warm to touch?  Physical damage upon contact with skin?

@anorton Quite painful to touch, so the immediate reaction is to move your hand back, but no skin burn in that short amount of time.

@Ricardo Can you make that advice into an answer?  Measuring the actual current draw beats guessing any day.

When a circuit is hot, it's very likely that it is drawing too much current. It may be a component that's getting more current than it's designed for, or a PCB track, or a wire.
So, before you do anything else, I strongly suggest that you get a DMM and measure the current drawn by the board when powering the led strip. Google for ways to measure current with a DMM, as it can be tricky if you never done it before.
Then, compare the value to those specified by the voltage regulator datasheet. The current should be within those values shown in the "Electrical Characteristics", and well below those from "Absolute Maximum Ratings".

All of the answers are excellent, but I'm picking yours since you explicitly say to measure the amps.

If you power the Arduino with an external power supply the on board regulator has to dissipate the voltage difference between input and 5VDC at the total current you draw from the board.
As Klaus Warzecha wrote in an answer to another question

The Arduino is just the brain, not the power station.

If the output voltage of your power supply is 12V, then the regulator will be dissipating 12-5V = 7 V at the total current drawn. Total dissipated power for eg. 150mA (just an estimate) would be P = V × I = 7 × 0.150 = 1W
The regulator will be pretty hot from dissipating 1W.
Mind you that the current is not limited to 150mA, enough LEDs can easily increase current and power. If the regulator is stressed (often) enough, sooner or later it will fail. It is better practice to power any load directly from the external power supply, taking the higher voltage into account.

A regulator normally get hot when is driven a current near to the maximum that could be driven, and its a normal thing the regulator keep warm.
A normal regulator like LM7805 could work until 125 C°.
If you try to drive more current that it can probably it will burn, so, maybe its time to you change your power supply to an external one to keep safe your Arduino board.


text:
Why can I not use pointers instead of array with PROGMEM?
I'm currently changing some libraries to use flash instead of RAM for string storage so that I do not run out of SRAM on a project.
Some strings in the library are declared in this manner:
const char *testStringA = "ABC";

This is different to how I normally see this done:
const char testStringB[] = "DEF";

However, I think that these two are equivalent when declared const and initialised in the declaration. Both work fine in code.
I attempted to move these to flash:
const prog_char *testStringC PROGMEM = "GHI";

I then found that this didn't work. It was producing gobbledegook when printed.
However, following the more usual pattern of:
const prog_char testStringD[] PROGMEM = "JKL";

works fine.
I can see in the disassembly:
00000068 <testStringC>:
  68:   04 01                                               ..

0000006a <_ZL11testStringD>:
  6a:   4a 4b 4c 00                                         JKL.

So it is clear the pointer and PROGMEM results in the string/array not being initialised.
Why is this?
Example code:
#include <avr/pgmspace.h>

const int BUFFER_LEN = 20;

const char *testStringA = "ABC";
const char testStringB[] = "DEF";
const prog_char *testStringC PROGMEM = "GHI";
const prog_char testStringD[] PROGMEM = "JKL";

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

void loop()
{
    char buffer[BUFFER_LEN];

    Serial.println(testStringA);
    Serial.println(testStringB);

    strncpy_P(buffer, testStringC, BUFFER_LEN);
    Serial.println(buffer);

    strncpy_P(buffer, testStringD, BUFFER_LEN);
    Serial.println(buffer);

    delay(1000);

}

Well, this question has been wisely answered in an answer to Stack Overflow question C: differences between char pointer and array.
Basically, what you're declaring as PROGMEM with,
const prog_char testStringD[] PROGMEM = "JKL";

is both the array and the memory it points to, that is, the elements of the array, both in current's scope stack. Whereas with:
const prog_char* testStringC PROGMEM = "GHI";

you declare a PROGMEM pointer to a constant string that may stay elsewhere in memory, but not declared as a PROGMEM string.
Though I did not test that, but you should try to declare:
const prog_char* testStringC PROGMEM = F("GHI");

to actually allocate the pointed string within the PROGMEM space. I guess it should be working, using Arduino's F() macro, which adds a lot of boilerplate code to actually have the same result as the array declaration.
As said in comments, if not in a global context, the PSTR() macro could be used instead of the F() macro.
Simpler is better: use the array declaration, not the pointer one!
Cf that other answer, the __flash qualifier is a third solution ;-)

I totally agree on the "simpler is better" - the array s far clearer. I just always get interested when something isn't immediately obvious.

F() returns FlashStringHelper which is essentially the same, but using PSTR() works fine (as long as you bring the consts inside a function).

indeed, I actually suggested first the PSTR() macro but changed to F() before submitting, because your consts are global ones in your Q, so I preferred to stick with the one that should work in both contexts.

What this line:
const prog_char *testStringC PROGMEM = "GHI";

does is to write prologue code to copy the characters in the string to SRAM, and then initializes the pointer stored in flash to this SRAM location. You must load the pointer via normal means, and then dereference the pointer as usual.
const char *str = pgm_read_word(&testStringC);
Serial.println(str);

This line:
const prog_char testStringD[] PROGMEM = "JKL";

creates the array of characters in flash, allowing you to access it as expected.


text:
Can I program a 3.3v chip on a 5v board?
I bought a Gertboard a while ago, and one of the features it has on-board is an ATMega328 (DIP). However, since the Gertboard is designed for use with the Raspberry Pi, it only operates at 3.3v, so the clock speed is limited to ~12MHz.
Programming it via the Raspberry Pi is quite cumbersome though. Instead, I'd like to transfer the chip to an Arduino Uno board so I can upload sketches from my desktop PC. I would then transfer it back to the Gertboard for normal operation.
The problem is that my Uno operates at the more typical 5v / 16MHz.
Is it safe to attempt this? Do I need to make any configuration changes in the IDE to tell it to account for a different clock speed?

avrdude over SSH not working out for you?

@IgnacioVazquez-Abrams I'm just exploring options really. I don't mind working on the command line if I have to, but I much prefer a GUI for code entry.

Samba to share the directory, and make to invoke ino to build. Messy, but it should do.

I've not seen a single ATmega328 not work at 16MHz at 3.3V before.

Sure, but that's not the question here.

@Cybergibbons The Gertboard has a 12MHz resonator built-in to provide the clock source, so unfortunately I can't change that.

I know it's not the question, which is why I didn't post it as an answer. Simplest solution, to me, would be to run both boards at 16MHz and not have to worry about anything else.

You could probably replace the avrdude executable on your machine with a script that remotes it to the pi, or better yet configure the IDE to use a different program as the programmer.  This would avoid the baud rate issue, and more importantly the constant chip transplantation that is likely to lead to bent pins or eventually worn out sockets.

The clock speed selected will affect both delay*() and millis()/micros() as well as the functions in <util/delay.h>, therefore you must use the target system's correct clock speed if you are using any of these functions. This can be easily done by editing boards.txt and copying an existing entry for the Uno and changing the value of the f_cpu parameter to match the target system (in this case, 12000000).
The difference in voltage does not matter, since the chip can run at either voltage and no connection is being made between the 5V system and the 3.3V system.

Unfortunately, the bootloader probably assumes 12 MHz.  In theory, the firmware of the 8u2/16u2 could be modified with a similar "mismatch" and likely result in the ability to utilize the bootloader with whatever odd baud rate results.  But it might be easier to improve the pi-based programming process, especially as this would avoid the constant chip transplanting.


text:
Use UTP Cable to transmit/receive data?
I was wondering if it was possible to use the utp port of a computer/laptop to transmit and receive data to an external device?
If you take a cat5 cable there are 8 wires, so lets say you have an Arduino would it be possible to use those wires for serial communication? If so how can I program the utp port? And is there a specification for this (for example use wire x for output and wire y for input..)
Thanks in advance,
Regards
Ps: I had no idea on which sub.stackexchange to ask it hopefully it suits here.

There is no such thing as a "UTP port".

@Vazquez-Abrams Sorry didn't know that, I assumed the ethernet port in a computer was called the utp port. How do you call it then?

You call the Ethernet port the "Ethernet port". Because it talks Ethernet.

By "UTP", I'm assuming you're referring to Unshielded Twisted Pair. The shielding and twisting aren't really relevant, because they're just physical characteristics of the cable itself. They don't have any bearing on the sender or receiver.
The salient point about UTP is that it uses differential transmission. That is, the data is sent down two wires at the same time, but one is inverted. The receiver uses the difference between the two signals to reconstruct the original data, eliminating any interference which may have been introduced en route.
Assuming the voltage level is safe (0-5v for most boards), you could connect each wire directly to an analog pin on the Arduino. If you read both continuously, and apply suitable thresholds/triggers in software to identify level changes, you could probably reconstruct the original signal.
It's definitely not ideal though, as ADCs are comparatively slow, and you would never be able to read both at exactly the same time. That means the transmission would have to be quite slow in order to work. The exact speed would depend on how quickly your program could poll the ADCs and process the result.
It would be much better to use some external circuitry to handle the differential signal. It could then produce a nice clean digital output which you could feed directly to any input on the Arduino. It should be able to run a lot faster, and leave your program free to do other things. Any good electronics vendor will stock a variety of ICs which would do the job, depending on your exact requirements.
Setting up your computer/laptop as a sender is a totally separate issue though. Many different ports use differential signals in some form, including ethernet, USB, and RS-232 (old DE-9 serial ports). Unfortunately, it would be very difficult to get direct control of their signal lines. You would almost certainly have to write your own device drivers, which is a pretty huge undertaking.
If you want to send serial data from your computer to an Arduino, the easiest way is just USB-to-TTL conversion. Most Arduino boards have this built-in, connected directly to the hardware serial lines on the microcontroller (which is how you upload programs/sketches). Alternatively, you can get external cables which do the conversion, and you can connect it manually to other pins, processing it using software serial.

Thanks for this answer, so I can't (easily) use that cable to communicate with my computer and an external circuit?

If you're using it as an Ethernet cable, then you can connect your Arduino to a network (usually via a switch/router). You would either need an Ethernet shield for your Arduino though, or an Arduino board which has Ethernet built-in. You can then program the Arduino to send/receive network traffic, using the Ethernet library.

At best you can connect at 10BaseT, which is the slowest implementation available for UTP. I believe I've seen a project in Elektor doing just that with only an AVR to do raw Ethernet. But you can't control the interface pins directly. The signals on ethernet are AC by nature because of the output transformer.

The Elektor article is called "Software-defined NIC, Ethernet-broadcasting op een AVR" (110733). The article was published in NL in April 2013, but I believe it was published earlier in other regions. It uses an ATmega644 clocked at 20MHz and is used with an old webcam to send images to a PC (approx. 2 images per second).


text:
Pull Chain Switch
I'm a bit new to electronics/Arduino projects, so am looking for some help on some wiring needed for a project involving this Pull Chain: http://proto-pic.co.uk/pull-chain-switch/
The chain works like a fan chain would.
I am using an Arduino UNO
I have wired up the pull chain to a mini breadboard with a light that turns on and off just to test it's working. What I want to do, is get an analog/digital read each time the chain is pulled?
Is this possible? If so, would you be able to help me with how it would be wired up, as I am completely new to the electronics side of Arduino. I simply need to get a reading each time the chain is pulled, I don't need it to switch a light on.
Thanks all!

Connect it between ground and an interrupt pin configured as an input with the pullup enabled. Configure the interrupt to trigger on any state change. Check the digital value of the pin in the ISR.


text:
is it possible to backup an uploaded program?
I have a cute robot built on Arduino Uno and Ardumoto, and I am trying to reverse engineer it first, and to add some new sensors afterwards.
I am stuck at how to deal with its program. I don't have the source code but I do not want to loose the program, yet in order to reverse engineer it I must write my own code and see if I can make it work.
Beware, I am a n00b to microcontrolers, and pretty lame to electronics (full of enthusiasm though).

Welcome to Arduino SE! The question here is a duplicate of this question. Although downloading and backing up are slightly different, the other post has answers that fit your criteria. If you feel that they are not duplicates, please edit this post using the edit button to specify what exactly you want. Thanks!


text:
Processing Input
How to make an input from computer using processing (like a password form) and trigger pin in arduino?
If you let some link to read more that would be very helpful.

What part are you having problems with? Sending data to Arduino from Processing or parsing data on the Arduino? Your question is very vague. Read up on http://arduino.cc/en/reference/serial

What exactly are you trying to accomplish in your project?  Please be more specific.

I want to enter a pass through processing and if its correct i want to trigger a pin.

Should it be the PC or the arduino which checks the password?  What happens if someone uses their own pc program instead of yours?

Arduino should have to contain the password

What have you done so far? Do you already have the PC-side app (with the password form)? How do you intend to connect the PC to your Arduino: serial/USB, or something else?

If you want the Arduino to contain the password, then a simple solution would be to put all the program logic there - generate a prompt, read input, check it, act on the result.  At that point the PC program can simply be any terminal emulator, written in processing or anything else.

On the processing side you need to communicate with the arduino using the Serial class. To set up use something like the following. It is a bit of guess work
to find which of the serial ports to use
Serial myPort;
void setup() {
  // List all the available serial ports:
  println(Serial.list());

  // Open the port you are using at the rate you want:
  myPort = new Serial(this, Serial.list()[6], 9600);
  myPort.buffer(2); // sets the size of the buffer, I send two bytes at a time
}

You can read a write using the Serial.read() and Serial.write() see https://processing.org/reference/libraries/serial/index.html for the processing serial references.

You need to have a look at the Serial commands: http://arduino.cc/en/Serial/read
http://arduino.cc/en/Tutorial/ReadASCIIString


text:
Create a Li-Polymer Battery Charger
I want to Create a battery Charger with the Arduino with real time battery status. I don't have any idea how to do that same time as the charging.

I know to use a serial monitor to get battery status but not to charge.

I would like to know how to do that simultaneously so that I don't over charge the battery.

This is the battery for Lumia 822
Nokia BP-4W 1800mAh 3.7v 6.7Wh

Do you know what is involved in charging a Li-Po battery?

Yes I charge it directly from a usb cable which is cut to take live and neutral lines

So you have a LiPo battery wired direct to a USB cable. You refer to 5v and GND as Live and Neutral...  Disconnect the whole lot immediately and walk away before you burn the house down!

Actually I charged it like that for many days but now I realize instead of charging quickly it can explode. And I see the charge is not like it is used to be it is a little less means it discharge quickly than before.

Sir is there anyway I can charge and monitor the same time using an arduino

Yes, but first you need to create a proper charge circuit.  Take a look at the schematics for the Sparkfun LiPower shield to start with,

Actually I can build that but how can  know when it is fully charged.

If you use a proper charge management chip it will have a status output signal that will tell you what it's doing - charge, fully charged, pre-charge, etc.  If you perform the proper charge (constant current etc) steps that you should do by using your Arduino to manage them then you will know when it's charged because your algorithm will be watching for that condition. If you just throw a random voltage at it and hope it works (BANG) then you have no hope, since you aren't properly charging it so can't know when the charge is finished because you're not giving it the right kind of supply

I'll add this to my answer but also put it here. Straight connection to a USB port is very unwise but may be viable if the port current-limits. A  usably OK result can be gained by: (1) Calculate Imax = same mA as battery mAh capacity. LOWER is OK.Higher is not. eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.  (2) Connect a ONE OHM resistor in USB to battery line. (3)Connect discharged LiPo battery to USB port via 1 Ohm. (4) Measure voltage across the resistor. 1000 mA gives 1.000  Volt 789 mA gives 0.789 V.  1234 mA gives 1.234 V. etc. ...

... If mA is LESS THAN Imax then this is OK to charge with. (5) Use Arduino analogRead() function to measure battery voltage while it is charging. BE SURE that value you read matches what a quality meter says. When Vbattery (Bat + to Bat-) AT battery measures 4.1 V STOP CHARGING, remove voltage. Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged). || For 10 bit ADC = 1024 counts total (0-1023) then for 5V reference 4.1V count = 4.1/5 x 1023 = 838 counts. | Using 830 counts to start with is safer. ...

...  | When battery is at limit and before removing Vcharge measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system. Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.  | BEST is to use a proper charger - they are not high cost ifyou look around and extend precious battery life.

@Majenko Your comments noted and generally agreed with. I have extended my answer to match what he says he is doing. If he/she does as I have said all may be moderately well. If not it is unlikely that better can easily be done to advance the cause.

also take a look at https://www.youtube.com/watch?v=A6mKd5_-abk

(1) A simple method
BEST method is to use a proper charger - they are not high cost if you look around and doing it properly extends precious battery life.
Next best in this context is my "better" method in 2. below.
BUT, given the system you say you are using now, the following very simple method will greatly improve your result and ave your battery from an early death.
You need a 1 Ohm resistor and a voltmeter that you can trust to read a 4.1V votage accurately. Without these the simple method risks battery damage or destruction - just as your present method does.
Warning: Straight connection to a USB port is very unwise but may be viable if the port current-limits.

If the current is ever higher than the rated maximum then battery destruction may occur.

If the battery voltage ever exceeds 4.2V at room temperature battery damage WILL occur and battery destruction may occur.

Worst case a badly treated battery can turn into a flaming inferno in seconds.
A usably OK result can be gained by:
(1) Calculate Imax = same mA as battery mAh capacity.
LOWER is OK. Higher is not.
eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.
(2) Connect a ONE OHM resistor in USB to battery line.
(3) Connect discharged LiPo battery to USB port via 1 Ohm.
(4) Measure voltage across the resistor.  The voltage will be 0.001 Volt for every mA that flows. eg
1000 mA gives 1.000 Volt
789 mA gives 0.789 V.
1234 mA gives 1.234 V. etc.
If the measured mA is LESS THAN Imax in (1) above then this is OK to charge with.
(5) Use Arduino analogRead() function WHILE CHARGING to measure battery voltage.
BE SURE that the voltage that you read with the Arduino matches what a quality meter says.
When Vbattery (measured from Bat + to Bat- AT the battery) measures 4.1 V STOP CHARGING, remove voltage.
Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged).
For 10 bit ADC = 1024 counts total (0-1023) then
for 5V reference 4.1V count = 4.1/5 x 1023
= 838 counts.
Using 830 counts to start with is safer.
When battery is at the upper charge limit,  and before removing Vcharge, measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system.
Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.
The BEST method is to use a proper charger - they are not high cost if you look around and they extend precious battery life.
._______________________________
(2) A better method:
LiIon (Lithium Ion)and LiPo (Lithium Polymer) batteries are functionally the same for charging purposes. I'll use the term "LiPO" from here on. I'll assume single cell batteries as most in cellphones and similar are. If the terminal voltage is between about 2.5V (should really be higher) and 4.3V they are single cell,
LiPo batteries have 4 main charge areas.

Under about 2V = dangerously dead. Discard

2V to about 3V = under voltage - charge very slowly

3V to 4.2V = charge at CC  = Constant Current.

On reaching 4.2V charge at CV = Constant Voltage until current reduces "automatically" (under battery chemistry control)  to about 1/4 x max rate.

Max charge rate is set by the manufacturer but is almost always the numerical mAh rating in mA. eg for a 1000 mAh battery max rate is 1000 mA. For a 3300 mAh battery it's 3300 mA etc. In a very few cases it is lower - maybe =half standard values and for a very small number of cells its higher - assume you do not have those.
Max voltage MUST NOT exceed 4.2V at room temperature. Lower, say 4.1V, does no harm and increases battery cycle life while slightly reducing capacity per charge.
The battery mAh rating is known as "C".
If C = 1200 then a cahrage rate of 1200 mA = C/1,
a charge rate of 300 mA = C/4,
a charge rate of 12 mA = C/100 etc
An easy charging method that gives long cycle life and about 70% to 80% of max possible capacity and a fast charge is

Determine max charge rate = C  = Imax = same mA as battery has mAh capacity.

If Vbattery is < 3V, charge at C/20 or less until Vbattery reaches 3V.
If Vbattery never reaches 3V it is dead.

When V_battery = >= 3V, charge at C/1 until Vbattery = 4.2V ( or 4.1V)

Finished!.

Remove applied voltage. DO NOT EVER leave 4.2V applied to a charged battery.

A more usual method that is only slightly harder is.

Monitor charge current.

Charge as above until Vbat = 4.2V.

While holding Vbat at 4.2V monitor charge current. This will fall as the battery absorbs additional charge.

When  Icharge falls to C/2 or C/4, stop charge. C/4 adds slightly more charge than C/2 but shortens cycle life.

Again - DO NOT leave 4.2V applied to battery once charged. Doing so will destroy the battery rapidly. Remove all voltage once charged.

.______________________________
Battery University:
Charging Lithium Ion & LiPo
Increasing lifetime
Index
.______________________
Q&A

Q: This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept.

Read the above material and the battery university pages.
4.1 V ABSOLUTE MAXIMUM is what I recommended.

Most LiPo single cell batteries are labelled as 3.6 V or 3.7 V as that is approximately the average voltage across the discharge cycle.

When fully charged they are at about 4.2 V (or 4.1 V if you take my advice - which you should :-).

As they discharge the voltage falls and by the time they get to just above 3 V they are essentially fully discharged. They should never be discharged below 3 V as it damages them and there is only a tiny amount of energy left.

So 4.1 V ABSOLUTE MAXIMUM is good
MEASURED WHILE CHARGING and
AT the battery terminals or very close to them.
ie no long leads or resistors or connectors.
If using an Arduino to measure battery voltage,  connect an Arduino ground lead to battery negative with as short a wire as practical and the ADC +ve input to the battery +ve at the battery connection point.
So once more: A LiPo battery labelled as 3.6V or 3.7V can and should be charged to 4.1V maximum and never discharged to below 3V.

Interesting I learnt many things from here but is there any way I can charge and monitor the same time. So I don't overcharge the battery as you mentioned

This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept

@user3224757 The answer to your above question in my comments has been deleted and is now in a slightly better form in "Q&A" at the end of my answer.

Also i would like to add Dave's video from EEVblog https://www.youtube.com/watch?v=A6mKd5_-abk

@Martynas You could posy reference to Dave's Video as an answer of your own - perhaps with comments on the key things he teaches in it. FWIW I personally find videos far less useful as though they can be information rich they are also compulsorily serial-access and at the presenter's rate. I prefer text and still images which allow a dgree of spatial multiplexing and parallel access :-.)

Sure @RussellMcMahon text is way better, but i am not sure OP's experience in electronics, and Dave covers a lot. I added video just to get the idea, how it works, and how to make it in very low level of experience :) Anyway this is not a short answer to that short question :)


text:
Are there any good and maintained libraries for using DS2482 I2C to 1-Wire bridge?
The DS2482-100 and DS2482-800 are I2C to 1-Wire bridges which are useful for driving complex 1-Wire networks.
These are natively supported by a number of packages in Linux so you can interface easily with them on a Raspberry Pi.
I was surprised to find there is not an obvious library for accessing them on an Arduino however.
I have found the following:

An Arduino library - has some quirks and not-maintained.
Part of AVR-Liberty - less quirks, not sure if maintained, not "Arduino" as
such, more AVR.

It is helpful to be able to rely on maintained libraries to deal with any changes to the Arduino environment.
Arduino libraries are often easier to use than ones designed for AVR in general, which means more people are able to use the software.
Is there a better library available?

The only thing i know of is the wire library, but I2c to TWI. There are some teensy onewire libraries out there as well, but it looks like that is not what you are looking for. This may be a good time to start your own library :-)

An unmaintained library does not necessarily mean a bad library. If it is feature-complete and flawless, then it does not have to be maintained. Also, the fact that no commit occurs for a long time does not always mean that there's nobody to maintain it.

At least, with an open source library you can easily change the code yourself if it is buggy or does not fit your needs. The DS2482 datasheet can help for that.

No, unmaintained doesn't always mean bad, but when there are issues with it and it hasn't been updated for several years, it generally is bad.

@Cybergibbons have you tried it? Some issues may not be relevant to all library users. As far as I see, there's only one issue open on the mentioned Arduino library, and it is just one month old; I would not consider that unmaintained (yet).

Yes, it isn't very reliable - seems to miss readings periodically, and needed modifying to deal with that issue. Also not fully implemented feature set of DS2482.

The library didn't deal with parasitic power, hence the unreliability.

I use this library to communicate with the DS2482 but I can not subsequently communicate with a DS2401+ via 1-Wire. I use the I2C 1-Wire Click (DS2482-800) and on the 8 channels a DS2401+. https://www.mikroe.com/i2c-1-wire-click -> I2C 1-Wire Click (DS2482-800) https://pdfserv.maximintegrated.com/en/ds/DS2401.pdf -> DS2401+. Can you please explain me ? Thank you

I have implemented a library, based on the Paeaetech one linked to above, but tidying up defines, fixing the listed issue, adding lookup table based CRC and support for passively powered sensors.

I believe the library linked by Cybergibbons has a bug in
uint8_t OneWire::wireSearch(uint8_t *address)
A discrepancy at i = 0 (bit zero in this library, id_bit_number = 1 in a Maxim example) only follows the direction = 1 path and fails to find ROM addresses where bit zero = 0 (i.e. even family codes are missed when mixed devices, some with even and others with odd family codes, are present on the 1-wire bus).
A fix I have just implemented and appears to work is to modify the library to declare searchLastDiscrepancy and last_zero as int8_t (not uint8_t), initialise/reset them to -1 (not zero) and, near the end of the method
    if (!last_zero)
            searchLastDeviceFlag = 1;

becomes
    if (last_zero == -1)
            searchLastDeviceFlag = 1;

I hope that helps.