text:
Using Arduino Micro With 12V Buzzer
I have an interesting situation.  I wonder if anyone can help?
I have:

4x Arduino Micros loaded with the basic Blink sketch
5x 12 volt buzzers
A desk full of completely fresh Duracell AA and 9v batteries

If I connect (using VIN and GND) any of the Arduino Micros to either a 9v battery, or a 12v network of 8 AA batteries, then they run the blink sketch, and the appropriate LED flashes on the Arduino as expected.
If I connect any of the buzzers to either a 9v battery, or a 12v network of 8 AA batteries, then they buzz as expected.
If I connect both a buzzer and an Arduino in parallel to either a 9v battery, or a 12v network of 8 AA batteries, then the Arduino works fine, but the buzzer makes barely an inaudible whimper.
If I connect only a buzzer to the Arduino and battery, it works fine.  If whilst the buzzer is buzzing I connect the Arduino, then on every ON or OFF of the blink sketch LED, the buzzer gets quieter and quieter until it can barely be heard.
These buzzers are rated to work at 25mA, so it really astounds me that they can't be run off a battery together with an Arduino.
Any help would be appreciated!
Thanks
Dave

Connect a capacitor across the buzzer - say 100 uF or higher at 16Vor higher. If this affects the above outcomes you have electromagnetic interference.

@Russel McMahon Thanks for the suggestion that it might be electromagnetic interference. Turns out you are right!  I added a capacitor and it started working. If you put a proper answer in, I'll mark it as accepted.

Thanks for the offer. I suggest that you accept jwpat7's answer as he has incorporated my brief suggestion as part of his answer and overall his answer is informative and useful for other users with power related issues.

Attach your voltmeter across the battery, and measure the available voltage when different things are attached; or attach it in series, and measure current draws.  You probably will find that a 9V battery's voltage is under 8 volts when a mix of multiple Arduinos and buzzers is attached.  That voltage may be too low to activate the buzzer.
A powerstream.com web page called 9V Alkaline tests shows how rapidly a 9V battery's voltage drops when heavy currents (more than a few dozen milliamps) are drawn from it, and a batteriesinaflash.com web page includes the following diagram that shows battery voltage quickly falling below 8.5 V in its first minutes of life when 27 mA is drawn from it.
For some models of Arduino, eg the Uno R3, various posts on the web list currents from 25 mA up to 45 mA, depending on LED and sleep settings.  Currents for the Duemilanove from 10 mA up are reported.  The Arduino Micros in your tests probably use a little more current than Pro Mini boards (which have no USB), and although it's unlikely they will use as much or more current than the buzzers, they still may drag the voltage down to a level where the buzzers won't work.
If your system needs to be battery powered, consider using separate batteries for different devices, to avoid problems like you saw.  Alternatively, use heavier-duty batteries, eg good-sized lithium-polymer units.  Also review posts about decreasing Arduino power usage via sleep, disconnecting the power LED, and using large capacitors to buffer power surges.
Edit: Given that voltage measurements show enough voltage being available, the suggested use of capacitors or inductors to isolate circuits may be a good idea.
When adding a capacitor, locate it physically close to the power-using board or component.  For electrolytic  capacitors, attach the capacitor's + terminal to the high side, eg to the +5, +9, or +12 side, and attach its - terminal to ground.
When adding ferrite beads, wrap the supply wire through the bead several times, if there's room.  The picture below illustrates the idea.
An electrolytic capacitor across a circuit acts as a voltage reservoir.  It also gives high-frequency signals an easy path to ground, reducing interference.  A ferrite bead or other inductor impedes high frequency signals, again reducing interference.

Thanks for the answer - in reading through it and the provided links, I've learned a lot about batteries that I didn't know!  I got my volt meter out, and measured the voltage. Turns out not to be voltage related, but electromagnetic interference from the arduino.  +1 for all the interesting stuff I've learned about batteries. Thank you.

+1 - nicely detailed and presented answer. You probably would benefit from and be useful in the Stack Exchange EE group as well. I see you are involved in a wide range of groups already (quite a lot of overlap with me fwiw). Are you really as venerable as your profile page says ? ! :-)

@RussellMcMahon, not quite :) but sometimes feel like it :(.  I learned Fortran and assembly language programming using an IBM 1620 in 1965.


text:
How to fix an IR remote signal
I am using the following code to send an IR signal:
#include <IRremote.h>
 IRsend irsend;

void setup() {

}

void loop() {

    unsigned int IRsignal[] = {86,88,86,88,174,86,88,88,86,88,86,86,88,86,88,86,88,174,86,88,174,86,88,2336,90,86,88,86,174,88,86,88,86,88,86,88,86,88,86,88,86,174,88,86,174,88,86,0};

    irsend.sendRaw(IRsignal, 48, 40);

    delay(3000);

}

However, when I attach an IR receiver to another Arduino and take a look at the signal that is produced by the code above, I see this:
Received:
OFF     ON
332 usec, 460 usec
1040 usec, 280 usec
2680 usec, 260 usec
820 usec, 80 usec
400 usec, 260 usec
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    46, 104,
    28, 268,
    26, 82,
    8, 40,
    26, 0};

Received:

OFF     ON
39228 usec, 280 usec
1160 usec, 340 usec
2460 usec, 480 usec
440 usec, 500 usec
340 usec, 260 usec
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    28, 116,
    34, 246,
    48, 44,
    50, 34,
    26, 0};

These numbers are not even close to the ones that are going in.  There are far few pulses recorded, the duration is very inconsistent (the original code is almost entirely made up of 880-860um pulses) and even close to the original values.  I must have made a serious mistake here.  What happened?
UPDATE ==========================
I multiplied all of the values in the array by 10 and attempted to play/read the values using another Adruino with an IR sensor.  I started to see better results.  each pulse time was close to 88, 86, or 174 but they are still off by up to 10%.  The related IR device is still unresponsive.  Is there any other way to improve this?
Received:

OFF     ON
29828 usec, 860 usec
900 usec, 820 usec
880 usec, 1700 usec
880 usec, 860 usec
880 usec, 840 usec
940 usec, 760 usec
840 usec, 880 usec
860 usec, 880 usec
860 usec, 860 usec
1740 usec, 840 usec
880 usec, 1700 usec
880 usec, 840 usec
6920 usec, 880 usec
860 usec, 860 usec
880 usec, 1680 usec
880 usec, 860 usec
900 usec, 820 usec
900 usec, 820 usec
880 usec, 840 usec
860 usec, 840 usec
960 usec, 740 usec
1760 usec, 880 usec
920 usec, 1620 usec
900 usec, 10680 usec
13580 usec, 8580 usec
8820 usec, 8680 usec
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    86, 90,
    82, 88,
    170, 88,
    86, 88,
    84, 94,
    76, 84,
    88, 86,
    88, 86,
    86, 174,
    84, 88,
    170, 88,
    84, 692,
    88, 86,
    86, 88,
    168, 88,
    86, 90,
    82, 90,
    82, 88,
    84, 86,
    84, 96,
    74, 176,
    88, 92,
    162, 90,
    1068, 1358,
    858, 882,
    868, 0};

Possibly I have an out of date copy of IRremote.cpp, but in that file on my system IRsignal[] values are in microseconds, not tens of  microseconds.   Ie, sendRaw sends buf[i] values as-is to mark() and space(), which call delayMicroseconds() after enabling or disabling PWM.

Are you sure it's a 40kHz signal, and not 38kHz?

@Gerben - no idea what the kHz is, how can I tell?  Either way, the signal should still come across to the other Arduino as the same data set right?

@jwpat7 - so it might work if I put an extra zero on each value (x10?)

Most remotes and receivers use 38kHz. So if you send 40kHz to a 38kHz receiver, the signal might not be read entirely correct.

@Hoytman, I checked a current copy of IRremote.cpp and it uses microseconds in sendRaw buffer values.  Re 38 vs 40kHz, your rcvr part number (what is it?) dictates which you should use.  Eg, adafruit's TSOP38238 is tuned for 38kHz.  If you send 40kHz to a 38kHz receiver it could garble things up like you saw.  It's easy to try the other rates, of course

source: Stack Exchange

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

sort: votes


text:
How to prevent file overwriting in processing?
i am working on this arduino project using processing. There are some sensor values which should be logged, but unfortunately my processing code rewrites the file after each cycle so that i get the last sensor value only. How do i prevent this from happening? I am using the ordinary method by the way. PrintWriter command followed by createWriter

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"),
    true /* append = true */));
The true is the append mode flag.
Also check if you're using
pw.append(p.toString());
        pw.append("sdf");
https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending

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


text:
RTC and SD work separately but not together
I am running a small project. I want to use an Arduino Mega 2560 v3, a PIR sensor, a micro SD card module, an RTC 1307 module, some LEDs, buttons and a buzzer. To enable and disable motion detection and when detection is found the time is saved to the SD card.
I wired everything together, coded and started to test. During tests, Arduino on bootup was restarting over and over. First, I was thinking that the problem is in the breadboard and connection. I checked it a few times and I didn't notice anything wrong. So I checked the code over and over. Still nothing.
So I started to test modules. And I found a problem. When I don't use in the sketch either the RTC or the SD card (physically they are still connected, because I am lazy) everything works fine. Arduino doesn't restart. I didn't use the SD module to write data, instead I used the serial port to show data. Everything works fine: I can see at what time is motion detected and Arduino prints it on the terminal.
In the second scenario, I didn’t use the RTC, only the SD module. This time again everything works fine. On the SD card I could read how many times motion was detected. This is weird because when I mix all together it doesn't work.
Here is my code:
// *********************************************
// INCLUDE
// *********************************************
#include <Wire.h>
#include <SD.h>
#include <SPI.h>
#include "RTClib.h"
// *********************************************
// DEFINE
// *********************************************
#define GREENLED 39
#define BTNON 11
#define REDLED 41
#define BTNOFF 9
#define BUZZ 3
#define PIR_PIN 10
//SD (na mega)
#define SD_CLK_SD 52
#define SD_MI 50
#define SD_MO 51
#define SD_CS 4

//RTC
#define RTC_SDA 20
#define RTC_SCL 21
#define RTC_DS 2

// *********************************************
// VARIABLES
// *********************************************
RTC_DS1307 rtc;
File myFile;
char godz[8];
char data[5];

int btnON;
int btnOFF;
int pirD;
bool stan_alarmu;

