What does it take to compile Linux on Arduino, if at all possible? Is it possible to run Linux on Arduino? If yes, what steps and limitations need to be considered? If not, what are the limitations that prevent this?

Linux is a very complex operating system, but it may be able to fit on an Arduino. Things to consider:

There is no current AVR port of the source code.
You would have no graphics, instead access the terminal over UART.
The filesystem driver would have to be rewritten to access internal flash or an external SD card.
It would be extremely slow! The ATmega328 would run at 16 MHz, or about 20 MHz max (overclocked). Most Linux machines run at a minimum of 400 MHz, and more with graphics.
You would probably need some extra RAM, probably a good idea to use an ATmega2650 (the one in the Mega), which has 16 times the RAM of the Uno. You could also use a Due (6x as fast as the Uno, more RAM).
You may have to write special USB drivers for OTG (on the Due) or MAX3421EE (Mega ADK, USB host shield).

In short, it would take a lot of time and effort, and probably would be too slow for everyday use. If you really want Arduino Linux, check out the Yún.

It is possible, however it would be a pain because you would have to write  it in C. (not to mention the extra hardware needed like an sd card shield and extra memory chip(s)) Something like Ontas, a kernel I wrote in C for the arduino, would help as It has support to add drivers, at the expense of making the void loop function repeat slower. (This is not as big of a deal as you might think it is)
(Ontas is still under development and new features are added all the time)

Click here for the link to the .ino and accompanying .h files


Is it possible to upload a program from a tablet? Is there any easy way to upload a program/sketch from an iPad or Android tablet without adding extra an shield (Bluetooth or Wi-Fi)?

If not, can it be done using shield? Which shield is preferred?

Also what are the IDE options available?

I figured out a way to do this without having to port the compiler to iOS. It only works with the arduino Yún, but the Yún can send code to other arduinos with an spi cable.

Install an SSH app on your device so you can communicate with the arduino
Using that, install Ino on your Yún, a command line arduino compiler
Create a file, put your code in it, then save it
use Ino to upload your code!

kind of confusing, but it could work!

Yes, you can upload over BLE with free(mium) iOS app - Apploader

http://www.apploader.info


Maintaining Arduino on Ubuntu 14.04 I used to use Arduino on Windows but I changed to Linux last week and I was wondering how to have a maintained version of the Arduino terminal:

Indeed, I'm not sure my version is quite recent:

The icon seems to have lived ages without a little lifting...

Maybe I'm wrong but it seems so when I open the "Tools" option for instance...

Furthermore I tried to copy and paste this code:

//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

int speakerPin = 9;

int length = 28; // the number of notes

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

// play the tone corresponding to the note name

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo); // rest

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   // pause between notes

   delay(tempo);

}

}

And not all of it appeared in the Arduino terminal.

If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using apt-get:

sudo apt-get update
sudo apt-get install arduino arduino-core

However, this way you get a very old version (currently 1.0.5). Obviously, it is not updated too often if at all.

If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:

sudo apt-get remove arduino arduino-core
sudo apt-get autoremove

Better way is to download and install Arduino IDE yourself. This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.

Open a terminal window (e.g. by pressing CTRL-ALT-T), and run uname -m to check if you are running 32 bit or 64 bit platform:

uname -m

See output:

x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Go to Arduino Download page on Download the Arduino Software and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.

In a terminal window extract the package and move it to your preferred location, e.g. /opt. You need sudo rights to move it to /opt. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for .ino). See the example commands below for installing the latest 32 bit version as of the time of writing to /opt.

cd ~/Downloads
tar xf arduino-1.6.7-linux32.tar.xz
sudo mv arduino-1.6.7 /opt
/opt/arduino-1.6.7/install.sh

You can also start the IDE from the terminal:

/opt/arduino-1.6.7/arduino

Download the IDE from Ubuntu Store. The latest version is there.


exchanging data between two hc05 bluetooth modules Iam working with gyroscope and Iam trying to send its values from one bluetooth(HC-05) module to another bluetooth module but the data exchange is not happening and I have used 2 arduino boards to do it.

Is there a simple way to do it?

I think there is no simple answer for that. First you have to pair 2 HC-05 modules. To do so, you have to configure one HC-05 as slave, and other HC-05 as master.

Steps for SLAVE:

Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
Note the values of AT+PSWD?, AT+NAME? and AT+ADDR?(let's say 1111:22:123456) commands. You might set the password to 1234 for easy remembering. Issue AT+PSWD=0000...
Be sure to set the module to slave mode by issuing AT+ROLE=0 command.

Steps for MASTER:

Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
Reset the module to its original state by issuing AT+ORGL command.
Remove the previous parings(if any) by issuing AT+RMAAD command.
Set same password as slave by issuing AT+PASSWD=0000 command.
Change the role to master; AT+ROLE=1
Set connecting mode to any address it sees; AT+CMODE=1
Initialize the SPP profile lib ; AT+INIT
Be sure that you see the slave HC-05 module, AT+INQ command will list the modules you see.
Be sure that you see address of the slave module(1111:22:123456).
Last of all enter AT+LINK=1111,22,123456(note the commas).

With these steps you should exchange data...

You will get your required details here.


Current Arduino STL Libraries I was going to update this question but I thought that this was different.

I have been trying to get std::vector to work with the latest Arduino. I have tried downloading several libraries found online but I can not get one of them to compile correctly. So here is my question, does anyone CURRENTLY know of a Arduino STL Library that is working?

StandardCplusplus: As stated above I tried to use this library but run into problems with the new/delete functions.

Andy Brown's AVR-STL Library doesn't even seem to come close to compiling.

If anyone has a working copy of these two I would love to have a copy or if you can tell me how to get them to compile. Otherwise I really need to find a way to get Vectors working, does anyone have any ideas?

Edit

I didn't want to answer this question so it is still active as I am sure there will be additions to this. Anyways I FINALLY got a library to work (for now, so far). I downloaded the StandardCplusplus library and found that in order to get any of the stl functions to work you have to add an include to the "StandardCplusplus.h" file before EVERY use, not just in the first file as stated in the Wiki on the Project page.

So I was able to get vectors to work using the following:

#include "StandardCplusplus.h"
#include <iterator>
#include <vector>

vector<int> test;

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

   test.push_back(1);
   test.push_back(2);
   test.push_back(3);
   test.push_back(4);
}

void loop(){
   for (int i = 0; i < test.size(); i++){
      Serial.println(test[i]);
   }
}

I would still like to know of other working STL Libraries as it seems that there are tons of outdated and old libraries out there.

I maintain an Arduino plugin that's a port of uClibc++ (just like the defunct StandardCplusplus library). It's available in the Arduino library manager for Arduino versions 1.6.10 and higher. It's called ArduinoSTL.

pay you attention which kind of arduino do you use. it can compile for Mega but not for Leonardo for example


Arduino Uno and FastLED WS2812B Glitching I’m using an Arduino Uno and a fastLed WS2812B.
I have the leds set up correctly. Every 2 seconds, the lights pause of about a second and display seemingly random colors.

Does anyone know what's wrong?

My code:

#include <FastLED.h>

#define LED_PIN   7
#define NUM_LEDS  10

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

}

void loop() {
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(0,0,255);
    FastLED.show();
    delay(100);
  }
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(255,0,0);
    FastLED.show();
    delay(100);
  }
}

I have run the code on the Arduino simulator online. If it is working in the Arduino Simulator chances are less that it has to do something with the code itself.
Hence, also as the root cause was found to be about sharing the ground @Majenko
This is also one example of solving the problem step by step. validating one section after the other. using the simulator you can verify that the code is working fine. later, proceed to verify the hardware. I hope this helps.
You can verify the FastLED code here (you can modify the parameters)


Can I port a project built on Arduino Uno to a standalone ATmega328 using the exact same code? I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?

Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.

If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.

Update:

  There's a bit more required, for example, the clock rate needs to
  match or the timing will be off ...

I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.

If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed without modifying the code for those differences.

You can run any code on an ATMEGA328P that you can run on an Arduino Uno. For maximum compatibility, you would configure the ATMEGA328P with a 16Mhz crystal/resonator.
There are instructions for using an Arduino Uno as an ISP for programming other devices, many of which require a Uno with a DIP version of the ATMEGA chip which can be removed.
What you cannot do is directly run code for an ESP8266 on an ATMEGA328P.


3-Way Bluetooth Communication? I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?

To reiterate what is going on here:
I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.

I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.

Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.

Thanks a lot!

Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.

Hope this gives you a place to start exploring.

Ok

So From Whatever I can Understand you could do this.

make one of the boards talk to a master control board.
make the control board talk to your phone.

Why don't you change  your approach

Make the board A communicate with board B with Bluetooth.
Use different pins to setup communication b/w phone and board b.