void wlAlarmu() {
  digitalWrite(REDLED,LOW);
  digitalWrite(GREENLED, HIGH);
  stan_alarmu=true;
  gettime();
  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("### Wlaczenie alarmu ### ");
    myFile.print(" ");
    myFile.print(godz);
    myFile.print(data);
    myFile.println("");
    myFile.close();
  }
}

void wylAlarmu(){
  digitalWrite(GREENLED, LOW);
  digitalWrite(REDLED,HIGH);
  stan_alarmu=false;
  gettime();
  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("### Wylaczenie alarmu ### ");
    myFile.print(" ");
    myFile.print(godz);
    myFile.print(data);
    myFile.println("");
    myFile.close();
  }
}

void alarm(){
  digitalWrite(GREENLED,LOW);
  digitalWrite(REDLED,HIGH);
  digitalWrite(BUZZ,HIGH);
  delay(500);
  digitalWrite(BUZZ,LOW);

  gettime();
  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("Alarm: ");
    myFile.print(" ");
    myFile.print(godz);
    myFile.print(data);
    myFile.println("");
    myFile.close();
  }
  delay(5000);
  digitalWrite(REDLED,LOW);
  digitalWrite(GREENLED,HIGH);
}

void blad() {
  while(1){
    digitalWrite(REDLED,HIGH);
    delay(500);
    digitalWrite(REDLED,LOW);
    delay(500);
  }
}

void gettime() {
  DateTime now = rtc.now();
  sprintf(godz,"%02d:%02d:%02d ",now.hour(),now.minute(),now.second());
  sprintf(data,"%d.%d",now.day(),now.month());
}

// *********************************************
// SETUP
// *********************************************
void setup() {
  //RTC
  Wire.begin();
  // Shield I2C pins connect to alt I2C bus on Arduino Due
  rtc.begin();
  if (!rtc.isrunning()) {
    blad();
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  pinMode(BTNON,INPUT);
  pinMode(GREENLED, OUTPUT);
  pinMode(BTNOFF,INPUT);
  pinMode(REDLED, OUTPUT);
  pinMode(PIR_PIN,INPUT);
  pinMode(BUZZ,OUTPUT);

  //test seq
  digitalWrite(GREENLED,HIGH);
  digitalWrite(REDLED,HIGH);
  digitalWrite(BUZZ,HIGH);
  delay(100);
  digitalWrite(BUZZ,LOW);
  digitalWrite(GREENLED,LOW);
  digitalWrite(REDLED,LOW);
  delay(500);
  pinMode(SD_CS, OUTPUT);
  if (!SD.begin(SD_CS)) {
    blad();
  }
  digitalWrite(GREENLED,HIGH);
  delay(1000);
  digitalWrite(GREENLED,LOW);
  gettime();
  Serial.begin(9600);

  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("####START SYSTEMU: ");
    myFile.print(godz);
    myFile.print(data);
    myFile.print(" ####");
    myFile.println("");
    myFile.close();
  }
  wylAlarmu();
}

void loop() {
  btnON = digitalRead(BTNON);
  btnOFF = digitalRead(BTNOFF);
  pirD = digitalRead(PIR_PIN);

  if(btnON == HIGH) {
    wlAlarmu();
    delay(2000);
  }
  if(btnOFF == HIGH) {
    wylAlarmu();
    delay(2000);
  }

  if(pirD==HIGH && stan_alarmu==true) {
    alarm();
  }
  delay(1000);
}

Please give an exact specification of the shields you are using. Perhaps there are some clues hidden.

My RTC module looks almost like this: http://www.arduino-projekte.de/index.php?n=45 datasheet is on bottom of page under  DS1307 Datenblatt PDF (ENG). SD microSD reader is made by Catalex  http://catalex.taobao.com/ but I couldn't find documentation on their site :)

It looks, as if you use the RTC-library from adafruit. Same for the SD library? My suggestion is, that the configurations of I²C-Bus for both modules are conflicting. Most probably concerning bitrate. You should have a look inside both libraries and check, which parameters they apply to the Wire-Library.

I coundn't find anything in libs. I found also that someone use rtc an sd library same as me and it works. http://www.michellechandra.com/physical-computing/activity-tracker-log-date-and-time-to-microsd-using-real-time-clock-and-arduino/

I tried to use 3 diffrent libs. Still nothing thats amazing.

Hmm, if you own a scope, you should check the stability of all voltages in your system. repeated rebooting hints to brownouts.

I don't have scope. Only multimeter. Voltage is between 4,86 - 4,90.

Have you tried using the hardware pin for SPI SS (it's 53, I assumed you're using an Arduino Mega by looking at your preprocessor directives). Sometimes weird things happen when you reassign this pin.

After long time i build new circut and new sketch. I used only rtc and sd, this time everything was working fine. There is no problem now. Something used to be wrong in past.

A common issue when using strings (character vectors) is that the vector size is not updated when the format is update. Check the size required for this data. Does it fit for the sprintf() statements?
char godz[8];
char data[5];

void gettime()
{
  DateTime now = rtc.now();
  sprintf(godz,"%02d:%02d:%02d ",now.hour(),now.minute(),now.second());
  sprintf(data,"%d.%d",now.day(),now.month());
}

What is the worst case size required?
Cheers!

I ran into the same problem lately. I have a work-around but don't have a clear explanation of this problem. As you initialize the different modules in your setup(), make sure to perform the SD card initialization first, then followed by the RTC's. Doing this completely sorted me out. However, I am yet to explain these results.
Though it is late, just in case anyone else runs into the same problem.

You should start to debug your code stepwise. I.e. insert debug output commands (print via serial) at some crucial points to find the block of code which resets your device. Then narrow it down, until you know the very command which breaks your setup.
Maybe, there will be more than one point in your software, which is responsible for the failure. Nonetheless you will be wiser after that.
Then you will probably have to dive into the guts of the libraries.
If you have identified some command or procedure call responsible for the reboot, it may be still a hardware issue. Writing SD-cards consumes considerable amount of power. If you supply your device solely via USB, I recommend buying an additional PSU and see, if the behaviour changes.
The next thing is to check the reset-signal on all of your shields and daughter-boards for unwanted connections like solder-bridges or single wire threads snipped of elswhere. Another funny thing are stacking connectors not matching the mainboard and shorting something on it.

Are you using breakout boards as pictured in your links? Or Arduino shields?
Many Uno shields are almost, but not quite, compatible with Mega boards. It is possible there there is one or more pins that are not compatible between them.
If you're using breakout boards, double check all of the connections to the Mega. Could something be dragging down your power supply? Or actually grounding the reset pin? It would probably be one of the programmable I/O pins since the failure only depended on whether you used the SD library and seems not affected by the mere presence of the board.

I use very similar breakout boards as in pictures. I don't use shields. I check connections many times.

When using Catalex Micro SD Card module, there is a problem with the MISO output. It is not disabled on the SPI bus because of a hardware failure. To correct the problem pin 13 on the IC must be liftet from ground connection and put together with pin 8, that have the CS signal. Now the Card Works fine with other SPI modules. Take care when soldering - it is very small pins.
Best regards OZ7LM Leif

It is too late to answer but I had the same issue and spent a week to solve it. This will not be the exact solution. It worked and I think this is the easiest way to solve it.
First let me tell you my components:

WeMos D1 R2 (ESP8266)
MicroSD Card Adapter
DS3231 RTC (I tried with DS1302 but it did not work).

How I solved is, on setup part, first I initialized the RTC DS3231 then I set the built in Arduino clock to DS3231 RTC values. After that I initialized SD card. In this case you are not able to get RTC data in loop but you have it in built in Arduino clock and SD card works. If your Arduino lose electricity, then it will get the RTC data in setup again.
This solution solves it in someway.
Also there is no tutorial for how to connect these cards to WeMos D1 R2 so I want to share my connections.
SD Card    WeMos D1 R2
-------    -----------
SC      -> D14/SDA/D5
SCK     -> D13/SCK
MOSI    -> D11/MOSI
MISO    -> D12/MISO
VCC     -> 5V
GND     -> GND

RTC DS3231   WeMos
----------   -----
SCL        -> SCL/D15
SDA        -> SDA/D14
VCC        -> 3.3V
GND        -> GND

Also my code:
#include <Wire.h>
#include "RTClib.h"
#include <SD.h> //Load SD library
#include <SPI.h>
#include <time.h>
#include <TimeLib.h>
File file;
int chipSelect = 5;
RTC_DS3231 rtc;
bool not1024prev;
unsigned long timepast;
unsigned long timecurr;
int cnt = 0;
int rpm;

char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

void setup()
{

#ifndef ESP8266
    while (!Serial)
        ; // for Leonardo/Micro/Zero
#endif

    Serial.begin(9600);

    delay(3000); // wait for console opening

    if (!rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1)
            ;
    }

    if (rtc.lostPower()) {
        Serial.println("RTC lost power, lets set the time!");
        // following line sets the RTC to the date & time this sketch was compiled
        //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        //rtc.adjust(DateTime(2018, 3, 11, 16, 29, 30));
    }
    DateTime now = rtc.now();
    setTime(now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());

    if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
    }
}

void loop()
{
    String curtime = String(year()) + "." + String(month()) + "." + String(day()) + "-" + String(hour()) + ":" + String(minute()) + ":" + String(second());

    Serial.println(curtime);
}


text:
Can I make the Arduino ignore serial print
I like having serial communication for debugging and testing purposes but after a while it takes away too much speed from the sketch.
Is it possible to have the Arduino ignore serial.print and serial.println throughout my code, without turning it into a comment or placing every serial printing inside for example "if(debug == true)" statements?
Thanks in advance.

If you insist on top performance, the best thing would be to use a macro for that:
#define Sprintln(a) (Serial.println(a))

Then instead of
Serial.println(F("Hello world!"));

write
Sprintln(F("Hello world!"));

etc. To deactivate the Serial printing, define the macro empty:
#define Sprintln(a)

This will have the preprocessor remove all debugging code defined with Sprintln from your code.
(Of course, there's a huge number of variations on this theme.)

You can also wrap all exiting prints in #ifdef ENABLE_PRINT and #endif and then define or comment out #define ENABLE_PRINT at the top of ur file

You can even set a debug level and define macro's for debugL1();, debugL2(); etc, so you can choose how many details you want to "log". The macro's will though make it unable to change runtime, but at the advantage of not having runtime overhead.

You could, for example, use the preprocessor to change all Serial in your code.
#ifndef ENABLE_PRINT
// disable Serial output
#define Serial SomeOtherwiseUnusedName
static class {
public:
    void begin(...) {}
    void print(...) {}
    void println(...) {}
} Serial;
#endif

Yet another solution is to implement a dummy Serial device. That would be a class that as HardwareSerial inherits from Stream and implements the necessary virtual member functions with dummy functions.
class NullSerial : public Stream {
public:
  virtual size_t write(uint8_t) { return (1); }
  virtual int available() { return (0); }
  virtual int read() { return (0); }
  virtual int peek() { return (0); }
  virtual void flush() {}
  ...
  void begin(unsigned long, uint8_t) {}
  void end() {}
  ...
};

NullSerial Serial;

As Serial is not defined as a weak symbol the application would need to use a Steam variable for output. And bind this to the HardwareSerial or the NullSerial.
#if defined(DEBUG)
Stream& trace = Serial;
#else
NullSerial noSerial;
Stream& trace = noSerial;
#else

#endif
...
trace.print(42);

This is not complete as all the HardwareSerial member functions (that the sketch uses) are needed but gives the general idea how to use OOP to solve the problem.
Cheers!

This worked well for me (great for debugging in PlatformIO!). Instead of declaring NullSerial Serial (which conflicts with the HardwareSerial declaration by the same name), I gave it a unique name (NullSerial nullSerial) and then overrode the original everywhere with #define Serial nullSerial. Lovely thing about this method is that my existing code does not change.


text:
What is the fastest and easiest way to transmit arduino's sensor data to a PC wirelessly
I have a specific problem :

I'm working on a testing platform. It has to be absolutely isolated, so I cannot wire it back to my PC. I again reiterate it. There is no way to wire it to my PC. IT HAS TO BE ABSOLUTELY ISOLATED
It has about 10 different sensors on it and I need to read sensor's data simultaneously at 100Hz.  It is currently working fine with 16Hz, but I need to improve it further, so I think maybe in future sampling rates higher than 100 is beneficial. 7 Hz is the lowest possible value that doesn't botch the whole things up.
I have a laptop on the platform which reads the sensor data via RS232, then it processes them in a fraction of a second and produce a control signal and send it to the actuators. It has to happen at real-time. Control algorithm is not heavy, it is several PIDs.
It has 6 actuators with the fastest possible reaction time of 0.005 second.
The main sensor currently is Microstrain 3DM-GX1. It is a very good sensors.
I want to add a GY-80 sensor in parallel to 3DM-GX1. I want to test various filtering algorithms on the GY-80's output and compare them to 3DM-GX1.
Platform has 6 degrees of freedom so I think laser transmission is not practical.
Distance between the computer and the platform is at most 3 meters.

For some reasons I am not able to use the laptop anymore. I want to read the sensor's data with an Arduino, preferably Arduino Mega 2560. My problem is that I don't want to load the control algorithm to the Arduino.
IMHO the perfect solution is going to be a Wireless link between the Sensors via Arduino to my PC. This way my PC logs data and also the Control Algorithm can promptly calculate the feedback signal and send it to Arduino which will send them to the actuators. This immensely makes things easier for me.
I think I need a RS232 shield for the 3DM-GX1 & Arduino, + some wireless solution for sending data from both sensors to my computer. Then I need to send back the control signal back to the actuators wirelessly.
Now what is the fast and easy way to transmit the data between PC and Arduino in real-time?
Thank you in advance!

How much bandwidth do you really need? 100Hz isn't that fast, even 4800 baud could do it easily if each sensor has a 4 byte response. In any case "the fastest" is vague and hard to answer.

He said he needs 100hz with 10 sensors. If each value is 16bit 4800 baud WILL NOT cover him. Also "fastest" means sample rate but it also means latency. For lowest latency use the highest baud rate / fastest data bus you can

I updated the whole question. I'd be thankful if you could help me find a good solution.

Ok well then some sort of rf would be better. I would look at bluetooth serial. I can find some links. What sort do latency are you looking to meet ?

I think the type that can support 24 sensors at 16bit 100Hz + 6 actuators at 100Hz is enough. Plus the time my computer needs to send back the signal. I need it to be easy to implement with Arduino.

What kind of latency is acceptable ?

I am new to this, Please forgive my ignorance. I am not sure about the latency! I know that at 16 Hz the 19200 baud-rate was enough. But now we are looking at 100 Hz. I don't know how to figure out the latency required.

The fastest way would be to use a laser link!! Yeah lasers. You could go with wifi or some other custom wireless but lasers will guarantee the highest energy density and therefor best bandwidth.  This guy claims near 10 MB/s with his setup:
http://www.instructables.com/id/Laser-Transceiver/

I think the transceivers have to be pointed at each other all the times. Because my platform has six degrees of freedom. It is rotating around different axes. Please correct me if I am wrong.


text:
IR Receiver interrupt and arduino sleep mode
I need to put my arduino into the sleep mode in order to consume less power. My arduino receives IR data and do some work with it, but I need to make it sleep until there is no data. If the data has appeared it should wake up and do something with data and go back to sleep mode.
Is there any way to do this.
I would be grateful for any help.

Is this the IRLib library from http://playground.arduino.cc/Main/IRLib ?

Actually I didn't know it that one. I use an adaptation of Ken Shirriff library made by Chris Young. Is very generic I found it in a lot of examples.

More info can be found at this stack exchange http://arduino.stackexchange.com/questions/6753/choosing-right-sleep-state/6755#6755

This is what I have managed to achieve ...

Library
IRLib - GitHub

Version 1.51 March 2015
  Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/
This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

Code
Modified code (from the demo IRrecord example):
/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.5  June 2014
 * Copyright 2014 by Chris Young http://cyborg5.com
 * Based on original example sketch for IRremote library
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://www.righto.com/
 */

/*
 * IRrecord: records IR signals
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Record a value by pointing your remote at the device
 */

#include <IRLib.h>
#include <avr/sleep.h>
#include <avr/power.h>

const byte LED_PIN = 8;
const byte RECV_PIN = 11;
const unsigned long BAUD_RATE = 115200;
const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
IRsend My_Sender;
/*
 * Because this version of the library separated the receiver from the decoder,
 * technically you would not need to "store" the code outside the decoder object
 * for this overly simple example. All of the details would remain in the object.
 * However we are going to go ahead and store them just to show you how.
 */
// Storage for the recorded code
IRTYPES codeType;          // The type of code
unsigned long codeValue;   // The data bits if type is not raw
int codeBits;              // The length of the code in bits

// These values are only stored if it's an unknown type and we are going to use
// raw codes to resend the information.
unsigned int rawCodes[RAWBUF]; // The durations if raw
int rawCount;                   //The number of interval samples

bool GotOne, GotNew;

// added by Nick Gammon
EMPTY_INTERRUPT (PCINT0_vect);

void setup()
{
  GotOne=false; GotNew=false;
  codeType=UNKNOWN;
  codeValue=0;
  Serial.begin(BAUD_RATE);
  while(!Serial);//delay for Leonardo
  Serial.println(F("Send a code from your remote and we will record it."));
  Serial.println(F("Type any character and press enter. We will send the recorded code."));
  My_Receiver.enableIRIn(); // Start the receiver
}

// Stores the code for later playback
void storeCode(void) {

  // added by Nick Gammon
  pinMode (LED_PIN, OUTPUT);
  digitalWrite (LED_PIN, HIGH);

  GotNew=true;
  codeType = My_Decoder.decode_type;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    // To store raw codes:
    // Drop first value (gap)
    // As of v1.3 of IRLib global values are already in microseconds rather than ticks
    // They have also been adjusted for overreporting/underreporting of marks and spaces
    rawCount = My_Decoder.rawlen-1;
    for (int i = 1; i <=rawCount; i++) {
      rawCodes[i - 1] = My_Decoder.rawbuf[i];
    };
    My_Decoder.DumpResults();
    codeType=UNKNOWN;
  }
  else {
    Serial.print(F("Received "));
    Serial.print(Pnames(codeType));
    if (My_Decoder.value == REPEAT) {
      // Don't record a NEC repeat value as that's useless.
      Serial.println(F("repeat; ignoring."));
     }
     else {
       codeValue = My_Decoder.value;
       codeBits = My_Decoder.bits;
     }
     Serial.print(F(" Value:0x"));
     Serial.println(My_Decoder.value, HEX);
  }

  // added by Nick Gammon
  pinMode (LED_PIN, INPUT);
  digitalWrite (LED_PIN, LOW);

}

void loop() {

  // added by Nick Gammon
  static unsigned long lastActivity;  // when we last woke
  // sleep if no activity for a while
  if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
    {
    Serial.flush ();  // wait for Serial to finish outputting
    Serial.end ();    // shut down Serial
    noInterrupts ();  // timed sequence coming up

    // pin change interrupt for D11
    PCMSK0 |= bit (PCINT3);  // want pin 11
    PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

    set_sleep_mode (SLEEP_MODE_STANDBY);
    sleep_enable();

    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu ();
    sleep_disable();
    power_all_enable ();   // enable modules again
    ADCSRA = old_ADCSRA;   // re-enable ADC conversion
    Serial.begin(BAUD_RATE);
    lastActivity = millis ();
    }  // end of no activity for a couple of seconds

 if (My_Receiver.GetResults(&My_Decoder)) {
    My_Decoder.decode();
    GotOne=true;
    storeCode();
    delay(500);
    My_Receiver.resume();
  }
}

Explanation
Main changes are in loop (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.
Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls power_all_disable to disable various internal modules.
Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.
I found that I had to use SLEEP_MODE_STANDBY rather than SLEEP_MODE_PWR_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.
For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

Power consumption
I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).
Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.
Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

My tests on my page about power indicate that SLEEP_MODE_STANDBY uses 480 µA more power than SLEEP_MODE_PWR_DOWN, so this sounds about right.
630 + 480 = 1110 µA

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

References

Power saving
Interrupts
Adafruit IR library
IR library source

oh my god, this is an answer! I need time to understand and test it ! Thanks a lot Nick !

Great page. About the low power mode: the low frequency clock is useful in scenarios where one has to do relatively frequent operations, like debouncing: the debouncing can happen at low frequency and then the clock gets cranked up only if the wakeup was real. So that a noisy environment doesn't kill the battery.

LOL !!! Nick, you are the author of that page, is really great !!! I didn't notice it.

@IgorStoppa - indeed, however in this particular case the IR receiver uses the bulk of the power. Still, it may well be possible to get a lower powered one.