Arduino to Arduino Bluetooth- http://www.martyncurrey.com/arduino-to-arduino-by-bluetooth/

Arduino to phone via Bluetooth- http://www.instructables.com/id/Connect-Arduino-Uno-to-Android-via-Bluetooth/

PS: - USE DIFFERENT PINS!


Simultanous read and read/write on two serial connections At the moment I'm using two softserials to connect to a GPS and an GSM module.

It seems not possible to have two open software-serials. So I was looking for an solution

After the initial-setup, the GPS module is only needed to be read from; while the GSM module needs to be bidirectional. So:

GPS > listen only
GSM > listen and write

Now I came across the GPS library from Adafruit, which uses an interrupt to receive data. Is this instead of a software serial. Or do I again run into the limitation?

An other solution might be to use the D0 and D1 to attach eg the GPS module. But than I won't be able to see the debug messages in my serial monitor. Is that correct?

Sorry in advance for these n00b questions. But I'm frustrated the things dont work as I want :)

edit

This is the adafruit GPS board.
And the board with whom it is connected: Gboard
The Sim900 is connected to D2/D3 and the GPS is connected to A2/A3.
D0/D1 are connected to a FTDI breakout board, which is plugged into my USB.

Adafruit_GPS.h (line 132-), which is included in Adafruit_GPS.cpp (line 13) refers in turn to the SoftwareSerial library on AVR platform and Arduino IDE version > 100.

#ifdef __AVR__
#if ARDUINO >= 100
    SoftwareSerial *gpsSwSerial;
#else
    NewSoftSerial *gpsSwSerial;
#endif
#endif

This means it uses software serial on an Uno. It also means if your problem is indeed with Software Serial, that is the library to check for bugs / updates or commit a patch to.

There is a working example of this, using the Adafruit Ultimate GPS, and the Arduino GSM shield
http://www.mallinson-electrical.com/shop/gpsgsm
I hope this helps


Can you access the EEPROM of an ATtiny with Arduino Code? I'm attempting to reduce the amount of RAM being used by my program by writing some values to the EEPROM of my micro controller. I'm currently programming on the ATtiny85 which has 512 Bytes of EEPROM. According to the documentation this is how you write to EEPROM:

#include <EEPROM.h>

void setup() {
  EEPROM.write(0, 1);
  EEPROM.write(1, 0);
  EEPROM.write(2, 3);
  EEPROM.write(3, 2);
  EEPROM.write(4, 1);

}

For some reason this isn't working for me and I can't seem to find the error. Am I programming this wrong or can the EEPROM of the ATtiny simply NOT be accessed with Arduino Code?

Here is the Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet-Summary.pdf

Here is the second sketch I'm using to test the EEPROM:

    #include <EEPROM.h>

void setup() {
  EEPROM.write(0, 1);
  EEPROM.write(1, 0);
  EEPROM.write(2, A3);
  EEPROM.write(3, A2);
  EEPROM.write(4, A1);

byte CLK = EEPROM.read(0);

}

void loop() {

  if(CLK == 1)
  {
    for(int i = 0; i < 3; i++)
    {
    digitalWrite(0, HIGH);
    delay(1000);
    digitalWrite(0, LOW);
    delay(1000);
    }
    exit(0);
  }
  else
  {
    for(int i = 0; i < 100; i++)
    {
    digitalWrite(0, HIGH);
    delay(1000);
    digitalWrite(0, LOW);
    delay(1000);
    }
    exit(0);
  }

  exit(0);

}

The Arduino EEPROM library is compatible with the ATTiny range of AVR microcontrollers as the library itself is built on the standard Atmel AVR avr/eeprom.h 'library' so it is compatible with all the AVR microcontrollers.

The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. Reading though does not cause much damage though.

Also note that using exit(0); will stop the ATTiny from doing anything else after it is called so I hope your intention is to only run the loop once, if not this would account for either not seeing anything or it only ever running the blinking cycle once.

To answer your follow up question. Yes you can run one sketch to set you values in EEPROM and then use another sketch to read those. That us usually the point of EEPROM it is a memory type that "keeps its value while there is no power".

Also you need to make sure the ATTiny is set to preserve EEPROM during upload with the ISP, this is done with the fuse settings. You need to look for a tutorial on fuse calculators for the AVRs. To set the EESAVE you need to set the High fuse to 0xD7, you can change this in the boards.txt file. Here is a fuse calculator.

If the code that is on your question at the moment is being used you won't be seeing anything as it needs the pins to be set with pinMode. That's a note for others that see this.

Next what you can do is run a basic test code which blinks the LED without anything else going on.

Basically:

void setup(){

 pinMode(0, OUTPUT);

}

void loop(){

 digitalWrite(0, HIGH);
 delay(1000);
 digitalWrite(0, LOW);
 delay(1000);

}

Below is the code you have written, it works I have it running in front of me.
I have commented it and changed a few things to make it work as intended, although the intention is not clear.

#include <EEPROM.h>

byte CLK = 0; //This is a global variable with an initial value

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

  EEPROM.write(0, 1); //set the pin to D1
  delay(5);

  //read from EEPROM address 0
  //this sets the value of the global variable CLK
  CLK = EEPROM.read(0); //place this inside a function

  //just to give an example...
  byte PIN = CLK;   //PIN variable is a local variable

  pinMode(PIN ,OUTPUT); //using that local variable

}