Sorry @NickGammon for maybe ask a very noob question. (I'm pretty new into this) I understand that you check for 2000ms if there is no activity, but I didn't get why you sleep and the next command is power all enabled. Are you suggesting that the only way is turn off 2 secs, turn on, watch if something happenning every 2 secs? There is no way to turn off until signal?

Oh I read it from your web. I think I can do the same with the example of
Sketch J

I didn't get why you sleep and the next command is power all enabled - the sleep call is the one where it stops, maybe for hours.

Connect the IR receiver to INT0 or INT1 (pins 2 or 3 respectively). You can use the attachInterrupt function. E.g. attachInterrupt(0, yourfunctionname, LOW). The function being called can be empty, if you only use it to wake up the MCU.
To wake from sleep you need to use the LOW trigger mode. Once waken up you probably want to remove the interrupt handler (detachInterrupt), or it will swamp the cpu with interrupts.
(Note that most IR receiver will still use something like 3mA.)

It has been confirmed by Atmel that any level change will wake the processor from sleep. See Interrupts for a quote of their email.

@NickGammon I never got it to work on anything other than LOW trigger. The datasheet says in table 10.1, note 3; For INT1 and INT0, only level interrupt. The example on the page you link to also only uses LOW triggers.

Most of my examples were written before someone on the Arduino forum raised the issue. Until then I had believed the datasheet. I raised a ticket at Atmel and got this response: "Our design team has confirmed that “Note-3 mentioned under Table 10-1” is a datasheet bug. So you can use any type of interrupt (Rising edge/ Falling edge / Low level / Any logical change) to wake up from sleep mode. Sorry for the inconvenience caused."

For example see this thread External RTC to wake Arduino up on interrupt. The poster there said, after I recommended changing from LOW to FALLING: "Wow. Nick you were right. Tried it with FALLING and it works like a charm. Thanks!" As you noted @Gerben, using LOW has its own problems.

I guess I need to give it another try on my next project. Thanks


text:
Convert uint8_t array to uint32_t array
I have this array of bytes, that I need to convert to an array of unsigned ints. Also the function (btea) that needs it, seems to need a pointer.
I'm currently using reinterpret_cast which seems to work, but I'd like to know how/why. I'm pretty new to C. It also seems kind of dirty. I could use a for loop, and bitshift everything into a separate int array variable, but that seems wasteful.
uint8_t data[] = {1,2,3,4,5,6,7,8};//can be any multiple of 4 bytes

btea(reinterpret_cast<uint32_t*>(data), sizeof(data)/4, encryption_key);

radio.write(data, sizeof(data));

...

void btea(uint32_t *v, int n)
{
  ...
}

Any pointers (pun intended) are much appreciated.

@mpflaga's answer gives a great alternative, but I thought I'd explain why your code works (grossly simplified).
All the reinterpret cast does is let the compiler know how wide of a variable it assumes is in each element of the array.  When you access data[1], it uses one byte at an offset of one byte from data[0].  When you cast to uint32_t and access data[1], it uses 4 bytes at an offset of 4 bytes.
If your memory looks like this (each square is one byte)...

...before the cast you are interpreting it as the top layout, after the cast you interpret it as the bottom layout.  It's still exactly the same in memory, you're just telling the compiler to use it differently. The reason that using a union is better is that it is safer.  Your code would read garbage after the end of the array if its length wasn't divisible by 4.
One other quick note, be careful with the sizeof() operator on arrays - it always gives the length in bytes regardless of the element size.

about the sizeof() I usually employ "#define LENGTH_OF_ARRAY(x) ((sizeof(x)/sizeof(x[0])))". Noting it is the size of the whole array divided by the size of an individual element.

Great explanation. But what about the * in reinterpret_cast<uint32_t*>. Why doesn't it reinterpret the array-data as a pointer?

@Gerben - That's because they both refer to the same memory location.  data[0] and *data are both the equivalent, but use different semantics. In fact, data[1] and *data + 1 are also equivalent.  The main difference to keep in mind is that when you declare and array like uint8_t data[7]; the compiler reserves 8 contiguous bytes of RAM and a memory address, but when if you declare uint8_t* data, it only gets you an address. There's a decent tutorial here that gives more justice to the concept than I can in a comment.

I prefer to use unions. example:
union fourbyte {
  uint32_t dword;
  uint16_t word[2];
  uint8_t  byte[4];
};

union fourbyte val;

val.dword = 0x03020100;

Serial.println(val.byte[0], HEX);
Serial.println(val.byte[1], HEX);
Serial.println(val.byte[2], HEX);
Serial.println(val.byte[3], HEX);

Serial.println(val.word[0], HEX);
Serial.println(val.word[1], HEX);

Serial.println(val.dword, HEX);

My byte array is of length 8. So I could do something like union eightbyte {uint32_t dword[2];  uint16_t word[4];  uint8_t  byte[8];};. Variable length arrays seem be impossible using this method.


text:
Day-night powered Arduino
What should I do to have an Arduino Pro Mini 5V (clone) powered by a 5V solar panel during the day and by battery during night which will be charged during the day by the solar panels.

is there any guide out there?
is it possible with the 5V version of Arduino Pro Mini or will I have to buy the 3.3V
I prefer to make the circuits by myself rather than buying them (for example: the charging circuit.)

This would be better answered on Stack Exchange Electrical Engineering.
Also see this question and answers. This is not quite the same and the answers there are OK but less than complete or correct, but it adds to the resource available.
You need a battery charging controller, a PV (solar) panel capable of producing somewhat more than maximum battery voltage and enough energy to operate your circuit and a battery with enough voltage to operate the device and enough capacity to store the energy.
Current drain will vary with total circuit. You can measure this will a milliammeter. I'll assume that 50 mA continuous will be enough. Less or much less may suffice. I have a pro mini clone operating at 20 mA on 5V at present and with due care you may be able to operate one with less or much less current depending on application and what your circuit needs are.
Looking at solar current needs at present, the average solar current needed is about Icircuit x 24/SSH mA where SSH = average sunshine hours per day. eg if you had 4 hours of sunshine per day but want to run the circuit for 24 hours a day the sun must provide (24 hours per day)/(4 hours of sun) = 6 x as much current as the circuit needs on average. So if your circuit needs 50 mA continuous the PV panel must provide 6 x 50 mA = 300 mA for 4 hours per day. You will see below that this is not a trivial amount.
Sunshine hours per day may be found for sites worldwide using the excellent www.gaisma.com The average sunshine hours per day for Iráklion may be found at that link and other locations in Greece can be found here but will probably be similar.
For Iráklion the SSH may be found in the 1st line of the 4th chart.
Average hours/day of equivalent full sunshine = kWh/m^2/day = a peak of 8.53 hours in June and a low of 2.08 hours in December.
Wow!
I think that is about as sunny a place in Summer as anywhere on earth not in the polar regions.  In Winter it gets about the same SSH as in my city. You can calculate PV sizing for peak summer - but if you want year round operation you should use the worst case winter month and add a bit for bad days.
For Iraklion us say 2 SSH per day so the panels needs to provide 24/2 = 12 x winter average load. So per 10 mA of load yo need 120 mA of panel and if the mean load is 50 mA you need 12 x 50 = 300 mA panel output.
Battery voltage needs to be > 5V at all times.
An easy cheap available starting solution is to use a 6B lead acid battery.
These are easyish to charge and provide a relatively stable operating voltage.
Vmax_charge is about 7V so an 8V or 9V PV panel is "about right". 9V is a common voltage for hobby applications. An alternative is to use a 12V panel. this is probably more suitable as they are widely available and cost per energy out is often lower. This wastes MOST of the panel output but still MAY be the cheapest option in many cases. (A 12V x 600 mA panel is rated at about 18V x 0.6A ~= 10 Watts. Actual Arduino load = 50 mA x 5V x 12:1 = 3 Watts)
At 50 mA load you need 24/2 x 50 mA = 600 mA PV output in full sun.
PV panel sizing is not as may be expected. It is easiest to get a panel that makes at least enough voltage and enough current. This is because panel RATED voltages are usually higher than the voltages they are used at. eg 12V system PV panels are usually rated at 18V max power voltage- so an 18W panel provide 18V at 1 A BUT if attached directly to a 12V battery the input to the battery = 12V x 1A = 12 Watts. There are ways around this but at first, just concentrate on panel mA.
So, you "need" a 600 mA panel for a 50 mA load.
Or a 60 mA panel for a 5 mA load.
Or a 6 mA panel for a 0.5 mA load.
Obviously, reducing load current is going to help panel sizing.
So knowing what your application really needs is essential.
Batery is easier.
If you use 6V lead acid then for one day you need.
Hours x load = mAh.
Here load=24 hours. mA = 50 in this example.
mAh = 24 x 50 mA =  1200 mAh = 1.2 Ah. This is the capacity of about the smallest LA battery commonly available. In practice you want to discharge your battery by only a small % of its actual capacity so use a 2.4 Ah or 3.5 Ah or larger. 7Ah is not vastly dearer and will last far longer and will have several days of reserve capacity for bad weather.
Charging can now be discussed - but I'll stop here and see what is said about the above. We can add charging and other detail if it seems useful to do so.

An easy battery to use is 2 x LiIon or LiPo cells in series.

Your coverage of solar power usage and calculations was excellent, are you going to continue the discussion with charging?

@KellyS.French 3years - 2 days old answer I see :-). It would perhaps be useful if you ask a specific question, referring to this Q&A. Also - reading what is said on SE EE on LiIon and other charging by me and others would quite possibly cover the subject well enough. | SE EE Battery charging and My 298! battery charging SE EE answer

@KellyS.French ...  and subsets: My Li bat charging answers ...
and LiIon charging and Nimh charging


text:
Arduino is not recognized by any computer
I have an Arduino Uno R3 and when I plug it into any computer, the computer doesn't recognize the Arduino. I checked up and the LEDs are working fine and when I open the device manager it doesn't show any Unkown Device.
What it could be? Could the ATMega be dead? I tried on two Windows 7 and one Linux machines, none recognized the Arduino.

Is it an official Arduino board or a clone?

I burned out the USB-serial converter once with a shorted USB cable and it did the exact same thing.  I was still able to program it using another Arduino and everything worked fine except for the USB connection (although it was a real PITA to load sketches to).  Might be something to test if you have another ISP.

@PeterR.Bloomfield It's an official Arduino board.

@Comintern That could be possible, but would that affect the LEDs? Because when I plug the USB the Arduino receives power, but has I said nothing happens.

The reason that it is not connecting can be anything from wrong driver installation to the dead Atmega 16u2 chip. But I must exclude the former option as you said you'd tried on different OS and different computers. So double check the driver installation. And if does not work try to find out whether Atmega16u2 is fried or not. One solution might be to reflash the original firmware through an external ICSP programmer. If don't have any programmer but another arduino uno you might try out the gamon's tutorial on flashing firmware on the little USB to serial interface chip.
Anyway if your arduino is new and official you can get the right support online on arduino.cc. but if it is a clone you may try to contact the reseller whom you bought from.

The problem is that when I plug the arduino it doesn't apear that something new is connected, and when I check the Device Manager there's nothing even the Unkown Device, I'll try to download the drivers again and plug it again to see what happens.

As I said above, you now have only one solution. If it is a new board get help from arduino.cc if it is an older one try to bring back to life the mini USB to serial chip on the board.

The board has almost 2 years so I guess the solution is to bring back to life the mini USB to serial chip, any ideas on how to do that?

I had the same problem. When I connected the board to PC the ON Green LED turned on and the arduino run the last code was uploaded but the board wasn't recognized. Changing the cable fixed this problem for me.

If your arduino runs the last uploaded sketch, the problem is with the ATMega16U2 chip in your Arduino. Try to update the firmware with this tutorial https://www.arduino.cc/en/Hacking/DFUProgramming8U2
If you can't update the 16U2 firmware don't throw away, you can program the Arduino with a ISP programmer like this https://www.pololu.com/product/1300


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

Polling loop on a timer?

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

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

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

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

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

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


text:
Set the timeout - Ethernet Shield library
Does anyone know if you can set the time for the timeout Ethernet Shield library? Let me explain:
I created a very simple function (below) that attempts to connect to an address if it is not accessible returns 0 if it is available returns 1. Problem is that when the site is not available, the microcontroller is waiting for an answer for a long time, wanted to reduce it.
uint8_t ping(const char* address)
{
    EthernetClient http;

    if(http.connect(address, 80)) {
        http.stop();
        return 1;
    }
    else
        return 0;
}

In the stream class there is a setTimeout(ms) function. e.g.
String str;
Serial.setTimeout(5000) ;
str = Serial.readStringUntil('\r');

Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.
int httpGetHeaders() {
  String request, response;
  int result = 0;
  long startOfHttpResponseTime;

  client.setTimeout(1000) ;
  response = "";
  inHeaders = true;
  startOfHttpResponseTime = millis();
  while((client.connected()) && inHeaders && ((long)(millis() - startOfHttpResponseTime) < HTTP_RESPONSE_TIMEOUT)) {
    String header = client.readStringUntil('\n');
    header.trim(); // trim off white spaces including CR and LF at end.
    Serial.print(F("head["));
    Serial.print(header.length());
    Serial.print(F("]:\""));
    Serial.print(header);
    Serial.println(F("\""));
    if (!header.length()) { // first blank line indicates end of headers
      inHeaders = false;
      Serial.println(F("No longer in Headers"));
    }
    else {
      if (header.startsWith("HTTP")) {
        Serial.println(F("HTTP Found"));
        int firstspace = header.indexOf(" ");
        result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
        Serial.print(F("result = "));
        Serial.println(result);
      }
    }
  }

  Serial.print(F("Result code = "));
  Serial.println(result);
  return result;
}

You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.


text:
How to interrupt a code after delay
I have a functionality on my mega 2560 to connect with other devices. Sometimes, devices can't answer. I don't want to wait for a longwhile. So, how can I interrupt the chunk of program after the specific amount of time?
My code for receiving messages is:
while (!(UCSR1A & (1<<RXC1)));

so, millis can't solve my problem because I haven't ability to check for conditional loops like that
if(currentMillis - previousMillis > interval) {

It's often better to mention why you would want to do such a thing. I'm guessing that you want to receive your messages every once in a while. It might be better to handle serial events in interrupts (for fastest receiving). Or to handle it in a timer interrupt (better timing).

The question might be better titled "How to break out of a loop with a timeout", since interrupts and delay have completely different meanings that you are using here.

OMG, I was stupid. I can just place millis in this while condition.

'if(currentMillis - previousMillis > interval) break;' may work as well. -- If the logic could become more complicated, a separate break statement for the conditions might make the code clearer.


text:
Arduino Uno, Ethernet shield, MySQL
I'm trying to connect my Arduino Uno with MySQL.
This is my code:
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xC8, 0x0A, 0xA9, 0xAF, 0x83, 0x58 };
IPAddress server_addr(192,168,0,102);

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference
char user[] = "root";
char password[] = "fifa2005";
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello from Arduino!', NULL)";

void setup() {
Ethernet.begin(mac_addr);
Serial.begin(115200);
delay(1000);
Serial.println("Connecting...");
if (my_conn.mysql_connect(server_addr, 3306, user, password))
delay(500);
else
Serial.println("Connection failed.");
}

void loop() {
}

I have the following database:
mysql> CREATE DATABASE test_arduino;
Query OK, 1 row affected (0.00 sec)
mysql> USE test_arduino;
Database changed
mysql> CREATE TABLE hello (source char(20), event_date timestamp);
Query OK, 0 rows affected (0.01 sec)

This is the output message:
Connecting... Connection failed.

I am not sure this is the right IP address: 192,168,0,102. I tried with the localhost IP address - 127.0.0.1, but nothing happened.

What kind of system is MySQL running on? E.g. Windows, Linux, MacOS?

Is 192.168.0.102 the address of the computer you're trying to connect to, or is that the address of the ethernet shield? I'm confused as to why you would try connecting to localhost...

My operating system is windows 7. 192.168.0.102  is ip adress of my laptop. At first I thought that I need to use IP address of the server but then I saw that actually need the IP address of my laptop

You need to use the IP address of the server running MySQL.

I use Apache to create a Mysql server and corresponding IP is 127.0.0.1. and it doesn't work with it. Ethernet shield and laptop are connected to the router. I think the problem is mac address or ip address which i used. I take the mac address from: cmd -> ipconfig -> Ipv4 address - 192,168,0,102. I take the mac address from : cmd -> getmac -> Physical Address.

I understand where is the problem. I have used the wrong port.I have to use port 3306 and add the following code:
'delay(500);
my_conn.cmd_query(INSERT_SQL);
Serial.println("Query Success!"); '
in the if statement

First you have to grant permission to the user!
Type the query in MySQL like:
GRANT ALL ON test_arduino.* TO root@'192.168.0.102' IDENTIFIED BY 'fifa2005';

Can't comment, so I put here. In your Arduino you shall use unique MAC address, that can't be same as in your laptop or any other node in network segment. And it can't be just any number because some bits have different meanings, so to be safe, use MAC from Ethernet shield samples (BTW in production units, MAC addresses have to be purchased, but unfortunately Ethernet shield comes without it).
127.0.0.1 is a "virtual" localhost address (alternative address used to access the services within same host), in your case you shall use MySQL server (your laptop?) host address, so
> server_addr(192,168,0,102);

is right.

authors: Γιάννης Τεβεκίδης


text:
Control Brushless ESC From Arduino
I am trying to build a quadcopter using an arduino. I Bought 4 30A ESC's from Ebay the link is http://www.ebay.co.uk/itm/4pcs-Brushless-speed-controller-ESC-MultiCopter-KK-Quad-rotor-X-copter-30A-S-/310950293677?pt=LH_DefaultDomain_3&hash=item486614f0ad and a A2212 2200KV motor, im also using a sparkfun arduino uno. I have connected the white (data) servo wire of the ESC to pin 9 of my arduino and the black (ground) servo wire of the ESC to gnd of the arduino. When i connect the battery to the esc i get the 3 beeps because of my 3 cell battery regardless of what code is on the arduino even if the arduino is not present. the code that is on the arduino is.
#include <Servo.h>

Servo motor;

void setup()
{
  Serial.begin(9600);
  motor.attach(0);
}
void loop()
{
  motor.write(100);
}

I'm not sure what is wrong. Can someone please help me.

If you were using an RC radio, what would the arming and/or calibrating process be for those ESC's?

im not sure about the arming process, im also not using a rc radio its being controlled by bluetooth from a phone, So if i need to arm it will need to be by code.

ESC's like these are designed for use with RC radios and have an arming process (like full throttle two seconds, neutral 2 seconds or something) that someone with a radio needs to do so that the motors don't spin up while they are turning everything on. You will need to find the right one for those ESCs and replicate it with your code.

Gone quiet here.. If the ESC gives you 3 beeps then it's alive. Your code does nothing beyond start up & output a steady 100 p.w.m. - it needs to emulate the RC arming process next, likely a high-to-low transition, you should then get a nice warble to tell you it's about to belt off somewhere... try outputting 1024, delay 300, then 0?

You may have the Servo library very helpful. Check out this answer

I had a similar problem. I solved it by using an oscilloscope to measure the arming sequence of an out-of-the-box RC remote controller and receiver.
The arming sequence through the controller-receiver was like this:

Connect ESC to battery (arduino is connected to signal and ground prior to this)
Wait for 3 beeps
Set the throttle to the lowest possible
Wait for another beep

I then adjusted my arduino code to output the same(similar) sequence.
Here is the code:
#include <Servo.h>
#define POT A0

Servo m1;

void setup() {
  m1.attach(6);
  Serial.begin(9600);
  delay(50);
  Serial.println("Serial ready:");
  arm(m1);
}

void loop() {
  int potValue = analogRead(POT);
  int s = map(potValue,60,930,1200,1700); //Map the pot values to motor values

  m1.write(s);
  Serial.println(s);
}

void arm(Servo m){
  Serial.print("Arming.");
  m.write(0);
  delay(100);
  m.write(1224); //A value at which the motor starts turning
  delay(2000);
  m.write(1024); //A value at which the motor stands still
  delay(3000);
  Serial.println(" Armed!");
}

You can also see a video of the whole thing in action here: A2212/13T brushless motor on a pivoting arm
EDIT: Further testing shows, that it suffices to output a low non zero value to arm this ESC. Simply doing Servo.write(1024); until you hear the confirmation beep seems to work.


text:
Wrong characters received with Bluetooth Mate Gold using Software Serial
I have a Bluetooth device from Sparkfun which I would like to use with the Arduino Mega. If I connect the module via the hardware serial pin everything works fine but when I use other pins like 12 and 13 with SoftwareSerial, the communication doesn't work as expected.
THE CODE
#include <SoftwareSerial.h>