void loop() {
  // put your main code here, to run repeatedly:

  // Note: the below if() will always be true as the value
  // of CLK is never change and shouldn't be changed as
  // it will change the pin number of the output

  if (CLK == 1) {
    for (int a = 0; a < 3; a++) {
      digitalWrite(CLK, HIGH);  //this uses the global variable
      delay(1000);
      digitalWrite(CLK, LOW);
      delay(1000);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
  else {
    for (int a = 0; a < 100; a++) {
      digitalWrite(0, HIGH);  //this has a predefined pin no.
      delay(500);
      digitalWrite(0, LOW);   //this has a predefined pin no.
      delay(500);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
}

Not sure if things have changed so significantly since the question was asked originally but I'll answer using the Atmel AVR libraries.

Don't assign the EEPROM value to a variable as then you are wasting precious SRAM again. EEPROM has unlimited read cycles.

I can't find any current references to EEPROM.read() as a Macro or function in the Arduino IDE. Instead there is the AVR EEPROM library which uses eeprom_read_byte() as shown below.

#include  <avr/eeprom.h>

// the setup routine runs once when you press reset:
void setup() {
/* The "131" value is used to prevent damaging excess EEPROM writes on every restart.
   If you want to try setting a different GPIO pin for LED blink change the test value in
   both the read and following write to EEPROM address 511 */

    if (eeprom_read_byte((uint8_t*)511) != 131) {
       eeprom_write_byte((uint8_t*)511,131);
// Store the GPIO pin number in EEPROM address 1
       eeprom_write_byte((uint8_t*)1,1);
    };
// initialize the digital pin as an output.
    pinMode(eeprom_read_byte((uint8_t*)1), OUTPUT); // LED pin value stored in EEPROM address 1
}

// the loop routine runs over and over again forever:

void loop() {
    digitalWrite(eeprom_read_byte((uint8_t*)1), HIGH);
    delay(1000);               // wait for a second
    digitalWrite(eeprom_read_byte((uint8_t*)1), LOW);

    delay(1000);               // wait for a second
}


How to select which resistor is required for my curcuit to reduce voltage I am trying to connect arduino and esp8266 as like this

I know arduino runs at 5V and RX of ESP8266 should not have voltage more than 3.5V. If you see my diagram there voltage is large than need on RX of ESP8266. I know resistor can help me for this and ohm law.

V = R.I => R = V/I

So I want to understand how should I select what ohm resistor for this cuicuit ? Can anyone explain with some calculation using ohm law ?

A resistor can only drop a certain voltage when there is a certain current - as you know from Ohm's Law.  If you have resistance R and current I the voltage dropped is R×I.

So if the current changes the voltage changes - and if the voltage changes the current changes.

So what do we do? Well, we have one known fixed value, and that is the 5V from the GPIO pin. And since that is fixed (at least when HIGH) we could add a fixed resistance to it to give a fixed current, right?

So let's do that. Pick a random value. Experience teaches you that certain values are better than others, but the actual value doesn't matter too much, as long as:

It's not so small that too much current flows out of the GPIO pin, thus damaging it, and
It doesn't create too high an output impedance, which we will come on to later.

10kΩ is a good figure to start with. Not only does it keep the current low enough, but it's pretty much guaranteed that you'll have one in your bits box somewhere. And we connect it to the GPIO like this (we completely ignore the ESP8266 for the moment):

simulate this circuit – Schematic created using CircuitLab

When TX is HIGH it's at 5V. It's connected directly across a 10kΩ resistor, so therefore we can use Ohm's Law to calculate the current - I=V÷R = 5 ÷ 10,000 = 0.0005, or 0.5mA. (Another useful thing with 10kΩ resistors is it makes calculations nice and easy).

Now, what if we were to split that resistor in half, so it was two 5kΩ resistors in series? The circuit would look like this:

simulate this circuit

Resistors in series add together, so those two 5kΩ resistors are the same as one 10kΩ resistor. We know that 0.5mA flows through 10kΩ at 5V, so the same must run through 5+5kΩ at 5V. But now we have two fixed value resistors. Because of that we can now apply Ohm's Law to each one to find the voltage drop across it.

So with 0.5mA flowing through a 5kΩ resistor we get V=I×R = 0.0005 × 5000 = 2.5V.  That's 2.5V across R1 and 2.5V across R2, since they are both the same. That's exactly 50% of the 5V across each one. At the point in the middle, point "A" on the schematic, you can see that the voltage has been cut in half. Once the current has gone through one resistor the voltage has halved (dropped by 2.5V), and when it goes through the other resistor it drops the rest to 0V, which is the other 2.5V.

If we were then to connect something to point A it would see a logic signal of 0V (LOW) and 2.5V (HIGH) from our 0V (LOW) and 5V (HIGH) signal.

But 2.5V is too low for the ESP8266 to read. Well, the answer is simple. We see that if we use two resistors we divide the voltage into two. The same applies for dividing it into three. For instance:

simulate this circuit

The sum is 10kΩ (well, 9.9kΩ but we'll call it 10kΩ for simplicity - a third each resistor, 3333.33Ω). 0.5mA through 3.3kΩ would be 0.0005 × 3333 = 1.66V. Funnily enough, 5 ÷ 3 = 1.66, so we have proved that it splits it into a third. That means at point A 1.66V of our 5V has been dropped (across R1), so 5V is now (5-1.66) 3.33V. Perfect for the ESP8266. Incidentally, point B would be 1.66V (3.33 - 1.66).

So now we have three resistors and the result we desire. However it's a little messy still. Remember that resistors in series add together? So why not add R2 and R3 together into a single resistor? That would be 6.6kΩ. Now I don't know of a 6.6kΩ resistor that's easily available, but 6.8kΩ ones are, though chances are you may not have one. If you did then a 3.3kΩ and a 6.8kΩ would net us near enough 3.3V to be usable.

But as I say you may not have one. So you pick resistor values that you do have. For instance you could use a 2.2kΩ and a 4.7kΩ, or a 10kΩ and a 22kΩ - anything that gives a roughly 1:2 ratio of value (the "upper" R1 resistor about half the value of the lower "R2" resistor).

Now - we get onto that mysterious phrase I mentioned earlier: Output Impedance. You recall we calculated the current that flows through the resistors - 0.5mA. The higher the value of resistors we use the lower the current. Well, that current not only flows through the resistors - a small amount also heads off into the ESP8266. The more that the ESP8266 wants for its RX pin the less there will be available for the R2 resistor. The result? Less current through the resistor = less voltage dropped across it.

The current drawn by the pin attached to point A on our circuit affects the voltage dropped across the resistors.

Too much current drawn and the voltage at point A will droop. Less will be dropped across the (current starved) R2, which means more must be dropped across R1. So point A is now a lower voltage. If that gets too low (too much current is drawn) then the RX pin can't read it properly.

Increasing the resistances decreases the current, but also decreasing the resistances increases the current. If the current is increased then the fraction of the current needed by the RX pin becomes reduced compared to what is available, so the output voltage drops less.

This output impedance, in case you're interested, is measured in Ohms, and is the same as the value of the two resistors in parallel - so (R1×R2)÷(R1+R2).

For instance, I tried connecting an ESP8266 the other day using 3 10kΩ resistors - R1 = 10K, R2 = 20K. It didn't work. You'd expect it to, given the ratios involved, however the output impedance (6.66kΩ) was too high for the ESP8266 I was using. Replacing them for 1kΩ resistors, so it was 666Ω output impedance, made it work straight away.

You can understand it easier if you think of the ESP8266 as just another resistor (it's actually more complex than that - it's also like a capacitor, so it forms a low pass filter which limits the frequency of, and deforms the shape of, the incoming digital waveform). For example:

simulate this circuit

I have deliberately shown the ESP8266 as a lower resistance that it would really be (you can expect MΩ) so as to illustrate the problem clearer.

Your R2 now has R(esp) in parallel with it. So the nice clean 20kΩ is now actually (20,000 × 100,000) ÷ (20,000 + 100,000) = 16.66kΩ. That gives us a total of 26.66kΩ, and at 5V that means a current of 0.188mA. Through the 10kΩ resistor we end up with (10,000 * 0.000188) 1.875V dropped. Take that from 5V and you can see that the ESP8266 would only be getting 3.125V.

By reducing the resistors in our network the difference that R(esp) makes to R2 reduces. For instance, reducing it to 1kΩ + 2kΩ gives us an R2 total of (2,000 * 100,000) ÷ (2,000 + 100,000) = 1.96kΩ - hardly any different from the 2kΩ we started with, so the voltage difference will be minimal (3.31 as opposed to the ideal 3.33).

The simple formula for calculating the output voltage from an input voltage and pair of resistors, so you don't have to go long-hand through Ohm's Law every time (though it is useful for understanding exactly what is happening) is:

Vout = R2 ÷ (R1 + R2) × Vin

I can never remember it, though, and usually use an online voltage divider calculator.

// According to voltage divider formula,

Vs=(Vo+R1)/(R1+R2), >(whereas R2 is parallel to output).

if Vs=4.5 volts,Vo=3.2V and R1=100 0hms,
than
R2=246 ohms.

For detail study google Voltage Divider circuits.


How can I find the time taken while a function is being called? I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.

There is micros() which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for millis())

unsigned long preFunction = micros();
foo();
unsigned long timeElapsed = micros() - preFunction;

The most accurate method would be to toggle a pin high right before the function, and low after.

If you than connect an oscilloscope or logic analyzer to the pin, you can measure the exact time it took for the function to execute.


Increase Serial Rx buffer I am working with an Arduino Due and I am having some issue with the serial Rx buffers size. I am using a GSM module and some of the replies to the Arduino exceed the number of bytes I can store in the buffer at once.

I have read about ways to increase the buffer size by modifying the Arduino default install files but I cannot take this route as my code may then be compiled on a machine with standard buffer sizes in the default install files and the module would not work correctly.

I am not sure if it is possible but I was hoping that someone might know how to increase the serial buffer size using the source code. If I can do it this way the buffer would always be the size I have specified.

Use timer interrupts to read and store the data from serial. Lets assume you are receiving data at baud rate of 115200 in default configuration (8data bits, 1 stop bit), 115200/9=12800 bytes per second, approximately 80 micro seconds for every byte, create a timer interrupt that is called once every 2 millisecond(Choose best time for your application making sure that receiver buffer does not overflow), In 2milli seconds 25bytes of data will be available in the buffer. So you can read data in batches of 25 each. From the interrupt read and store the available data from the buffer.

I know this is for an input string, but allcocating a buffer size may help.

void setup()
{

  Serial.begin(57600);
  while(!Serial){;}
  inputString.reserve(20); //RESERVE SOME SPACE FOR INPUT STRING

  delay(50);

}


Multiple servos noise I'm building  an application that uses 20 servo motors, and i control then with an Arduino Mega. The servos are having some instability, to the point where they make small random swings. Im powering then from a 7.4V LiPo battery and I drop the voltage to around 6V with 2 series diodes. I've made some research and found 4 things that may help stabilize the servos.

Put a 1000uF eletrolitic capacitor between the battery VCC and GND pins.
Put a 470uF eletrolitic capacitor between each servo VCC and GND pins.
Put a 100nF ceramic capacitor between each servo SIGNAL and GND pins.
Put a 10k pull-up resistor on each servo SIGNAL pin.

My question is, how to make the right decision here. It is better for the project if I take all this designs into account, or I shouldn't be making some combination of this, or one in particular?

You can use the old software serial library from mikal heart. that one does not die interupts. You can do a google search on it.

here is a forum topic about it:
http://forum.arduino.cc/index.php?topic=82596.0


Digispark Serial Port Communication I am using Digispark ATTiny85 and i need to send and receive data through the serial port of my computer.
Does anyone have an idea as to how do i proceed with sending STRINGS and NUMBERS through the serial port ??

I have read that the ATTINY 85 does not have a serial port.
If that is the case is there any alternative ??

have read that the ATTINY 85 does not have a serial port.

It depends on your definition of serial port.

From a hardware perspective it has a usi. That can be configured as a uart. Whether it fits your need or not is up to your application. Read the datasheet to be sure.

Its quite simple, you need a program on your PC that will send data (that you type) to the serial port.

If you are on Windows then you want a 'Terminal Emulator' program, I don't know what its called on Linux but it will be along the same lines.

If you are using the Arduino IDE then there is already something built in, the Serial Monitor will do the job.  You don't even need to be using the IDE for programming you should be able to use the monitor anyway.

Also you can write your own application to do it, but don't do that unless you really have to.


USB Device not recognized (error 43, arduino uno) I know that there's already post about this, but mine is different. Instead of not recognized, it gets recognized, and I can upload codes, but after a while, windows starts to not recognize it. And there is a temporary fix for this for my laptop, I need to restart. And even after restarting, it still becomes not recognized after a while

Edit : forgot to mention, even if it is not recognized, it still sends power to the arduino

The USB microcontroller Atmega16U2/Atmega8U2 on the Ardunio UNO board might be corrupted. Try uploading the USB to Serial HEX file with boot-loader found in C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\firmwares\atmegaxxu2\Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
using Flip OR any other other ardunio (as an ISP programmer). for doing this you have to first enter BOOT-LOADER by shorting the Reset Pin of the USB controller to GND  both pins can be found on ICSP2 of the UNO.
This will surely solve the issue.
But,
if the problem still persists then your USB controller is damaged and have to replace the controller and again upload the USB to serial firmware, the process is same as mentioned above, but you don't need to short reset and GND as you don't have an boot loader installed in the new controller.


Are pins 2 and 3 supposed to be connected? I was playing with my arduino ad realized that pins 2 and 3 are somehow connected. When I press a button to for pin 2, it sets both pin 2 and pin 3 to HIGH even though nothing is connected to pin 3. The code I have is set up for pin 2 and mentions nothing about pin 3 but if i change the hardware to plug it into pin 3, it behaves as pin 2 would. None of the other pins do this. Is it supposed to be like this or is something wrong?

int switchState = 0;

const int led1 = 12;
const int led2 = 8;
const int led3 = 3;
const int button = 2;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  switchState = digitalRead(button);
  if(switchState == HIGH){
    digitalWrite(led3, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led1, HIGH);
    delay(500);
    digitalWrite(led3, LOW);
    digitalWrite(led2, HIGH);
    digitalWrite(led1, LOW);
    delay(500);
  }
  else{
    digitalWrite(led3, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led1, LOW);
  }
}

An input that isn't connected to anything "floats". It will give you unpredictable values. It could be influenced by nearby pins. That is probably what you are seeing. (The metal traces for the 2 pins probably run next to each other on the Arduino's PC board.)

You should either tie an input to ground with a resistor, tie it to +5V with a resistor, or use INPUT_PULLUP mode, which ties it to an internal pull-up resistor. Any of those things will prevent the input from "bouncing around" and giving unpredictable results.

(Note that using a pull-up resistor, either internal or external, has the result of inverting the logic state you get from that input (you get HIGH when the input is not connected to ground, and LOW when it is connected to ground.)

You can use this:

pinMode(button,INPUT_PULLUP);


Can I turn off a device using the 5V and analog pins? Could I connect a device that requires minimum 5V 1A from the 5V Pin to the Ground and somehow turn it off inside  a sketch?

edit: I'm using a Due based boad, the digix http://digistump.com/wiki/digix/tutorials/basics

You would use a transistor. Something like this would work.

In this case the Arduino controls a transistor to drive a brushless motor.

Source: Arduino Cookbook: (https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-8/figure-8-9)

Update:
For the sake of clarity I should point out that the TIP102 is the device to use for the 1A required (not the 2N2222). And as pointed out by others the 5V supply of most Arduino boards would not be sufficient to supply 1A, so an external supply would be advised.

Have you try using a digital potentiometer name AD5220, it let you adjust the resistance
with using your hand. You can find more info about it at www.analog.com. I would upload an
image of the schematic but i just don't know how.


Inappropriate ioctl for device I am using an Arduino Uno and a Mac and trying to upload my code into the board.
I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.
How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.
EDIT
Programmer -> AVRISP mkll
I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.
I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are /dev/cu.Bluetooth-Incoming-Port and /dev/cu.Bluetooth-Modem
And this is the error
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

Plug your Uno into the Mac using a known good USB cable.
Go to the Apple menu -> About This Mac -> More Info -> System Report
Under the USB selection (on the left) please confirm whether or not you see something like this:

You can also open a Terminal window and type:
system_profiler SPUSBDataType

Amongst other things you should see:
USB:

    USB High-Speed Bus:

      Host Controller Location: Built-in USB
      Host Controller Driver: AppleUSBEHCI
      PCI Device ID: 0x3b34
      PCI Revision ID: 0x0006
      PCI Vendor ID: 0x8086
      Bus Number: 0xfd

        Hub:

          Product ID: 0x2514
          Vendor ID: 0x0424  (SMSC)
          Version: 0.03
          Speed: Up to 480 Mb/sec
          Location ID: 0xfd100000 / 2
          Current Available (mA): 500
          Current Required (mA): 2

            Communication Device:

              Product ID: 0x0043
              Vendor ID: 0x2341
              Version: 0.01
              Serial Number: 9314036423335121A0B1
              Speed: Up to 12 Mb/sec
              Manufacturer: Arduino (www.arduino.cc)
              Location ID: 0xfd130000 / 8
              Current Available (mA): 500
              Current Required (mA): 100

Note the "www.arduino.cc" entry.
In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

If you see all that it should work.
If not, please state in what way it differs.

Programmer -> AVRISP mkll

The Tools > Programmer menu selection is only used when you do Tools > Burn Bootloader or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the Tools > Programmer menu.

I had this problem on a Linux distribution. It was just a permissions issue for me.

sudo ./arduino

from the Linux Terminal in the Arduino folder worked fine.


First time set up- permission denied to usb port- ubuntu 14.04 I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:

Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

From the documentation:

  Open Terminal and type:

ls -l /dev/ttyACM*

  you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

  The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

  Now we just need to add our user to the group:

sudo usermod -a -G dialout $USER

  then:

sudo chmod a+rw /dev/ttyACM0

  You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file /etc/udev/rules.d/01-ttyusb.rules containing the following and then reload the udev rules and replug the Arduino device:

SUBSYSTEMS=="usb-serial", TAG+="uaccess"

Or just use the chown command.

sudo chown <username> /dev/ttyACM*

This worked for me


Determining state of charge using current sensor (ACS758) with arduino uno I am working on a university project and I am struggling with estimating the state of charge of our batteries, by using coulomb counting.

Background: We are supposed to build a power supply for a mostly constant load of 100 W (can go up to 140 W) which will be placed outdoors for two years. The plan is to have a small wind turbine plus some solar PV connected to a large battery assembly. The system has to run close to 24/7 with limited downtime.

I have bought some ACS758 50A bidirectional current sensors as well as an Arduino UNO. I am extremely new to Arduino and I would really appreciate some help with the coding. The plan is to have the arduino do the sampling of current and integration, which is then translated to SOC as a percentage and sent to a Raspberry Pi which will send email alerts if the SOC is below a certain level.

I have been looking at sample code describing how to extract the raw data from the ACS sensor: https://www.dfrobot.com/wiki/index.php/50A_Current_Sensor(SKU:SEN0098) as well as sample code that performs integration (Integrating an analog signal using ARDUINO UNO SMD), which is what I would use for coulomb counting.

What I need is most likely a combination between the two, however I do not even know where to start from.

Thanks in advance!

Instead of using a separated component for each thing you can use a proper solution that is itself already a combination of both: the DS2438's integrated current accumulator. This link explain it pretty well, also here is a library to use it with arduino. They are pretty cheap (a few dollars) and will perform very well!

Although, in your place I would consider choosing a different approach. I don't know which kind of battery (Li-ion, LiPo, Lead-acid..) you are using, but in many cases if you monitor the battery voltage, you can have enough information about the battery state. I can't ask you in comment yet beause I'm new here and don't have enough reputation, but if you can describe better the kind of battery you are using and what you intend to monitor which your circuit, I can edit this post to offer you a better solution.

you should probably determine the soc using both current integration and open circuit voltage method.It is possible to cover the weakness of both techniques and provide an accurate monitoring technique.I can provide you the codes if you need,

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int mVperAmp = 100;const float chargingdfficiency= 0.7;
int RawValue= 0, ACSoffset = 2500;
double Voltage = 0, Amps = 0;
double g,q;
int m=0,c=0,d;
void resett(){
digitalWrite(8,LOW);
digitalWrite(7,LOW);}

void setup() {
pinMode(A0, INPUT);pinMode(A1, INPUT);
pinMode(7,OUTPUT);pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
Serial.begin(9600);
delay(10);lcd.begin(20, 4); delay(10);}

void loop() {
resett();
double vini=analogRead(1);vini = vini*5/1023;
vini=5*vini;Serial.print(vini,3);vini=vini/6;
double soc=((666.6667)*vini)-1300;delay(10);
q=soc*.42;
if(soc<30){m=1;resett(); digitalWrite(7,HIGH);} //charging
if(soc>=100){m=0;resett();digitalWrite(8,HIGH); } // DISCHARGING
if(m==0){resett();digitalWrite(8,HIGH);}
delay(10);
while(1){
RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if((Amps<.098)&&(Amps>-.098)){Amps=0;}
if(Amps>9){
resett();
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Overload");digitalWrite(9,HIGH);
while(1);}
if(m==0){
if(Amps<=1.5){g=1.183;}
else if(Amps<=2){g=0.042*Amps+1.12;}
else if(Amps<=4){g=0.028*Amps+1.148;}
else if(Amps<=5){g=0.032*Amps+1.132;}
else if(Amps<=6){g=0.03*Amps+1.142;}
else if(Amps<=7){g=0.325*Amps-0.628;}
else if(Amps<=7.5){g=0.066*Amps+1.185;}
else if(Amps<=8){g=0.028*Amps+1.47;}
else if(Amps<=10){g=1.694;}
soc=(q-Amps*g*0.0002778)*2.38095; q=soc*.42;
if(soc<5){m=1;resett();digitalWrite(7,HIGH);} }
if(m==1){
soc=(q-Amps*chargingdfficiency*0.0002778)*2.38095;
q=soc*.42;
if(soc>=100){m=0;resett();digitalWrite(8,HIGH);}}
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Soc = ");
lcd.setCursor(13,0);
lcd.print(soc,1);
lcd.setCursor(19,0);
lcd.print("%");
lcd.setCursor(1,1);
lcd.print("Amps= ");
lcd.setCursor(13,1);
lcd.print(Amps,1);
if(m==1){lcd.setCursor(1,2);lcd.print("Charging");}
else{lcd.setCursor(1,2);lcd.print("Discharge");}
lcd.setCursor(1,3);lcd.print("Normal");
Serial.println((vini),3);
Serial.print("Amps = ");
Serial.println(Amps,9);
Serial.print(" Soc = ");
Serial.println(soc,9);

for(d=0;((Amps==0)&&(d<=1200));d++){RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if(d==1200){vini=analogRead(1);vini = vini*25/(6*1023);
soc=((666.6667)*vini)-1300;d=0;}}

delay(1000);
}
}


Arduino coding of producing frequency Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.

The code below generates 38 kHz and modulates its duty cycle.

// Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
// Author: Nick Gammon
// Date: 24 September 2012

const byte POTENTIOMETER = A0;
const byte LED = 10;  // Timer 1 "B" output: OC1B

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

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

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  }  // end of setup

void loop()
  {
  // alter Timer 1 duty cycle in accordance with pot reading
  OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

  // do other stuff here
  }

This is meant to be a comment, but I can't put (pseudo) code in a comment.

A 40 kHz square wave? Simple:

for(;;){
   wait ( 1 / 2 * 40.000 );
   make pin high;
   wait ( 1 / 2 * 40.000 );
   make pin low;
}


How to cast float into four bytes? I'm trying to save GPS coordinates to an EEPROM.

In this example I feed it the latitude of 56060066 as the argument float x

void writeFloat(unsigned int addr, float x)
{
  byte seriesOfBytes[3];
  *((float *)seriesOfBytes) = x;
  // Write all four bytes.
  for(int i = 0; i < 4; i++)
  {
    i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
    Serial.println(seriesOfBytes[i],BIN);  // Debug line
  }
}

I'm expecting to receive the following four bytes from the serial print:

00000011
01010111
01101000
10100010

Instead I'm getting these:

00101000
11011010
01010101
01001100

I've tried changing all sorts of parameters, but can't seem to find the problem. Can anyone spot the issue?

You are getting exactly what you said you want. 4 bytes representing the number in float format.

What you are expecting to get, is 4 bytes representing the number in big-endian integer format.

Using Majenkos solution for casting, you need to change the types and reverse the for loop for big-endinaness.
I also used int32_t because the size of the int is 16-bit (2-byte) on the Arduino Uno (and other ATMega based boards) and on the Arduino Due it's 32-bit (4-byte). Its better to define the exact int in this case.

union {
    int32_t ival;
    byte bval[4];
} int32AsBytes;

void writeInt32(unsigned int addr, int32_t x)
{
    int32AsBytes.ival = x;
    for(int i = 3; i >= 0; i--) // reverse for big-endian
    {
        i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
        Serial.println(int32AsBytes.bval[i], BIN);  // Debug line
    }
}

union Float {
    float    m_float;
    uint8_t  m_bytes[sizeof(float)];
};

float        pi,pi1;
uint8_t      bytes[sizeof(float)];
uint8_t      bytes1[sizeof(float)];
Float        myFloat;

#include <Wire.h>
#define disk1 0x50    //Address of 24LC256 eeprom chip
void setup(void)
{
  unsigned int address = 0;
  Serial.begin(9600);
  Wire.begin();
  pi = 300.78;
  Serial.println("*******************************************");
  Serial.println("pi = "+ String(pi));
  Serial.println("***** Conversion by using type casting *****");
  *(float*)(bytes) = pi;
  for(int i=0;i<4;i++) Serial.println( bytes[i]);
  Serial.println("*******************************************");
  for( int i=0;i<4;i++){
      writeEEPROM(disk1, address, bytes[i]);
      address=address+sizeof(bytes[i]);
  }
   address=0;
   for( int i=0;i<4;i++){
      bytes1[i]=(readEEPROM(disk1, address));
      address++;
      Serial.println(bytes1[i]);
   }
   Serial.println("************Conver Byte to Float*************************");
 pi1 = *(float*)(bytes1);
 Serial.println("pi = "+String( pi1));
 Serial.println("********* Conversion by using union *********");
 myFloat.m_float = pi1;   // assign a float to union
 Serial.println("myFloat.m_Float = "+String( myFloat.m_float));
 Serial.println("myFloat.m_Bytes = "+String(myFloat.m_bytes[0])+String(myFloat.m_bytes[1])+String(myFloat.m_bytes[2])+String(myFloat.m_bytes[3]));  // get the bytes
}
void loop(){}
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB  Wire.send(data);
  Wire.write(data);
  Wire.endTransmission();
  delay(5);
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{


Benchmarking String.toInt() vs Checking individual characters gives unexpected result I'm trying to check whether the input string contains all digits or not. I achieved this using 2 different algos. One is to convert the string to integer using String.toInt() and then checking if its value lies between the integer of length of the input string.

e.g. If input string is "123". The corresponding integer must lie between 100-999.

Second, I wrote a function that iterates over each character of the string and checks if its ASCII values lies between 48-57. If not, it returns false.

When I bench marked these two algos, I found that when the string contains only digits, the 2nd algo is about 9 times faster than the 1st one. But when the string contains even a single non-digit character, the 1st algo takes ~1ms, but the 2nd algo always takes ~5ms. Why is this? I've not been able to figure this out.

The code:

unsigned long start;
unsigned long middle;
unsigned long end;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // send an intro:
  Serial.println("String toInt():");
  Serial.println();
}

void loop() {
  // Read serial input:
  if (Serial.available()) {
    String r = Serial.readString();

    start = micros();
    unsigned long rInt = r.toInt();
    int rLen = r.length();

    if ((rInt >= floor(pow(10, rLen))) || (rInt < floor(pow(10, rLen-1)))) {
      Serial.println("Please enter valid integer value!");
    } else {
      Serial.println(rInt+1);
    }

    middle = micros();

    bool isInt = doesContainInteger(r);
    if (isInt) {
      Serial.println(r);
    } else {
      Serial.println("Please enter valid integer value!");
    }

    end = micros();

    Serial.println(middle-start);
    Serial.println(end-middle);
  }
}

bool doesContainInteger(String s)
{
  int sLen = s.length();
  for (int i=0; i<sLen; i++) {
    char sChar = s.charAt(i);
    if (sChar<48 || sChar>57) {
      return false;
    }
  }
  return true;
}

As pointed out by Majenko in his (slightly annoyed) comment, you need to change your timing code to time only the calculations you want benchmark, not the I/O or other irrelevant code. For checking the conversion using toInt(), for example, try:

// time our conversion
unsigned long start = micros();
unsigned long rInt = r.toInt();
bool invalid = rInt == 0;
unsigned long end = micros();

// print the result
if (invalid) {
    Serial.print("in");
}
Serial.print("valid conversion took ");
Serial.print(end - start);
Serial.print(" microseconds.");

Note that your assumption that a three-character input that's a valid integer will be between 100 and 999 is wrong; "003" and "-17" are both three-character inputs that should be correctly converted.

According to the toInt() documentation, 0 is returned on failure to convert, so I check for that in the code above. But since one can't tell the difference between a successful conversion of "0" and unsuccessful conversion of "abc" or some other non-integer, you really should be sure before you call toInt() that you've got a valid integer int the string.

1 ms means easy calculation.

2 ms means more time spent in calculation.

5 ms means far more time in message printing to Serial buffer.

I calculated the error message passes serial line in 20-30 msec, so that is why I think there has to be a little bit faster buffer in between there.


Arduino UNO code ignores variables selectively This is the first code I wrote for my UNO R3 just to feel out the functions and I've already got some jankiness. Throughout this description I am referring to the first two if statements one inside the other one.

I'm trying to increment i every time the signal is activated and then j is used to create a small space of time where the button being pressed will not increment i. My problem is my if statement involving j seem to be totally ignored. I've tried multiple configurations of the if statement structure to no avail.

Here is where things get interesting. So upon setting up the serial connection back to my PC to debug this irritating problem and printing out the actual value of j (to see why it was triggering my if statement prematurely) it magically fixed the problem. It's like until the program literally acknowledges j's value in the print statement it doesn't exist but if it does it works. Any ideas on this?

Note: the serial monitor in both picture depicts consecutive iterations with the signal activated the entire time.

This picture shows the serial monitor after running with the button pressed but the print statement commented out

This picture shows the serial monitor at a space where the button was pressed and held (same time frame as image 1) but in this one it increments i to 3 and then continues incrementing j. How is this happening?

Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.

It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, Serial.print() will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.

I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the void delay(unsigned long milliseconds); function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use delayMicroseconds(unsigned int) for shorter but more precise timing. Or better yet, use the unsigned long millis(); function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.

Yes, and I do appreciate the original answer as it is effective(something just bugs me about losing sensory capability for any amount of time), I just was not really looking for a work around but rather the engineer in me was simply interested in why the code would be responding the way it was. Anyways though I got around to writing my tester and now it's working like a charm. Maybe I was being sloppy before? Obviously I just need to do a bit more testing. I'll post the code just in case anyone is interested in seeing it(also will keep in mind the preference to actual code rather than screen shot in the future) . Thanks for the support!


Concatenate string constants Please take a look at following example (I have Java background):

const char* BT_ADDRESS = "abcd,ef,ghijkl";

void bar(const char* string) {
  ...
}

void foo() {
   bar("AT+BIND=" + BT_ADDRESS);
   bar("AT+LINK=" + BT_ADDRESS);
}

How to achieve this with "Arduino-C++" so BT_ADDRESS only has to be entered at one location?

There is, as you may expect with C, many different ways of doing this.

The simplest is probably to use, instead of a const variable, a preprocessor macro.

In C you can concatenate string literals like this:

print("AT+BIND=" "abcd,ef,ghijkl");

Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.

Now you can, of course, replace one of those with a preprocessor macro:

#define BT_ADDRESS "abcd,ef,ghijkl"
print("AT+BIND=" BT_ADDRESS);
print("AT+LINK=" BT_ADDRESS);

The preprocessing replaces BT_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.

Other options, depending on what print does, is to expand it to take two const char * parameters and deal with them both separately.  For instance, you might have:

void print(const char *command, const char *data) {
    Serial.print(command);
    Serial.println(data);
}

print("AT+BIND=", BT_ADDRESS);

If you don't know how many parameters you may want to pass you could use variadic arguments:

#include <stdarg.h>

void print(int count, ...) {
    va_list args;
    va_start args, count);

    for (int i = 0; i < count; i++) {
        const char *arg = va_arg(args, const char *);
        Serial.print(arg);
    }
    va_end(args);
}

print(2, "AT+BIND=", BT_ADDRESS);

Yet another option is to pre-format the data into a single string using the various string operators.  For example:

int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
char temp[len + 1]; // Be sure to keep space for the terminating NULL.
strcpy(temp, "AT+BIND=");
strcat(BT_ADDRESS);
print(temp);

I could go on all night with different options...  The first one using the preprocessor is probably easiest though.

Get rid of strange print() and use standard stdout, fprintf() and % format tokens.

#include <stdio.h>
#include <Stream.h>

// printf to file support http://arduino.cc/playground/Main/Printf
// we need fundamental FILE definitions and printf declarations
// apparently it eats 1k FLASH by saves to much copy&paste and hopefully even FLASH

// create a output function
// This works because Serial.write, although of
// type virtual, already exists.
static int stream_putchar (char c, FILE *stream) {
    ((Stream*)(stream->udata))->write(c);
    return 0;
}

void SetupFileStream(FILE* file, Print* stream) {
    fdev_setup_stream(file, stream_putchar, NULL, _FDEV_SETUP_WRITE);
    file->udata = stream;
}

#ifdef UDRE0
// non interrupt transmit function
static int uart_putchar (char c, FILE *stream) {
    volatile byte *ucsrna = (byte*)(stream->udata);
    while ( !bitRead( ucsrna[0], UDRE0) ) {;}  // wait for transmit buffer is empty
    ucsrna[&UDR0-&UCSR0A] = c;
    return 0;
}

void SetupUartStream(FILE* file, volatile byte *ucsrna) {
    fdev_setup_stream(file, uart_putchar, NULL, _FDEV_SETUP_WRITE);
    file->udata = (void*) ucsrna;
}
#endif

#define INFO(fmt, args...) \
    fprintf_P(stderr, PROGSTR("INFO: " fmt), ## args);

// create a FILE structure to reference our UART output function in main project file
static FILE myStdOut = {0};
void setup() {
....
    Serial.begin(19200);
    SetupUartStream(&myStdOut, &UCSR0A);   // when debugging in AvrStudio then debugger is saturated by debug messages in user data empty interrupt handler if used buffered stream output
    // The uart is the standard output device STDOUT
    stdout = &myStdOut;
    stderr = stdout;
...
}

....
const char* BT_ADDRESS_RAM = "abcd,ef,ghijkl";
const char* PROGMEM BT_ADDRESS_FLASH = "abcd,ef,ghijkl";

INFO("AT+BIND=%s", BT_ADDRESS_RAM);
INFO("AT+BIND=%S", BT_ADDRESS_FLASH);


serial data gets spoiled I use this small program on my Raspberry Pi to recieve a string sent by my arduino.

import time
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

def check_for_command():
    bytestoread = ser.inWaiting()
    if bytestoread != 0:
        temp = ser.read(bytestoread)
        print(temp)

while 1:
    check_for_command()
    time.sleep(0.1)

the code on the arduino is rather simple:

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

void loop(){
Serial.println(“Hello Pi”);
delay(2000);

the annoying part is. I recieve this:

  b'Hello Pi\r\n'

instead of the clean

  Hello Pi

How do I get rid of those extra bits without using a list for each character.

Thank in advance!

The b prefix in Python 3 just means that it is a bytes literal. It's not part of the output, that's just telling you the type.

The \r\n is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling strip().

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

See also:

What does the 'b' character do in front of a string literal?

As the bytes sent by Raspbian is encoded in UTF-8, use the following line in order to avoid a strip() at a later-on stage:

temp = ser.read(bytestoread).decode('utf-8')


Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64 I have tried to install many versions of IDE, but non of them has started successfully. There is just the logo of the program shows up and then nothing happens.
My laptop: Toshiba Satellite C50-A630
The releases I have installed: 1.6.12 , 1.6.13, 1.0.6

I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.


How to change IIC (I2C) clock rate on MKR1000 The IIC clock defaults to 100kb, need to increase it to ~200kb.

I've tried:

changing the constant TWI_CLOCK and rebuilding Wire.cpp
calling initMasterWIRE(200000) after Wire.begin().

I'm using a scope to verify the change, and thus far can't seen a change in the clock width.

I believe the pull resistors are 10k?  Might need to decrease a bit to.

Looking for a very short example!
TIA.

Looking for a very short example!

easy:

1) find out the mcu used by the board;

2) look up its datasheet;

3) go to the i2c section and find the register(s) that control the i2c clock speed;