int bluetoothTx = 12;
int bluetoothRx = 13;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available())
  {
    char toSend = (char)bluetooth.read();
    Serial.print(" Receiving: ");
    Serial.println(toSend);
  }

  //Read from usb serial to bluetooth
  if(Serial.available())
  {
    char modeS = Serial.read();
    Serial.print(" Writing Blu: ");
    Serial.println(modeS);
    bluetooth.print(modeS);
  }
}

I'm using an Android App (BlueTerm) to test the communication.
Here is what I get when sending a letter from Android to Arduino.
 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Writing Blu: d
 Writing Blu: d
 Writing Blu: d

I'm not able to receive anything from the Arduino.
I've tried decreasing the baudrate but nothing changed. Do you have any advice?
Update
I have tried without the following lines but nothing changed... It seems that the module can be used only with the hardware serial pins 0 and 1... It's a shame
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);

What character are you sending from the Android App that is being received as 'ÿ'?  Are you just echoing back the 'd'?

Every letter I send from the Android app is received as 'ÿ'. Then from Arduino serial monitor I press three times d and send.

Just making sure, because 'ÿ' is the same as 'd' if you use 2 bytes per character and reverse the bit ordering. Seemed really strange if that was the case.

Is it possible that since Software Serial doesn't work well with baudrates over 38600 then the lines used to change the rate: bluetooth.print("$$$");   delay(100);   bluetooth.println("U,9600,N");   bluetooth.begin(9600); are not received by the module? If that was the case then I would have sent bytes @ 9600 to the module which has a default listening rate of 115200.

That was my next thought.  115200 is really pushing it for Software Serial.


text:
Can I charge a 4.2 V battery with a 5 V adapter?
Can I charge a 4.2 V battery with a 5 V adapter without damaging the battery?

What type of battery is it, this will help you get a better answer.

Welcome to Arduino SE. I'm going to close this as off-topic because the question doesn't seem to involve Arduino at all. If it's supposed to be about Arduino then feel free to edit the question and we can re-open it.

This question would be a better match to the Stack Exchange Electrical Engineering group.
A 4.2V battery is very likely a LiIon or LiPo battery. I'll call it LiPO below as it's easier to type.
Most cellphones and many small electronic device use a single LiPo battery and use a 5V input to charge them. To do this they have internal control circuitry that ensures the battery's specifications are met. You can obtain suitable control electronics (in many cases as a single IC requiring maybe a few external resistors to configure it) and it makes great sense to use such a control circuit.
In an emergency you can use a 5V source to charge a 4.2V battery IF you know what you are doing and are able to ensure the battery specifications are adhered to. Failing to stay "in spec" may lead to the traditional LiPo "vent with flame" response, and even if there is no apparent damage the battery life can be greatly or very greatly reduced by out of spec treatment.
Key requirements are:

NEVER exceed 4.2V at battery terminals.
NEVER exceed Ichg_max = manufacturers max charging current.
This is usually the same value in mA as the battery capacity in mAh.
ie 1000 mA for a 1000 mAh battery
3300 mA for a 3300 mAh battery etc
When charging, EITHER stop charging when battery potential reaches 4.2V OR if you are able to hold the battery AT 4.2V, then stop charging when Ichg falls (under battery control) to say Ichgmax/4.
If Vbattery is under 3.0 V (which it NEVER should be) charge at no more than C/10 (eg  for a 1000 mAh cell) until Vbattery rises to >= 3.0V. If the battery will not rise to 3.0V under C/10 charge it is dead.

IF you can satisfy ALL these requirements at all times you can charge a LiPo or LiIon battery from 5V without a special charger.

No. You must use a charger properly designed for the battery; attempting to connect a Li-ion battery directly to a USB charger will damage the battery, possibly catastrophically.

https://www.youtube.com/watch?v=KWo4aDNnZT8

@Magic-Mouse The video is lots of fun, but does not address the issues involved. See my answer for details.

It does not address the issues, but it proves that LIPO is not a toy. And should be treated as if not.


text:
Is is possible to hook up an SD card and a GSM/GSRM module?
Is it possible to hook up a GSM/GSRM module AND an SD card at the same time to an Arduino Uno, or any Arduino?
I want to build a cellphone to read off the buttons that are being dialed into it for a poor guy who has no hope of using a regular cellphone, and I figure I need to include wav files for the buttons (and any other functions) on an external source.
I'm a good programmer, so if I can hobble the parts together I can make them talk to each other.  But, I'm not so sure the different schemes for this all use the same pins, so I was wondering if someone would be so kind as to enlighten me..

SD uses SPI and the GSM uses the Serial connection with AT commands

So this shouldn't be an issue?  Those pins aren't shared?

No the pins aren't, Serial is 0, 1, but the software serial is used because those are the programming pins on an arduino and SPI are 11, 12, 13

Yes.

But let me try to talk you through it.
Step 1 - Analysis/Requirements:
Get your requirements right, what should your system do, what functionality.
So, GSM functionalities and SD card savings (in short).
One of the requirements would be that's it on an Arduino (atmega 328P).
Any other hardware requirements?
Step 2 - Design:
Check the possibilities with the Arduino, 1 hardware serial and multiple software serial connections. One hardware SPI/I2C I believe.
SD cards often use SPI connection and GSM units most likely use serial.
So this works great. Check some tutorials on SPI and (arduino) serial.
Step 3 - Wiring up
Wire everything up, as defined in the datasheet of the devices. Cross the Rx and Tx lines. Put MISO to MISO and MOSI to MOSI accordingly.
Be sure everything has enough power (GSM modules typically draw a lot of current when sending/connecting). Usually, if you find out that two devices are attached to the same pin, there might be something wrong (unless you can declare how they're seperated or why this is the case).
Step 4 - Implement
Well, you stated you're good at programming, so I'll leave this open for you.
But mind that it's only one of the three steps, so you should look at some tutorials, it'll learn a lot faster than asking everything. Try to get a bit comfortable with your thoughts, base them on things you have learned.

So this shouldn't be an issue? Those pins aren't shared? - user1833028

Things like this can be found in the device's datasheet and if you follow some tutorials you'll see that they're different and why.
Also, what helps for me often, is to try to seperate this 'big' project into two smaller projects.
Try to get the GSM working and after that you go for the SD card reader.


text:
Convert string plus hexadecimals to array of hex:
I have a string which I send to the arduino using serial monitor. Something like that:
my specific string 0x0F 0x2C 0x98 0xBC

How can I parse this string in the arduino to get an array of hex values:
0x0F 0x2C 0x98 0xBD

? There are two prerequisites:

All hexadecimal starts with #
The size of hexadecimal is 2. No 0x111 or '0xbbb'

Do hexadecimals start with a #, as you wrote in the text, or with a 0x, like in the example?

It would be easier to send decimal numbers over the serial and read them as so. After that you can read them from the array as HEX values?
If you have the possibility to change whatever is sending through your serial.

How can I parse this string in the arduino to get an array of hex values:

There are a few standard library (stdlib) functions that can help you with that. Below is a snippet:
char buf[] = "0x0F 0x2C 0x98 0xBD";
uint8_t val[4];

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

  char* bp = buf;
  int i = 0;
  do {
    char* ep;
    val[i] = strtol(bp, &ep, 16);
    Serial.println(val[i], HEX);
    bp = ep;
    i += 1;
  } while (*bp != 0);
}

void loop()
{
}

Cheers!

You can try reading each character and convert it to hexadecimal representation.
I suppose you wanna 1 byte each value in hexadecimal representation, so, let's start.
For example the string "0x25", ignore the 0x and read the '2' and save it into a char variable. Same for '5';
char highBits = '2' - '0'; // convert to decimal representation
char lowBits  = '5' - '0';

byte = (highBits << 4 | lowBits);

Now, save it inside you array. Make sure you check if the value is one of the possible letters in hexadecimal and convert it properly (A=10 and so on).
Just include an if statement if it is a letter and convert it.


text:
Install Bluetooth inside a home theater, How?
I have a 5.1 home theater(old one), I would like to transform it into a audio streaming system. I have a Arduino UNO and HC-05 Bluetooth Module, and I don't know how to install it in my home theater(if it does). solution please...

Can you be more specific please? What are you wanting the Arduino to do?

I don't know, just mentioned that I have..

You want to use the arduino to override the buttons of your home theather?
Or do you want your arduino to send IR commands (same as a remote) to your home theather?

I just want to make my home theater into an A2DP bluetooth audio reciever..thats all..please give me solution regarding that..

@Harish Were you able to do it? Could you please share the details?

I don't think this will be feasible. There are two main issues:
1. I don't think there's a sensible way to get the HC-05 module to work with A2DP. It's great for a simple serial connection, but Bluetooth-enabled media devices generally won't connect to it if they're looking for audio streaming systems (as far as I know).
2. The Uno probably isn't powerful enough. Even if you could get the audio data into it, I don't think it will be able to decode the information to an analog audio signal in real-time.
Something like a Raspberry Pi with a suitable Bluetooth module might be a better choice for this.

So could you suggest me any Bluetooth module that works like A2DP, so that I can install in my home theater.

I would suggest something like this, if you want your stereo to be able to receive music over bluetooth:
http://www.tinydeal.com/en/Bluetooth-Music-Receiver-A2DP-Wireless-HiFi-3-5mm-Stereo-Audio-Dongle-Adapter-p-70931.html?currency=EUR&ship_to=NL&gclid=Cj0KEQjwgI6pBRDak6aRovWNqLsBEiQA8zZSLttsqa4WBkkKJSjTnlIndXji0IkOhH4QXCRPJiaEqyEaAly68P8HAQ
Cheaper as an arduino, way easier and actually possible.


text:
Can I use ATtiny48 as a board in Arduino?
I have seen people using ATtiny45 and other boards and there are hardware configurations files for them. Can we use ATtiny48 as a processor for Arduino?
If so where can I get a boards.txt file that supports it? Alternatively how can I write such a file?

@Gerben that is "MEGA48" ...


text:
How to reset an Arduino with node-serial?
I was reading about using an Arduino with a Makefile. In the Makefile-Arduino project there is a reference to the Python serial library required to reset the board.
Looking into the usage of PySerial to reset the board, there is some reference to DTR or here

What is DTR?
How to control this bit with node-serial and reset the Arduino?


text:
Overloading function loop
I want to introduce a boolean that is the first iteration of loop and then false
every subsequent iteration. I want it invisible, so I have to modify loop in some way. Is that possible?

What do you mean by "I want it invisible"?

I use plclib to teach how to program the control system and I want it to be as much like real systems as possible,(no c-syntax) and when programming a sequence, it is standard with a variable with the property described in my question. Students can nothing about programming and must learn to program control systems in industry-standard I have managed to avoid c++ - syntax so far.
I added a function called start() to the library, but it complicated the logic of the code in a way that is not very educational.

So I have managed to get a number of funktions that allows one to program the arduinon without using anything other than the language elements that are similar to those found in industrial control systems, and to avoid the destrucktion of the illusion the variable need to be invisible

So you want a variable that is limited in scope so it can only be used within your library, and is inaccessable to other (student) code?

So you just want to redo what you already have: setup() called once the first time, and loop() called forever afterwards? What's the point? You should edit your question to make it much clearer what you really want.

The way to do this isn't to overload the loop function, the way to do this is to abuse the linker and replace main().
The main.cpp file that gets used in the Arduino make prototypes main as int main(void). On my system at least the linker prefers the longer prototype, so you can just do this:
int main(int argc, char* argv[])
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    //The one shot loop...
    loop();
    if (serialEventRun) serialEventRun();
    //Put whatever else you need to do between before the unending loop here.

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

Both get compiled, but the int main(int argc, char* argv[]) prototyped version gets linked as the entry point, so your "invisibile" code gets executed.


text:
EEPROM value reverting to 255
When I write '13' to the EEPROM and read it straight after it works correctly.
However when I comment out the write part of the code and try to just read the data, the value is no longer 13 as it used to be but reverts back to 255. Whats going on?
I am running a standalone atmega328 on a breadboard with a 16mhz crystal, programmed by a Nano R3.
void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT);

//EEPROM.write(1,13);
}

void loop() {
scoreBinary();

}

void scoreBinary(){

int score= EEPROM.read(1);

if(score==13){
digitalWrite(2,HIGH);
}
delay(10000);
}

By default the EEPROM in the MCU is erased (to 0xff) when the chip is erased before flash is written to. If you want to prevent this then you will need to program EESAVE in the fuse bits, which is bit 3 in the high fuse byte of the '328.

Ah! Thank you! Makes sense! Now to change the fuse bit should I change the value in boards.txt ? Currently the high fuse byte is diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xDA (1101 1010 in binary) And I should change this to diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xFA (1111 0111 in binary) Is that correct =/ ?

Or perhaps theres something I can type in the cmd using avrdude?

Read the current high fuse value (avrdude ... -U hfuse:r:-:h), bitwise-and it with 0xf7, and write it back out.


text:
Communicate with custom usb slave device with DUE?
I have a arduino due which i know has usb host mode. The usb library that comes with the due supports mouse and keyboard.
I have another usb device (diacnostic tool) id like to talk to, it use a:
USB Com Board Driver ( Multi-instance )
TI USBN9604
"Universal Serial Bus Full Speed Node Controller with
Enhanced DMA Support"
datasheet: www.ti.com/lit/ds/symlink/usbn9603.pdf
Ive also logged the raw byte usb traffic between windows and it when operating and would like to try sending some of those same calls to the device with the due.
Where do i start ?
Example Capture:
    000000: PnP Event: Device Connected (UP), 12.04.2015 09:14:51.390 (1. Device: USB Com Board Driver ( Multi-instance ))
The USB device has just been connected to the system.
000001: Bulk or Interrupt Transfer (DOWN), 12.04.2015 09:15:14.953 +23.562 (1. Device: USB Com Board Driver ( Multi-instance ))
Pipe Handle: 0x8639885c (Endpoint Address: 0x6)
Send 0x1b bytes to the device
 40 05 17 C0 00 09 02 00 AA 00 00 00 00 00 00 00
 00 00 00 00 00 00 00 00 16 06 12

i found what i needed here: http://arduino.cc/en/Reference/USBHost
and
https://github.com/felis/USB_Host_Shield_2.0


text:
float precision in arduino
I am reading a string which i have to convert into a float with a maximum of precision.I didn't want to use toFloat() function since it make a truncation so i made my own code.
My problem is that the final result is also approximated.
I need a precision of 4 digits after the float.I read the documentation about float in the arduino website.They say it should be maximum 7 digits of precision but i don't get it.When i test my code on the value of '23,459' ,all i get is 23,46.
Any suggestions?
void setup() {

 Serial.begin(9600);

}
int longu=0;
char data='2';
  String data2="23,459";
  float val=0;
  int posVir=0;
  int t=0;
  float postVir=0;
  float preVir=0;
  int lonPostVir=0;
  int lonPreVir=0;
  float posvir2=0;
  void loop()
{

   lonPostVir=(data2.substring(posVir+1)).length();
   lonPreVir=(data2.substring(0,posVir)).length();

   longu=data2.length();
   posVir=data2.indexOf(",");
   preVir=(data2.substring(0,posVir)).toFloat();
   postVir=(data2.substring(posVir+1)).toFloat();
   posvir2=postVir*pow(10,-lonPostVir);
   val=preVir+postVir*pow(10,-lonPostVir);

  Serial.println(val);

    }

Serial.print only gives two decimal points. (Otherwise it would return 23.4589996337890625 as that is the closest float value that exists.)

Are you sure about that sir?

Sure about which of the two statements?

I confirm that 23.4589996337890625 (i.e. 12299272/2^19) is the float32 nearest to 23.459.

The simplest way to get more decimal places to print is this:
Serial.println(val,NUMBER_OF_DECMIAL_PLACES);

This will print out any number of digits after the decimal place. Regular print without the number of digits specified will default to 2 decimal places. for example, here is some code and the result that gets printed:
float val = 23.459;
Serial.println(val);
Serial.println(val, 4);
Serial.println(val, 10);

23.46
23.4590
23.4589996337

You may notice that with 10 decimal places printed you can start to see how much the actual value of 23.459 needs to be approximated to fit within a floating point number. This is similar to how 1/3 can not be represented 100% accurately in a finite number of decimal digits; 459/1000 cannot be represented 100% accurately in a finite number of binary bits, so it is approximated.
Also, note that for non-floating point numbers the optional second argument to print and println is the base it should be printed in (dec, hex, oct, ...) and has nothing to do with precision.

Just write the amount of numbers you want to get float here Serial.println(val); after the val.
example:
Serial.println(val, 5);
It will give 5 digits after the decimal point


text:
How to make universal remote controller?
I am trying to make simple TV remote using Arduino.
I got this link from Google for making a remote.
Code uploaded perfectly on my device. But all it does is blink a the LED on pin 13.
I hope I have got right code. I have tested it on my TV at home. Is that the correct way of testing it?
IR receiver I have is TSOP-15
P.S. I am completely new to Arduino
The below shown is my Arduino board(induino r3)

As you've stated in your question, the TSOP-15 is a receiver. That means it detects infrared signals rather than sending them out.
To make a remote control with that code, you need a simple infrared light emitting diode.
It's also important to note that you need to know what signals to send. Different TVs will have different IR codes, depending on the manufacturer. That information can be detected using your receiver module along with your TV's proper remote control.

By infrared light u mean IR led? Because there is IR LED- 14 on the board

@Freddy Yes, an IR LED is correct. You would need to modify the code to operate on pin 14 instead of 13 though.


text:
Getting started
so I am not a newbie to computers or programming. I regularly program in C# and Java, know quite a bit about computer hardware and operating systems. But I am bored of writing stupid calculators or game bots. I want something exciting and something that involves physical hardware. So I want to get into electronics and micro-controllers. I was wondering how I should go about this? Any topics I should read first? How electrics work maybe? Any guides I should skim over? I plan to buy the Arduino starter kit and a load of components, along with a soldering iron etc soon; but want to get reading now. I do not need to go right into the advanced stuff but I like to know how things work before I use them; not just "plug this wire here to do this". Any help is much appreciated.

Here you go.

Just think of a cool/useful project.  Do some research. Look at related projects others have done. And then make it. Jumping right into the deep end. No boring books with example you need to replicate. That's what worked for me. I too came from a software developer background.

The best way to get started is surely by reading a book, I would recommend

Getting Started with Arduino
Exploring Arduino

Besides, there are many tutorials on YouTube also to start with.
But books are just one thing. Arduino or electronics is more about getting a hands on experience. Even if you have read a hundred times on how to blink a LED it is difficult to do it when doing it on hardware. So the best thing for you is to work with small small codes.
Say initially just blinking a LED(thats like the HelloWorld of electronics) and then moving on two patterns with LED. As you get used to the IDE and the hardware move on to more challenging projects like simple DC motor control or servo control. Try and make your own projects with your imagination. The challenges which you face teaches you more than any book. Then move on to serial and wireless communication and try working with a few sensors on the ADC and start making small projects.

Eh. Hands-on experience is part of any technology, but without the theory to back it up you're limited to putting large blocks together unless you don't mind accidentally destroying something. Not that I'm saying that destroying things is bad per se, just that it becomes safer and easier with the theory.