4) change it/them.

alternatively, you can take a look at the i2c initialization code and go from there.

the likely solution will be a one liner: use a mask to clear bits and then set those bits depending on your desire i2c speed.


Corrupted output from HC-05 Bluetooth module I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).

I am using 9600 baud rate and trasmitting the following:

void serialTransmit(int data){
  // send to raspberry pi or other device(s).
  Serial.print("Serial Transmit: ");
  Serial.println(data); // this is hard coded as "12" for testing
}

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.

What could be the cause?

First thing to try:

Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.

If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.

To do this wire up the arduino and module like this:

Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.

Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:

/* Serial Loop */

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 9

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ;

void setup() {
  Serial.begin(9600);
  Serial.println("AT");

  mySerial.begin(38400);
  mySerial.println("AT");
}

void loop() {
  while (mySerial.available()) {
    myChar = mySerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    mySerial.print(myChar);
  }
}

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"

AT+ORGL //back to factory settings
AT+ROLE=0 //slave role - transparent serial bridge
AT+UART=9600,0,0 //default baud rate
AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.

Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.

Cheers

Add the module as software serial then add these lines to setup() these line tell us the Bluetooth to turn into data mode:

bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);


counting pulses from encoder on interrupt 0 pin every 50 ms I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see   on my screen zeros and ascii caracters but not the  number of pulses.:this my code .

 volatile int  pulses = 0;

 int flag=0;
 int setbit = 0;
 int encoder_in = 2;
 void count() {

       pulses++;
     }

  void setup()
   {

 Serial.begin(115200);
 pinMode(encoder_in, INPUT);
digitalWrite(2, HIGH); //Enable pullup

// initialize timer2
 noInterrupts();           // disable all interrupts

TCCR2A = 0x00;
 TCCR2B = 0x07;
TCNT2 = 0x64;
//EIMSK = 0x03;     // Enable external interrupt INT0
//EICRA = 0x0f;    // Trigger INT0 on falling edge

 TIMSK2 |= 0x01;  // enable timer compare interrupt
interrupts();             // enable all interrupts
attachInterrupt(0,count,RISING);

 }
  ISR(TIMER2_OVF_vect)
{
TCNT2 = 0x64;            // preload timer
 setbit=setbit+1;
  if(setbit==5)
  {
  flag=1;
 setbit=0;

   }
}

 //ISR(EXT_INT0_vect)
 //{ pulses++; }

 void loop()
{

 if (flag==1)
 {

   Serial.println(pulses);
    pulses=0;

  }
  }

Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.

Remove the Timer and Wire Libs

add this code in void setup()

attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.

and attach your sensor/incoming pulse wire on Pin 2 on arduino.

make a new function like this

void_counter(){
pulses++;
}


Fan regulator control from Arduino I'm trying to control my ~230 V fan from the Arduino.

Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

To control AC power for inductive load (motor) a Triac is used. The concept is called phase cutting. It works for a resistive load (heater) too.

This module is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.

Robotdyn has a library for the module.

EDIT:

I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. (video on youtube)

The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.

I wrote an adrduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.

#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

EDIT 2 version with triac activated by 'pwm' pin

const byte TRIAC_PIN = 9;
const byte ZC_EI_PIN = 2;

unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
int prescaler = 8;
byte prescalerBits = _BV(CS11); // /8

void zeroCrossing() {
  TCNT1 = 0; // reset the timer counter
}

void setup() {
  Serial.begin(115200);
  Serial.println("START");

  attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

  pinMode(TRIAC_PIN, OUTPUT);
  uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
  ICR1 = topPeriod;
  OCR1A = topPeriod + 1;
  TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
  TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
}

void loop() {
  if (Serial.available()) {
    unsigned long microseconds = Serial.parseInt();
    Serial.find("\n");
    uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
    OCR1A = period;
  }
}

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals

EDIT 3:

The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.

It depends on the motor.
To quote MarkT from this post:

The simple advice is you can't.  Standard induction motors in domestic appliances cannot
safely be speed-controlled (some can be a little, but its not easy to find out by how much).
Get a DC fan

To quote dc42, from this post:

What sort of motors do the fans have? If they use induction motors,
then you won't be able to control the speed much using phase angle
switching - the speed is tied to the supply frequency. If they are
series-wound motors with brushes, then phase angle switching should
work.
The results you reported when you tried to use the velleman kit
suggests to me that the fans may have induction motors.

For more information, read:

How to control AC 220V fan speed with arduino's PWM output..?? and;
Changes in Dimming Circuitry! and;
Learn about zero-crossing. This might help How stuff works - dimmer switch.
AC Fan Speed Control with Arduino


Can I use notepad++ for writing sketches? Before I install the Arduino IDE, I was just wondering whether I could just use notepad++ to write the files and move them into correct location. I assume notepad++ doesn't support Arduino code, but I suspect there will be a mod for it, even though sketches are a low-end version of C++, which is supported.

You can easily use notepad++ or any text editor to edit arduino code files (.pde or .ino). I use the sublime text editor for all my arduino coding.

As you noted, the arduino syntax is c++, so setting the syntax highlighting mode to c++ is all that you need to do; no mod should be necessary.