A quick search on Amazon found a number of basic books on electronics. I'm not familiar with any of them to recommend one of them. But "plug this wire here to do this" isn't a bad way to start - you'll probably have some questions about what this component is for or why they had you connect it the way they did. That will give an immediate direction to your studying which in turn will bring in some more questions and more information.
If you really want some basics ahead of time (noting that I don't know what will be basic for you), you might search for Ohm's Law (voltage and current through a resistor), and Kirchoff's Laws (voltage and current in electric circuits), and follow any leads that look interesting. Look up some common components that you'd find in a starter kit, like resistors, capacitors, and LEDs. But things will begin to get "real" for you once you have parts in hand and start using them to make some basic stuff like making lights blink or fade, motors turn, and buzzers buzz.


text:
Arduino Uno + 2 Monster Motor Shields
I've got an Arduino Uno and two Sparkun's Monster Motor Shields.
The aim is to control 4 motors.
There is no problem to control 2 DC motors with single motor shield. There's a manual on how to do it .
But how can I control all of motors (address commands to each of them) when I stack motor shields one on one?
Thanks in advance.

I actually wouldn't stack them. Check which inputs you have on the boards and which outputs you'll take for them on your arduino. Then wire them seperately. Or you could put one in the arduino and wire the other induvidually. Why do you actually need two motor shields if I may ask?

I need a 4WD vehicle being able to carry 50 kgs of weight. Splitting this load between 4 wheel drives helps find cheaper DC motors with moderate characteristics. That's it. Any ideas?

You can make it 4WD with one motor shield. Use one output for the left side and one for the right side. And I guess you should then wire the motors parrallel as then they'll have their own power circuit.
This way you also avoid any possible driving mistakes, where you try to put both motors on one side against eachother.

can you please share the UNO to Monster Motor Shield pinout diagram please... and which Arduino code did you use with this combination? your help will be much appreciated. thanking you in advance.

A shield is simply a PCB that fits on an Arduino. You cannot stack them, because then they would use the same pin layout. Instead, connect each shield to different pins based on the requirements set in the documentation of the shield.

Not really the answer to your question, but an alternative solution, which has proven to work in my case.
We were working on a line-following robot with an ATMega 328P (Same as arduino, but withouth shields) and thus we wired an shield directly. For the shield we used, we only needed 4 inputs (pwm left, pwm right, direction left, direction right). Try to find out what your shield is using, on which pin, and you can drive the shield directly withouth stacking them (as they then would use the same pin).

My alternative solution would be to use 1 driver. And wire the motors parrallel.
If you choose to use 1 shield, you can stack it. But for other shields you have to check which pins to use. There is no drawback on using one shield, the only thing is that the motor driver will draw more current, but they're basically designed for this.

Thank you pals! I have just decided to refuse using 2 shields at the same time because of possible driving mistakes. Converting my device into a tank is indeed a solution. Well, at least it'll drive more predictably. Thank you all one more time :)

You don't actually need to use threads/tracks on your 'car' (though it does look cool). In our application it actually worked with 4 wheels.
Steering, would otherwise also need a servo.
Consider accepting this solution as an 'answer' by pressing the ✓


text:
Can I connect a PWM pin on one Arduino to an analog input on another?
I was considering several different ways to send simple data from one Arduino to another when I though, why not connect a PWN pin of one Arduino to the analog pin on another?  I could send simple messages for one to the other by setting different values on the PWM pin.  This seems like it would work, except for the fact the the PWM pins mimic voltages with pulses.
Is this a reliable way to link two Arduinos, If I only want to communicate 4 states?  Also, will I need to include some additional components in the connection (resister, capacitor, etc.)
All it needs to do is send a 2v pulse for yes and a 5 v pulse for no. It needs to do this about 6 times an hour.

Yes, you can do this with "a little programming"  or more easily by adding two cheap components.
If you connect a say 47k resistor from PWM_Out to Analog_In and a say 100 uF capacitor from Anaolg_In to ground you will be able to read the equivalent analog value to an accuracy of around 1%. Read it N times (maybe 10 times) with a delay of say 12 ms between reads and average it for a better result. This works because the PWM period is about 1 mS so delaying for a period of multiple cycles but not an exact multiple means you sample semi randomly.
For the sort of resolution that you want (4 levels) a MUCH smaller capacitor could be used (maybe 1 uF.) But even a 100 uF capacitor is cheap.
You could instead use PWM out (analogWrite) and a digitalRead.
Perform say 100 digital reads with say 12 ms between reads (so about 1.2 seconds total) and keep two counts - PinWasHigh and PinWasLow for (obviously) high or low conditions. The contents of PinWasHigh tells you what % of reads was high. Due to random sampling you cannot rely on this for 100 levels but determining say 10 levels should give good accuracy. The sum of PinWasHigh and PinWasLow should total 100 as a sanity check.
While use of a serial port (hardware or software) or SPI allows more data transfer per time and without much effort, this simple analog method is good enough for many applications.

Great answer, I eventually went with the no-component solution that you gave towards the bottom of you answer

@Hoytman I avoided mentioning a similar solution that takes slightly more coding knowledge but is faster to read. The Arduino PWM takes ABOUT 1 mS per cycle. If you dave the value of micros() when it goes high and compare it with the value when it goes low again you get the APPROXIMATE high time in microseconds. You can do the same thing for low time. The two should add to ~= the PWM period. Once you are confident in the ability to read the high pulse duration and have a feel for the variations to expect you can read the PM % high in maybe 2 mS.

It is possible, but not the best idea. The analog inputs require a reasonably stable input - this can be achieved with a RC filter to smooth the PWM output. This would work for reasonably slow data rates.
You would be better to use one of the many communication protocols supported by Arduino (serial, SPI, I²C).

The best choice would be to use SPI, as it is the fastest communication method. Instead, the easiest to use (at least from what I learnt) is I2C

All it needs to do is send a 2v pulse for yes and a 5 v pulse for no.  It needs to do this about 6 times an hour.

@Hoytman, then why don't you send a 1 second pulse for yes, and a 10 second pulse for no? Just pull (at least once per second), and count how long it is before it goes back down?

For greater precision, less code, faster execution and no need for capacitors read the PWM "analog" signal on the other Arduino from a digital input pin with
pulseIn(pin, HIGH, timeout)
The timeout is optional (1 second by default). As soon as the line goes high, a timer engages and automatically stops the instant the line goes low.
The primary reason to use PWM communcation (as opposed to i2c, SPI, etc.) is to broadcast to an unlimited number of devices simultaneously without the need for a clock signal or acknowledgement.
We are currently using this method of communication for neural networks composed of separate tiny processors for each neuron substructure (one processor for each synapse and activation function).

Indeed, this is quite a bit better than the filter methods, if the processor can be available to take the measurement then.  If not, some better use of hardware timers and interrupts should handle it.  But all of these schemes are generally inferrior to place-value-coded communication channels like asynchronous serial, I2S, SPI, etc.

Full solution to receive PWM signal and convert to a like analogRead() one. Its based on @Cortex_systems answer and Id like to share it to help others with a more comprehensive answer.
int var = pulseIn(digitalPin, HIGH, 4200);
if (var == 0 && digitalRead(digitalPin) == 1) {
    var = 2100;
}
var= map(var, 0, 2100, 0, 1023);

Here is the why:

You can not just read PWM signal to analog pin in arduino. We will
receive the PWM in a digital pin with its pinMode set to input and read it with pulsIn(pinNum, high/low, timeout).
pulseIn() records the length of the pulse. Longest pulse in PWM is 2100 microseconds.
Timeout is set to 4200 for 2 cycles of PWM. Without this
it will wait for a new high and freeze the code in cases that PWM is
0 or 255.
At max and min this will read 0, so in that case check with digitalRead() to determine and adjust.
Finally, map the result so it appears like an analogRead().

Note! This adds a delay of up to 4.2 milliseconds to code.

To read PWM without delay use Interrupts http://www.camelsoftware.com/2015/12/25/reading-pwm-signals-from-an-rc-receiver-with-arduino/


text:
Memory Problems on Arduino Uno
I am doing a project using Arduino UNO, cc3000 WIFI chip, micro SD card shield, and a TTL serial camera in order to make a security system that will post a picture online (not enough processing power for video) when motion is detected on the camera.
Thankfully, the hardware works after a few shortcomings, but my program seems to be taking up 97% of the Flash storage.
Also, I am looking for a better way to transfer the image than saving it 32 bits at a time and then waiting about 10 sec so the HTTP request will send it to the server.
One thing I do know is that I have tested all the hardware and those functions are working. My problem is in the logic.
Any help appreciated! (Image is around 13KB and UNO only has 2kb of dynamic memory).
My full code is here: https://www.dropbox.com/s/arxa253mxwvqtg1/HomeProj.rtf?dl=0
void loop(void)
{
    cam.setMotionDetect(true);

    while (1) {
        if (cam.motionDetected()) {
            Serial.println("Motion!");

            cam.setMotionDetect(false);
            if (! cam.takePicture())
                Serial.println("Failed to snap!");
            else
                Serial.println("Picture taken!");

            uint16_t jpglen = cam.frameLength();
            Serial.print(jpglen, DEC);
            Serial.println(" byte image");

            char filename[13];
            strcpy(filename, "IMAGE00.JPG");
            for (int i = 0; i < 100; i++) {
                filename[5] = '0' + i/10;
                filename[6] = '0' + i%10;
                // create if does not exist, do not open existing, write, sync after write
                if (! SD.exists(filename)) {
                    break;
                }
            }

            File imgFile = SD.open(filename, FILE_WRITE);
            while(jpglen > 0) {
                uint8_t *buffer;
                uint8_t bytesToRead = min(32, jpglen);
                buffer = cam.readPicture(bytesToRead);
                imgFile.write(buffer, bytesToRead);

                //Send Request
                Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
                if (client.connected()) {
                    Serial.println("Connected!");
                    client.println("POST /upload HTTP/1.0");
                    client.println("From: Arduino");
                    client.println("Host: fierce-chamber-5675.herokuapp.com");
                    client.println("Content-Type: image/jpeg");
                    client.println("Content-Length: " + 32);
                    client.print("Connection: close");
                    client.println();
                    for(int i = 0; i < 32; i++) {
                        client.print(buffer[i], HEX);
                    }
                    client.println();
                } else {
                    Serial.println(F("Connection failed"));
                    return;
                }
                client.close();

                Serial.println(F("-------------------------------------"));
                jpglen -= bytesToRead;
            }
            imgFile.close();
            cam.resumeVideo();
            cam.setMotionDetect(true);
        }
    }
}

You are running a wireless TCP stack, an SD card interface, and a web camera with some sort of motion detection, on a less than $20 computer?  I think you should congratulate yourself and move on to the next project.
I believe you are asking too much to add more to it. At $20 a pop, I would think about adding another UNO if you really do want to add more functionality. Let the 2 talk via serial, with one processing the video, the other processing the wireless.  The TCP part uses a considerable amount of resources, both memory and processing power.

Dude its not $20, its $35. I ran out of pins and had to buy a micro SD card shield. Its tough getting enough money when you are a 14 yr old. But I get your point. Still, I want to try and get this project running because I want to install it in front of the house as a security system. Mostly just about saying, "I did that," and applying prior knowledge to real life application.

https://www.sparkfun.com/products/12757

Instead of using HTTP you could write your own TCP/IP server on the host.  Good practical learning experience. You should be able to reduce the 10 second latency by avoiding the overhead of web. Google TCP sockets. I understand you resource concerns. My present Arduino project is at 94% capacity.

The other thing is it is best to let your loop function get called from the Arduino software, instead of looping itself. That way housekeeping can take place. Move the setMotionDetect to setup. Maybe not doing it that way is leading to some additional delay?


text:
How do I find which values are corresponding to the changing values from my phototransistor?
I am new to using serial input. I have an IR emitter and a photo transistor hooked up to my Arduino, I am trying to see which values corresponds to the colored object I put over my IR emitter and phototransistor.
How do I find which values are corresponding to the changing values from my phototransistor?

Could you add code and a terminal dump from the monitor please?