Arduino includes a "Use external editor" option in the preferences menu that will make it reload the file every time you compile or upload. It also disables editing in the editor window. In this mode, just save your file in any editor, change to the arduino window, and hit upload.

Since 1.5, arduino has had command line support. most editors allow making the "build" button execute arbitrary commands in the current directory. by setting build to run "arduino --verify" or "arduino --upload" you can code in any editor you want even without having an arduino window open.

You can use anyto text editor and save it as a .ino file. You still have to open the file with arduino software and compile/upload to the arduino board


Convert String to IPAddress How can i convert a String to IPAddress on arduino / esp ?

etc. "192.168.1.2"  -> IPAddress(192, 168, 1, 2)

Tried this

void setup() {

  Serial.begin(115200);

  IPAddress apip;

  const char *apipch;
  apipch = "192.168.4.1";

Serial.println(apip.fromString(apipch));

}

void loop() {
  // put your main code here, to run repeatedly:
}

But i just get an output "1"

The IPAddress class has a member function bool fromString(const char *address).

You could do this:
String myip="192.168.1.2"
IPAddress local_IP;
bool x= local_IP.fromString(myip);


Digital pin output voltage fall down when driving a relay I'm trying to trigger 8 different 5V relays using arduino atmega 2560. the relays (70Ohm coil) are powered by an external 5V source, and im trying to trigger them through a driving stage which contains for each relay a npn transistor (2N3904) and 1kOhms resistor directly connected to digital pin of the arduino.
the relays in my application are supposed to be drived 2 by 2 not all of them at once.
My problem is that i dont succeed triggering the relay with digital pins of my arduino, once i connect it to the resistor the voltage of the digital pins falls down from 5V to 0.4V or less. The transistor needs only 7mA to be triggered, the output current of the atmega2560 pins is 20mA max.
i tried with an external 5V source, it triggers correctly showing 10mA maximum of current through the driving stage.
Thank you in advance for your help.
Best regards.

If the coil is 70 ohms and it's driven by 5V, it should draw about 5/70 = 71 mA.  That's pushing the 2n3904 a bit hard, and doesn't even account for inductive effects. (It's a small-signal transistor.)  Do you have an NPN power transistor to try, just as a test?  If its current gain (beta) is too low, use a Darlington configuration by combining it with your 2n3904.  (2n3904 base from digital out resistor, emitter drives power NPN base directly, both collectors are connected together to the bottom of the coil, and the power NPN emitter is the effective emitter of the just-created "super transistor" with high beta and power handling.)  Be sure to use an anti-kickback rectifier (1n4001)across the relay coil.


Can I program for Arduino without having a real board? I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?

There are a whole slew of Arduino simulators out there, many free, and some paid products as well.

The CodeBlocks Arduino development environment includes a free Arduino simulator, still under development but functional.
Simuino simulates the Arduino Uno and Mega pins - not a pretty-looking realistic simulator, but it works.
The Python based Arduino Simulator is another option, that plays well with the official IDE
Virtronics Simulator for Arduino looks promising, but I don't see why I would pay $14.99 for it, when I could buy one or more actual Arduino clones for that price

Many other Arduino simulators are out there if you search, and new ones are being announced, even crowdfunded, all the time.

Yes you can, and fairly easily. There is a wonderful online simulation (completely free) called TinkerCAD. It has an excellent breadboard simulation, with parts like transistors, LEDs, ICs, and Arduino. You can program the Arduino and run it all in a live simulation that includes interactive inputs (pushbuttons, DIP switches, etc.).

[Edit: The following text refers to functionality that has been moved to Circuits.io, namely Eagle PCB]

That's not all. It also includes in a separate tab schematics for your circuit, and another tab for PCB design of your breadboard circuit! Or, you can just make your schematics from scratch and make your PCB from there.

You can have your circuit designs made and you can buy them. You can do all of this in circuits.io, and you aren't risking messing up your actual Arduino. It also has warning indicators in the simulation (for example, if you didn't use enough resistance on an LED, or an IC).


WiFi connection in loop function What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:

setup(){
    wifi.mode(WIFI_AP_STA);
    setup softAP
    server.on("/",handleroot)
    server.begin()
}
loop(){
    server.handleClient()
    if(credential_submited){
        Wifi.begin(credentials);
        flag_connection_started =true;
        credential_submited = false;
        flag_for_internet_server=true;
    }
    if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
        server.on("/",handleroot)
        server.begin()
        flag_for_internet_server=false;
    }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.

You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().

BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.

This is not a big deal...

You can do it vary easily, the most simple way is that you can use EEPROM to achieve this..

Simply pass the SSID and PASSWORD of new network to ESP8266 and save it in EEPROM and also create a new variable in eeprom that store the status that new network credentials is entered or not and check it in loop and then fetch new network credentials from the EEPROM and try to connect to it...

You can also check and connect to your desired network from the loop...

Or alternatively you can use the library that can help you in doing that [WiFiManager]: https://github.com/tzapu/WiFiManager


Arduino Countdown without using delay() I am working on a project which requires countdown from 30sec to 0sec. I can't use delay() function because I am taking input from keyboard during countdown. millis() function wont help because my board will be active for more than 50 days. I require something like counter which I can reset after or before completion of 30sec.

Background

The function millis () returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).

See: http://arduino.cc/en/Reference/Millis

Example:

unsigned long startTime = millis ();

Since there are 232 bits in an unsigned long it can count from 0 to 4294967295.

Computing this in terms of days we have:

2^32 / 1000 / 60 / 60 / 24 = 49.710 days

So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

Is this bad?

No. Is it bad your clock overflows (goes back to zero) at midnight? No it isn't.

Let's clear up some misconceptions:

The processor does not reset when the timer overflows.
The timer does not stop.
Nothing "bad" happens.

All that happens, on a timer overflow, is that it goes back to zero and starts counting up again. Just like your clock does.

How do I time an event?

There are two ways of timing something (eg. a minute from now). You can add or subtract. Because of the way that unsigned arithmetic works, subtracting is the correct way.

Example of adding - not recommended!

I want to detect a minute in the future...

unsigned long startTime = millis ();
unsigned long whenToStop = startTime + 60000;

...

if (millis () >= whenToStop)
  {
  // do something
  }

This will work most of the time, but not when the timer overflows. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

2^32 - 50000 = 4294917296 (0xFFFF3CB0)

Now we add 60000, and get:

2^32 - 50000 + 60000 = 10000 (0x2710)

Our "whenToStop" variable has overflowed and is now quite small. And thus it is immediately less than the current time, and our check for when a minute is up fails, it appears to be up immediately.

Example of subtracting - recommended

I want to detect a minute in the future...

unsigned long startTime = millis ();
unsigned long interval = 60000;

...

if (millis () - startTime >= interval)
  {
  // do something
  }

This will work all the time. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

2^32 - 50000 = 4294917296 (0xFFFF3CB0)

In 50 seconds the timer wraps around and goes to zero. Subtracting now gives us:

// millis () - startTime   = elapsed interval
    0        - 4294917296  = 50000 (0xC350)

The subtraction "wrapped around" and gave us a small number. If you use a scientific calculator and try the above you may get a result of 0xFF0000C350. The initial 0xFF is the "extended sign bit", in effect, however as the field is unsigned, and only four bytes long, the sign bits are dropped, giving a small positive number, not a large negative one.

Demo using the Mac Calculator app:

In 60 seconds the timer goes to 10000. Subtracting now gives us:

// millis () - startTime   = elapsed interval
    10000    - 4294917296  = 60000 (0xEA60)

So the elapsed interval (the difference) is now 60000, which is what we wanted.

Directly after we set up startTime and millis we will see a sequence like this:

millis ()   -  startTime    =  difference
                             (modulo 2^32)
4294917296     4294917296               0  <-- we start timing here
4294917297     4294917296               1
4294917298     4294917296               2
...
4294967295     4294917296           49999  <-- largest unsigned long value
         0     4294917296           50000  <-- wraps here back to zero
         1     4294917296           50001  <-- keeps counting up
...
      9999     4294917296           59999
     10000     4294917296           60000  <-- time's up!

Recommended method

Use unsigned long (not just long) for "time" variables.
Record the start time of some event (eg. a debounce, when you start feeding the fish, etc.)
Subtract the start time from the time now, giving a difference.
See if the difference exceeds the desired interval.

eg.

startedFeedingFish = millis ();

...

if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
  {
  // stop feeding the fish
  }

Can't I just reset millis?

You can, but you don't need to. Plus it may well throw out any library you are using that does not expect millis to be reset. Plus you have to decide exactly when to do it. It would need to be a time when you aren't using millis. For example if you happened to be feeding the fish in the above example, and your code reset millis, then the fish will get an awful lot of food!

What about micros?

The function micros() returns the number of microseconds since reset. This also wraps around, however since there are 1000 microseconds to a millisecond it will wrap around faster.

 2^32 / 1000 / 1000 / 60  = 71.58 minutes

http://arduino.cc/en/Reference/Micros

However you can use exactly the same technique to keep track of time to the microsecond interval. Be aware that you can't time more than 71.58 minutes this way though.

Also be aware that the resolution of micros() is four microseconds (because of the timer prescaler) so you won't ever be able to time a one or two microsecond interval.

Limitations

If you are using millis() you cannot time more than 49.71 days, and if you are using micros() you cannot time more than 71.58 minutes, without extra code to detect the wrap-around. For long intervals I suggest a real-time clock, since that would be more reliable during power failures, or when you replace batteries, etc.

Reference

This answer taken from my page http://www.gammon.com.au/millis

You could handle the wrapping - for example

long long start = millis();
// do some stuff
long long end = millis();

// If the counter wrapped during that time, artificially fix 'end'
if (end < start) end += 4294967295;

long duration = (long)(end - start);

(Of course this is basically impossible to test, but I think it's correct.)


Arduino on battery getting unstable if temperature falls i am building an outdoor sensor with a combination of a custom Arduino board and a battery (+solar charging). I experience strange behavior when the temperature falls below a certain value (i can reproduce it by putting it in the freezer), regardless which type of battery i am using. The custom Arduino runs without power-regulation, straight from the 3.7volts the battery can provide.
How can i prevent this to happen? I guess a little heating would be not really a solution as i am trying to consume as less energy as possible.
Would a (step up) regulator possibly help? Any other ideas?

---Update---
Thanks to your comments here i figured out, that the AVR 328p should not be operated below a voltage of 3.7v if run at 16Mhz. As i am running with a 3.7v LiPo Battery that could easily explain my problem i guess. My first try to decrease the processor speed to 8Mhz with a Prescaler worked, but the GSM Fona does not seem to like it. So i would like to try something in between like 10Mhz or 12Mhz. As the prescaler does not support this, my question is: can i just use another crystal or would i have to modify something in the code/bootloader as well?

To answer your modified question:

Running the ATmega328p at 16Mhz with 3.7v is out of spec - see this EESE answer for reference or the ATmega datasheet - so the obvious solution would be to lower its speed to 8Mhz.

But since you also mentioned that there is an additional GSM breakout board involved (Adafruit Fona), which expects UART (in auto-baud mode) Rx/Tx connection, it might not be that trivial. Further exploration of the Fona library's source code reveals that it has several hard-coded delays (see Adafruit_FONA.cpp::begin, for example), but its core seems to be implemented inside the Adafruit_FONA::readline method, which uses an underlying Stream, which in turns comes from a Software/Hardware serial object, as shown in the FONAtest.ino example that comes with the library.

From my experience, Software/Hardware serial should work fine on 8Mhz, except maybe when using high baud rates, which is solvable.
The hard-coded delays doesn't look like they should cause actual damage except for delay, but you could cut them in half just to see if you can make the library work.

Additional aspect that you should consider is the comment from Adafruit's Fona product page, regarding pin Vio:

  This is the pin that you MUST drive with an external voltage from
  3V-5V to set the logic level converter

So, despite that from the datasheet, the Fona seems to have a voltage regulator, you might still want to consider adding a decoupling capacitor between Vcc and Gnd of your battery, to  mitigate transient current draws from any component in your circuit.

It's most likely that the cold weather is messing with your batteries. I don't know what battery types you've tried, but this site says that Lithium batteries (Not Li Ion, but standard single use, expensive, lithiums) hold up well in very cold and very hot environments. For rechargeable batteries the site recommends NiMH batteries. Of course, we all know that lead acid batteries hold up well in cold (Or else our cars wouldn't start!), so those are also a viable option. Lead acids can be purchased in somewhat small forms, but they may still be too big for your purposes.

For the other part of your question, yes a regulator will help. It's rarely acceptable to run directly off a battery without a regulator. Since your application is low power you'll want to use an efficient switching regulator (Search for modules, not individual chips). Remember that a battery's output changes based on its charge level, temperature, current draw, and other things I'm likely forgetting. Using a regulator mitigates these effects as regulators are less affected by temperature and current draw than the battery that supplies it (Hopefully).

So to summarize: Use Lithium batteries, or NiMH if you need to recharge, or Lead Acid if you need a ton of capacity and size isn't a limit. Then get a switching regulator module. Best of luck with your project!