text:
Request for member is Non-class type
Im getting this error:
iotHook.ino: In function 'void setup()':
iotHook:13: error: request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'
request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'

When I try to lunch my begin function of my class:
class Esp8266 {

  public:
    Esp8266();
    void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
    ...
  private:

    HardwareSerial *wifiCom;
    HardwareSerial *debugCom;
    ...

}

Esp8266::Esp8266() {
}

void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
  this->wifiCom = wifiCom;
  this->debugCom = debugCom;

  this->debugCom->begin(115200);
  while (!this->debugCom) {
  ;
  }
}

EDIT 1:
Updated image with new code

Why is not picking up the begin function?

Remove the brackets from your constructor.

@Majenko You mean from this Esp8266::Esp8266() {} to Esp8266::Esp8266() ???

No, what Ignacio says. The constructor in your sketch.

Your current problem is that the USB Serial interface of the Leonardo isn't a hardware serial device, it's a CDC/ACM device, and the class for that isn't HardwareSerial, it's Serial_.
So you can't pass it to a function that expects a HardwareSerial.
What you should be using, instead, is the Stream class.  That will allow you to pass any object that is based on the Stream class, such as HardwareSerial, Serial_, Client, etc.  Many different things, including serial and networking protocols, use Stream as their base class.
It does have the down side, though, that you have to initialize the Stream objects in your sketch (that is, do the Serial.begin(...) and Serial1.begin(...) in your sketch not your class) because the Stream class doesn't have the concept of a baud rate, and so no begin(baud) function.
This is what I mean:
class Esp8266 {

public:
    Esp8266();
    void begin(Stream &wifiCom, Stream &debugCom);
private:

    Stream *_wifiCom;
    Stream *_debugCom;

};

Esp8266::Esp8266() {
}

void Esp8266::begin(Stream &wifiCom, Stream &debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;

    while (!_debugCom) {
        ;
    }
}

Esp8266 esp;

void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    esp.begin(Serial, Serial1);
}  // end of setup

void loop() {
}  // end of

Note, as well, my use of pass-by-reference (Stream &whatever) so you don't have to pass a pointer in your begin function.  Also notice the use of unique variable names in the class (I always prefix my member variables with _) so you don't have to keep putting this-> in everywhere.

To be able to move the .begin() function inside your class you will have to use both HardwareSerial and Serial_ object types within your class.  There's two ways this may be done.
First is dynamic casting:
void Esp8266::begin(Stream &wifiCom, Stream *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;

    HardwareSerial *hard;
    Serial_ *cdc;

    if (hard = dynamic_cast<HardwareSerial*>(_wifiCom)) {
        hard->begin(115200);
    } else if (cdc = dynamic_cast<Serial_*>(_wifiCom)) {
        cdc->begin(115200);
    }

    if (hard = dynamic_cast<HardwareSerial*>(_debugCom)) {
        hard->begin(115200);
    } else if (cdc = dynamic_cast<Serial_*>(_debugCom)) {
        cdc->begin(115200);
    }

}

I haven't tested this, and I don't know if the Arduino's cut-down C++ library is even capable of it, but it's worth a try.
The other method is to overload the .begin() function of your class with multiple versions that take different parameters:
void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    wifiCom.begin(115200);
    debugCom.begin(115200);
}

void Esp8266::begin(HardwareSerial &wifiCom, HardwareSerial *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    wifiCom.begin(115200);
    debugCom.begin(115200);
}

void Esp8266::begin(HardwareSerial &wifiCom, Serial_ *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    wifiCom.begin(115200);
    debugCom.begin(115200);
}

You're still storing them internally as Stream objects in all cases, but within the begin() function itself you also have them available as their child classes.  It does mean you have duplicate code copied between the different versions of begin().  You could modularize it a little more though by moving the duplicated code into functions which would only need to be duplicated twice, not three times - one to act on a single Serial_ object and one to act on a single HardwareSerial object:
void Esp8266::initSerial(Serial_ *ser) {
    ser->begin(115200);
}

void Esp8266::initSerial(HardwareSerial *ser) {
    ser->begin(115200);
}

void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
    _wifiCom = &wifiCom;
    _debugCom = &debugCom;
    initSerial(&wifiCom);
    initSerial(&debugCom);
}
... etc x3 ...

Thank you, this is the cleaner answer. Is not very clear to me why I have to initialize the stream object outside of my class. Is important to me because my code have a guessing routine inside my begin function that tries different baud rates till it finds the correct one (http://pastebin.com/GYjE48yj), since I cant use .begin(speed) inside my class, do you know any workaround?

@DomingoSL It's because the .begin(baud) function only exists in the HardwareSerial and Serial_ child classes and not the Stream parent class.  You could try using dynamic casting to attempt to convert the Stream objects into first a HardwareSerial object and then (if that fails) a Serial_ object, but how that would perform (if it's even possible) on an Arduino is anyone's guess. The other option is to provide multiple begin() functions or constructors that take all the possible different combinations of object types and deals with them accordingly.

@DomingoSL I have added more detail to my answer.

You've confused the compiler by making it think that esp is a function that takes no arguments and returns a Esp8266. But the no-argument constructor is called by default, so you don't need the parens there regardless.
Esp8266 esp;

Updated code according to your answer but same error

Please check the edit I made

You do see that that's a completely different problem, right?

The line:
esp.begin (Serial, Serial1);

Should be:
esp.begin (&Serial, &Serial1);

It is expecting a pointer to a HardwareSerial instance.

Also make the instantiation line:
Esp8266 esp;   // <--------- no brackets!

This compiles without errors for me:
class Esp8266 {

  public:
    Esp8266();
    void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
  private:

    HardwareSerial *wifiCom;
    HardwareSerial *debugCom;

};

Esp8266::Esp8266() {
}

void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
  this->wifiCom = wifiCom;
  this->debugCom = debugCom;

  this->debugCom->begin(115200);
  while (!this->debugCom) {
  ;
  }
}

Esp8266 esp;

void setup ()
  {
  esp.begin (&Serial, &Serial1);
  }  // end of setup

void loop ()
  {
  }  // end of loop

I would rework to use references anyway, saves all that mucking around with pointers:
class Esp8266 {
  public:
    Esp8266(HardwareSerial & wifiCom, HardwareSerial & debugCom);
    void begin();
  private:
    HardwareSerial & wifiCom;
    HardwareSerial & debugCom;
  };

// constructor
Esp8266::Esp8266(HardwareSerial &wifiCom_, HardwareSerial &debugCom_)
  : wifiCom (wifiCom_), debugCom (debugCom_)
  {
  }

// initialize stuff
void Esp8266::begin()
{
  debugCom.begin(115200);
  while (!debugCom)
  {
  }
}

Esp8266 esp (Serial, Serial1);

void setup ()
{
  esp.begin ();
}  // end of setup

void loop ()
{
}  // end of loop

Corrected for Leonardo
Sorry, my reply above was compiled for the Mega2560, I didn't notice the Leonardo tag.
Majenko is quite right, you need to rework for the Leonardo. My example using references can reduce down to this now:
class Esp8266 {
  public:
    Esp8266(Stream & wifiCom, Stream & debugCom)
      : wifiCom_ (wifiCom), debugCom_ (debugCom) { }

  private:
    Stream & wifiCom_;
    Stream & debugCom_;
  };

Esp8266 esp (Serial, Serial1);

void setup ()
{
  Serial.begin (115200);
  while (!Serial) { }
  Serial1.begin (115200);
  while (!Serial1) { }
}  // end of setup

void loop ()
{
}  // end of loop

By storing a Stream type you can still print to them, however you need to initialize in setup, not in the begin function, which now becomes redundant.
I agree about not using this-> although my preference is for trailing underscores as the use of leading underscores is reserved in quite a few cases, depending on the location and capitalization.

Now the error is:Esp.h:42:6: note:   no known conversion for argument 1 from 'Serial_' to 'HardwareSerial'
no matching function for call to 'Esp8266::begin(Serial_, HardwareSerial)'

With arduino ide 1.6.5: Esp.h:42:6: note:   no known conversion for argument 1 from 'Serial_' to 'HardwareSerial'
no matching function for call to 'Esp8266::begin(Serial_, HardwareSerial)'

You're thinking double-underscore.  Builtin (predefined) macros have the format __BLAH_BLAH (sometimes with trailing __ too)  although some older compiler versions have some non-standard ones with just one underscore (they are naughty).  Certainly for avr-gcc version 5.2.0 all the predefined macros (with the exception of #define AVR 1) are in the standardized double-underscore format.

According to the C++ Standard: Reserved in the global namespaces: identifiers beginning with an underscore. Thus all identifiers in global namespace, starting with an underscore, are reserved. Also reserved in any context are identifiers beginning with an underscore and an uppercase letter. In addition: identifiers containing adjacent underscores (or "double underscore"). So you are only one capitalization away from a reserved identifier, by using leading underscores. You might be tempted, for example, to make a class constant like _ITEM_COUNT which has now become reserved.

Reserved doesn't mean unavailable.  If you like, all my member variables are reserved - I don't want anyone else using them.  Any my constants are most static and ProperlyCapitalized (as are my class names) since they aren't reserved.

That is a completely different thing. I don't want anyone else using them You can achieve that by making them private. If you use a reserved identifier (which possibly becomes a #define) then you run the risk that a word like _FOO will be replaced by some define which the compiler-implementers are entitled to use, and then find all your code doesn't compile. Whatever your motives are, you should not be using reserved identifiers. There has to be a set of identifiers that compiler-writers can use. They have specified what they are. Use them at your peril in your own code.

As if I would ever be daft enough to use _FOO as a variable. And if I did use it as a macro it would complain during compilation. And you never expose member variables to the wider public - you always have them private (or at worst protected) and use getters and setters. You never use all capitals for variables either, that's just daft. So _FOO is never going to be a conflict, since my member variables would never even approach that format. In my past 30 years of programming I have never come across a conflict like you mention. That can't just down to luck, or I'd have won the lottery by now.

The issue is not whether or not you are daft. The issue is, do you follow the Standard, or not? Look, over the years I've written a lot of code with leading underscores, probably a hangover from the way Microsoft did it. So, I did it too - in the past. Of course, you are free to not follow the Standard. And you may never have a problem. But if you choose to use reserved identifiers, and one day one of them becomes #defined as some weird sequence of characters, you will be scratching your head as to why you get a compile error on what looks like a perfectly good line of code.


text:
Powering arduino and sensors and motor damaging 16x2 LCD?
I have an application that requires reading sensors and moving a stepper motor.
The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.
My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.
From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.
The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.
This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.
I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?
Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).
And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)

Could you please post a picture of your setup. 2. Have you used bypass caps? 3. Are you sure that there isnt some loose connection between the LCD and the arduino?

Well, it's a bit of a rats nest, to be honest. As well as the sensors there are also some button boards, some peripheral boards with LEDs etc, All of which need 5V. I'm not sure a photo will be that useful. 2. No, I haven't done this yet. But when I test the LCD on another Arduino without any other attachments, it still doesn't work. I'm wondering if the LCD panel is permanently broken. 3. I've tried connecting to another arduino, still no luck. The thing is; are LCD boards sensitive to voltage spikes or reverse polarity.

In that case please upload the schematics. Have a look at http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/ for some general info on protecting your circuit

I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. This sounds like a round-about way of doing it. Just plug the 5V regulated output into the 5V pin on the Arduino board. Make sure you have all the grounds connected.

If I simultaneously connect the Arduino to my laptop (to program it and see the serial messages) and connect 5V from the regulated supply to the Arduino 5V pin (and regulated ground to GND), aren't I effectively connecting the regulated supply to the laptop regulated supply? What happens if there is 4.9V on one and 5.1V on the other?

In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.
A few suggestions:
Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister.  That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.
You should also check the pins for continuity errors, or shorts.
Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.
And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.
I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.
I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.

source: Stack Exchange

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

sort: votes


text:
Knowing the Ohms of a Radio Speaker
I have extracted a speaker frim a cheap radio. And I want to connect it to arduino uno. But, I dont know the rating of the speaker. And I am Afraid that If it is over rated, it can fry my arduino. The diameter of the speaker is 9 cm (approx). Whether this Speaker is more likely to be  of 4 ohms, 8 ohms, or 16 ohms ???
I dont have a multimeter...What cam be the probable value of speaker ?

Have you tried measuring it?

I googled "measure speaker resistance" and found http://www.wikihow.com/Measure-Speaker-Impedance
Step by step instructions
You will need a multimeter - a great thing to have in any case.

I dont have a speaker. What can be the probable value of The speaker. according to its Diameter (9 cm) ?

I have extracted a speaker from a cheap radio. ... I dont have a speaker. - Do you have a speaker or not?

Sorry that was mistyping. I have a Speaker but I dont have a Multimeter. What can be the probable value of The speaker. according to its Diameter (9 cm) ?

What difference will it be in your application if it is 4 or 8 Ohms? Do you really need to know? Just go ahead and test it with a series resistor.

Get a multimeter. If you are doing anything electronics related, you will need one sooner or later. They're not expensive. Or find your local hackerspace/makerspace - they are usually happy to let people use their tools (take your speaker in).  They can also teach you to use the tools. And they're great guys. I don't know where you live, so some of the above statements might not apply to your local hackerspace (but probably do).

I'm not aware of any simple rule that relates speaker diameter to speaker impedance.  Traditionally, 8 Ω is quite likely for typical cheap speakers, with 4 Ω not far behind in likelihood.
As pointed out in the Measure Speaker Impedance link that AMADANON gave, the DC resistance of the speaker's coil will be somewhat lower than the speaker's AC  impedance.  The link suggests 6 Ω DC resistance for a speaker with 8 Ω impedance.
As far as driving the speaker from an Arduino output pin, all of the likely values of speaker impedance are too low to allow driving it directly.  Dividing the maximum allowed pin current of 40 mA into 5 V gives 125 Ω as the least resistance an Arduino output should ever see.  When I attach a speaker to an Arduino output, I usually put a 200 to 400 Ω resistor in series with it.  For my purposes (eg alert-buzzers) that gives enough volume without overstressing the Arduino.
If you still have the radio, look for a small transformer near the speaker connection.  If the radio has an audio output transformer, it probably will have a few KΩ of resistance in the primary and a low-resistance secondary.  If you attach the primary of that transformer to the Arduino pin you can deliver slightly more power to the speaker, but may need some  clipping diodes or flyback diodes in the circuit to prevent damage from overvoltages.

Indeed, and if you put 250 Ω in series, you are protected against a short circuit (as that only lets 20 mA through which is acceptable). Plus what jwpat7 said about a flyback diode. Alternatively drive the speaker from a small transistor which will probably make it louder and also protect the output pin.

What difference does it make anyway? If you are protecting the output pin with a resistor, whether the speaker is 4 Ω or 8 Ω isn't going to make much difference to your choice of current limiting resistor. FWIW I measured a speaker which claims to be 8 Ω and got 7.9 Ω on my meter.

@NickGammon, possibly I missed the context of your second comment.  Anyhow, my phrase  “all of the likely values of speaker impedance are too low to allow driving it directly” and the  200 Ω to 400 Ω range I mentioned are consistent with your “whether the speaker is 4 Ω or 8 Ω isn't going to make much difference to your choice of current limiting resistor”.

Yes, I think we are in agreement. :)

To clarify, my comment was not aimed at you. It was aimed at the OP. Why does it matter what the impedance is?

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


text:
Attiny88 problem with LEDs and voltage
I have the following problem and wonder if anyone may have some inside into what may be happening.
I have an array of 20 leds that i manage to multiplex using the attiny88 using only 9 pins (4 columns by 5 rows). At any given time only one led is on. The different leds are activated with a pushbutton. Initially, i used five transistors with a 1k resistor to turn on and off the rows of the led array.
Everything worked like a charm even at voltages as low as 2.5 vol. I then decided to remove the transistors to free-up some space in my pcb. Now the circuit works well at voltages above four but at 2.5v it makes leds to turn on randomly, when pressing the pushbutton.
I presume this behavior is because the one led is taking to much current, but i wonder why could be the case if the chip is only driving one led at a time. Also keep in mind that the circuit works very well at 4vol.
Any clue about this and how could i fix it? I like the idea of not using the transistors.

Schematics please

Do you have the required current limiting resistors? If yes, where in the circuit are they? What value are they? A schematic is an invaluable resource for diagnosing your problem - without it we cannot have a hope in working out what is happening.

driving one led at a time. Are you sure you aren't lighting 4 leds at a time (one entire row).

Iwill have the schematic tomorrow. One thing i read is that some pins that do  no have pwm

I will have the schematics tomorrow. One thing i read is that maybe some pins without pwm may turn high at low voltages. Testing this is complicated for me as it is some massive rewiring. Any thoghts on this?


text:
Function that returns a Structure
I want to create a structure called CarSpeed it has 4 int FR,FL,BR,BL (FrontRight,..) ; and i would like to create a function that returns this structure :
ActualSpeed Readspeed(void)
{
   code to read the speed of the car(already done)
}

Can someone help me define a function that returns this structure  ? only the way how I should define it, the usual C way doesnt work :
typedefstruct CarSpeed{...}

and then
CarSpeed ActualSpeed;
ActualSpeed Readspeed(void){.. }

Since you're (probably) using a C++ compiler, it's usually easier to declare structures like this:
struct CarSpeed
{
    int fr, fl, br, bl;
};

(Note that there's no need for typedef.)
You can then return an instance of it directly from your function:
CarSpeed ReadSpeed()
{
    CarSpeed data;

    data.fr = ...;
    data.fl = ...;
    data.br = ...;
    data.bl = ...;

    return data;
}

You can call it from another function like this:
CarSpeed speed = ReadSpeed();

That will copy the contents of the structure into an object called speed. In this example, it's an 8 byte structure so it's a non-trivial copy. That shouldn't be a big problem unless you're calling it very frequently though.
As noted in another answer, using a pointer (or a reference) can be more efficient if necessary.

Thx, but I get this error :
nMotSet-Final:12: error: 'CarSpeed' does not name a type , maybe i should include the variable creation part in a .h file ?

If you mean the struct declaration, then it's essential to put that in a header file if you intend to call ReadSpeed() from a different file.

I would recommend to use pointers, it's faster and has the same result.
Something like this (disclaimer - I did not compile it):
typedef struct {
   int a;
   int b;
} pair;

int init_pair(pair *ptr) {
   if (!ptr)
      return -1;
   ptr->a = 6;
   ptr->b = 9;
   return 0;
}

int do_something() {
   pair mypair;
   return init_pair(&mypair);
}


text:
Send and Receive with ESP8266 and arduino
Hi i would like to implement a sensor and control system for my home. Basically, i would like to send and receive data to my arduino uno using esp8266. I am able program the esp8266 using at commands to send http request to my server. How can i make my server send commands to my arduino uno using esp8266?

Do you want your "server" to send instructions direct to the esp8266 (esp8266 is a server), or do you want your esp8266 to connect to the server, send a request, then the server returns commands as a response (esp8266 is a client)?

Im not using the esp8266 alone, but using the esp8266 chip as a way for me to connect to the internet. I would like the esp8266 to be able to initiate a command to the server and be able to receive commands at any time without sending a command to get the response.

Then you need your esp to run as both a client and server. Open a listening socket and respond to the requests that come in.

Is there a library for socket for esp8266?

No idea. I always program my ESPs directly in C.


text:
Can a WiFi enabled Arduino make a HTTPS request to my Web Server?
I need my Arduino to connect to my web server through HTTPS, can the Arduino handle it?
It only has to act as a client.

Please state which Arduino. There are quite a few different ones.

I was just checking if it was possible to do some secure cloud connected sensors with the cheap non Linux Arduinos.

It sounds like a better way to do it would be to have a PHP script act as handoff server (maybe protected by originating IP address) to access the HTTPS site and provide the data over a less processor-intensive protocol.
How to get HTTPS on Arduino?
However, another answer suggests that we are working towards a solution to your issue, but it's not quite there yet (~12 seconds to encrypt a packet).
https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/


text:
How do I set the motor state to "HIGH" at the beginning of this sketch?
My intent with this sketch is to have motors run for one minute, then stand by for 18 minutes. In practice, the sketch starts the motor state at "low" for the OffTime interval, then goes to the OnTime interval and loops. The desired result is exactly the opposite: the "high" interval first, followed by the "low". I have tried setting the motorState to "HIGH" in the constructor and played with the order of the IF statements to no avail.
I would appreciate any insight into this problem, as well as an intuition for the practical use of millis(). I need a solution which doesn't use delay but am having trouble wrapping my head around the logic of millis() as used. (I adapted this code from a tutorial.)
class LifeTest
{
  // Class member variables initialized at startup
  int motorPin;
  long OnTime;
  long OffTime;
  // These maintain the current state
  int motorState;                               // Used to set the motor.
  unsigned long previousMillis;                 // Stores last time motor was updated.

  public:
  LifeTest(int pin, long on, long off)
  {
    motorPin = pin;
    pinMode(motorPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    motorState = LOW;
    previousMillis = 0;
  }

  void Update()
  {
    unsigned long currentMillis = millis();     // Check to see if it's time to change the motor state.
    if((motorState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
    motorState = LOW;                         // Turn off motor.
    previousMillis = currentMillis;           // Remember the time.
    digitalWrite(motorPin, motorState);       // Update the motors.
    }
    else if((motorState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
    motorState = HIGH;                        // Turn on motor.
    previousMillis = currentMillis;           // Remember the time.
    digitalWrite(motorPin, motorState);       // Update the motors.
    }
  }
};

LifeTest motor1(50, 60000, 1080000);
LifeTest motor2(51, 60000, 1080000);
LifeTest motor3(52, 60000, 1080000);
LifeTest motor4(53, 60000, 1080000);

void setup()
{
}

void loop()
{
  motor1.Update();
  motor2.Update();
  motor3.Update();
  motor4.Update();
}

I would appreciate any insight into this problem, as well as an intuition for the practical use of millis().

I have a lengthy tutorial about this at How to do multiple things at once ... like cook bacon and eggs.
However as this site frowns upon link-only answers (the link might go down) I'll try to explain as well, here.
millis() is like having a wristwatch. You glance at it from time to time to see if it is time to do something, like catch a bus to work, put the dinner on, take the cake out of the oven, that sort of thing.
If you delay() all the time, you can only do one thing at a time. For example, if your cake takes 30 minutes to cook, and you do this:
PutCakeInOven ();
delay (30UL * 60 * 1000);  // delay 30 minutes
TakeCakeOutOfOven ();

This is fine, but you aren't also cooking some eggs at the same time, or doing the dishes, right?
With millis() you can do lots of things! Win-win! The basic technique is to note the time when you started, and then when time is up, you do whatever-it-is you need to do. Like this:
unsigned long BakeStartTime;
const unsigned long CookingTime = 30UL * 60 * 1000;  // 30 minutes
bool CakeInOven = false;

void setup ()
  {
  PutCakeInOven ();
  BakeStartTime = millis ();  // when the cake went into the oven
  CakeInOven = true;
  }

void loop ()
  {
  if (CakeInOven && (millis () - BakeStartTime >= CookingTime))
    {
    TakeCakeOutOfOven ();
    CakeInOven = false;
    }

  // do a whole lot of other stuff, like cooking some eggs

  }

You can expand this technique to do dozens of things "at once".

just change the constructor to
  LifeTest(int pin, long on, long off)
  {
    motorPin = pin;
    OnTime = on;
    OffTime = off;

    previousMillis = 0;

    motorState = HIGH;
    pinMode(motorPin, OUTPUT);
    digitalWrite(motorPin, motorState);
  }


text:
Need help in modifying the design
I am planning to do a project on Sequential tilt motion lock using Arduino uno and accelerometer. I would like to present the accelerometer within a rotatable object. So what other components do i have to add to be able to do it i.e.. for wireless transmission of data from the object(that has the acc. meter) to the Uno board.

Seems to do the trick already. What else do you need?

@Gerben i would like to perform the task wirelessly..

So then add a wireless serial module.

@IgnacioVazquez-Abrams i am a absolute beginner to electronics and stuff. So if you can suggest a component that will be good for me to purchase and try and do the project.

@SomasundharamSampath There are hundreds of different modules and frequencies available. With what do you wish to control it?

The basic idea of the project is to have a unconventional key to doors.. So i thought of fixing the arduino board to the door and have a portable object within which the acc. meter will be placed... So to give signal to the arduino board from acc. meter i require a wireless module (range:less than 30 meters is sufficient i guess)

If you do a google search for "arduino wireless serial" you'll get several results. Plugging them into the arduino should be trivial. Most suppliers (other than ebay) will also have examples for you to reference where it comes to coding your project to use the module.
You should also be aware that you will usually need a transceiver, and a receiver.
You might take a look into the XBEE solutions, as they appear to be popular.

authors: Тарас Павлик


text:
What are the basics in writing a program in Arduino?
I am an undergrad in ICE. I was searching for ideas to do mini projects on and found this Arduino boards and programs. So actually what are the basics to develop our own gadgets? Any guidelines...?

I suggest you Google for some ideas, blogs, tutorials, etc. Your question is basically asking us to summarize hundreds, if not thousands, of web pages.

There are some excellent books available as well as videos and articles on the Internet which will walk you through basic projects.  The most common method of programming is to use the free Arduino IDE which will talk to the board from your Mac or PC.  You can run the board straight from the USB port's power, or from an external source if you need it to be portable.
The programming language is very similar to C.  The program structure is basically a setup portion and then a continuous main loop that runs until the board is powered off.
If you want to experiment without actually purchasing one, there are some emulators available which will let you build entire project on a virtual breadboard before buying any actual components.  Fritzing is a great board planner that you can install, or if you would rather, you can use 123D Circuits from your web browser which will let you edit and simulated the circuits.
Basic knowledge of electrical circuits will be helpful for getting started, and is a great asset when designing larger projects.


text:
Underwater positioning system (swimming pool)
I'm making a few experiments with a quite simple rover car I made using Arduino UNO and a few spare parts. Just for the heck of it I made it waterproof and now I want to toss it in my pool to make some underwater exploration. Maybe I'll fit some scrubers under it to make it easer to clean the floor.
My problem is: my rover navigates on its own, avoiding walls and objects using an ultrasonic sensor. But underwater the speed of sound goes up, and different qualities of water make it even harder for this system to work. Sometimes the pool is full of particles, and the scruber will probably worse the water quality around the robot.
My question is: what kind of system is better to navigate underwater, simply avoiding walls? The current behavor (on dry ground) is to turn to the right and go on when it finds a wall, I would like to keep this behavior, but underwater. As it's a simple toy, I'm hardly willing to spend a hundred bucks on a fancy laser proximity sensor, neither I need to map the entire pool with a single pulse, it should be a simple wall avoiding system.
Thank you!

bumberswitches (i.e. limit switch with long stiff wire attached).

Infrasound could work. Same as ultrasound but low frequency audio instead.

Infrasound works well on large distances. I doubt it's of any use inside a regular pool.

Try it out with the ultrasonic system.  Other than the speed issue (which will result in things appearing closer than they are) the ultrasonic system should work fine in the water, even with floating particles.

@IgorStoppa You don't have an Olympic size pool in your garden?!

@Majenko: I suppose with Olympic you refer to the real thing, as in "swimming place near Mount Olympus", colloquially known as Aegean Sea. Because that's what would probably make the use of infrasounds possible. No, I don't have that in my garden.

@IgorStoppa Imagine the pool parties you could have...

@IgorStoppa Also, just because infrasound has a large range doesn't mean it's useless for shorter range. It doesn't travel any faster than ultrasound, it can just travel much much further. It still echoes off close things. The only thing you have to watch is that your sound production period is shorter than the period of your shortest desired echo, and with infrasound that is limited by the wavelength of you want to produce at least one full cycle of the audio signal. So you choose your frequency to suit. You may well end up with a frequency that isn't strictly infrasound, but sure isn't ....

... ultrasound. Low audible frequencies, for instance . The theory of operation is just the same

Have a look at this, form the Robotics site, perhaps: http://robotics.stackexchange.com/questions/7564/how-to-localise-a-underwater-robot

How about a tilt switch?  The bottom corners of a pool should allow the car to ride up the wall a little, when it tilts past 5 or 10 degrees, turn it left.....


text:
How to differentiate between 2 Micros on Linux
I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine.  I need them to have unique serial ports.  Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible).
This is the serial number that I get for both:
$ udevadm info -a -p  $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial
  ATTRS{serial}=="0000:00:14.0"

Is there any way to manually set the serial number on an Arduino Micro?  Or is there any other unique identifying properties I can use for udev rules?
Typically, I do something like this in my /etc/udev/rules.d/99-usb-serial.rules file:
SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice"

Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.

The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch.  The VID and PID are tied to the board, and the serial number is always the same regardless of which board.
So no matter which board you program it will get the same details as any other board of the same kind.
There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: USB_VID and USB_PID.
So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board.  You can then differentiate the two boards in udev using the VID/PID combination.
Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.

That "0000:00:14.0" isn't the serial number for the Arduino: udevadm is printing info for more than one device, and that's for the USB controller chip.
Arduinos built on the ATMEGA32U4 don't get a serial number: I have some Leonardos giving me the same problem you're having. When the bootloader was originally designed, the programmer didn't have it report one. I found a modified bootloader that does, but I haven't tried it yet: http://forum.arduino.cc/index.php?topic=503703.0
Genuine Arduinos with an FTDI chip report unique serial numbers. Some of the knock-offs either don't set it in the chip, or may set it to some non-unique number(skipping that step to save a  few cents of manufacturing cost). Ones that use a 16U2 chip for the USB interface (like the Uno R3) are supposed to get a unique serial number. The Chinese ones I just bought did, but it's possible that other makers of them are cutting corners like some users of FTDI chips do.
Arduinos that use the Chinese CH340 USB chip also don't report a serial number: the chip doesn't support it. I think that's also true for the CP2102, but I'm not certain.
You may be able to fix the problem with that modified bootloader (I hope so: I have half-a-dozen Leonardos, and it's a hassle anytime I have more than one connected simultaneously. Fortunately, I don't normally use them as "PC peripherals"). Or you could buy another of the "tiny" Arduinos with a 328P that uses a USB-to-serial chip, and base the udev rules on VID and PID to distinguish them.

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


text:
String operators
I have a section of code that I am unsure of what it is doing.
static int bufindw = 0;
static char buffer[4][96];
static char *strchr_pointer;
int result;

result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The part where I don't understand what is happening is strchr_pointer - buffer[bufindw] + 1. strchr_pointer and buffer[bufindw] will be strings. It gives the result I expect it to give because I know in the end it needs the correct index value in buffer[][] and in addition the number 1 is being added to it as well. How can a string minus a string?

Those are pointers,not strings.

Let's break it down logically for you.
You have 4 strings, each capable of containing 96 characters:
static char buffer[4][96];

That is a block of RAM that covers 4*96=384 bytes.  Let's say that block of ram starts at address 0x100.
result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The phrase buffer[x] returns the address of the string number x in your array of strings.  It's the same as &buffer[x][0] - the address of the first character in string x.
You also have a pointer strchr_pointer which contains something - what that is I don't know because you haven't told us.  Chances are it's the result of a strchr() call, which:

returns a pointer to the first occurrence of the character c in the string s.

So you have looked for a character in a string and found that it's at a specific address.  Let's say that's address 0x111 for the sake of argument.
Ok, so if we take bufindw as 0 for the first string in your array, and work from the inside out, we have:

buffer[bufindw] = 0x100
strchr_pointer = 0x111

strchr_pointer - buffer[bufindw] = 0x111 - 0x100 = 0x11
strchr_pointer - buffer[bufindw] + 1 = 0x100 - 0x111 + 1 = 0x12

Replace that into the function's parameters:

&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1] = &buffer[bufindw][0x12]

So you have the address of the 0x12'th (18th) character (or character number 16 since they count from 0 not 1), which is address 0x112.
That address is then passed to strtod() to convert it into a double-precision number:
    strtod(0x112, NULL);
That value is then cast to an integer:
(int)strtod(0x112, NULL);

So the decimal portion is discarded (not rounded, chopped off).
Say your string contains: "This is the value:23.83589743" and is located at 0x100.
You use strchr() to find the first occurrence of ':', and it finds it at address 0x111, which is the 18th character of the string, so 0x100 + 17 = 256 + 17 = 273 = 0x111.  You subtract the start of the string and add one to it, so you end up with 18, which is the start of the numeric value (the 18th character).  The string from that point on contains "23.83589743".  That is then passed to strtod() and cast to an integer, and so is truncated to 23.
It's not surprising you're confused, the whole thing can be re-written much simpler:
strchr_pointer = strchr(buffer[bufdindw], ':');
result = (int)strtod(strchr_pointer, NULL);

All that manipulating of the buffer address is like doing "x = 6 + y - 3 + 4 - 7" - completely pointless, since you might just as well write "x = y".

And yes, strchr_pointer is the result of a strchr() call.


text:
Connecting a switch and a MOSFET to an Arduino?
I have an LED strip that I am trying to turn on with a magnetic switch when a door opens. I want the LEDs to fade on when I open the door and fade off when I close it, which is where the Arduino comes in. I am using PWM for the fading. I can get each component to work separately. The fading LEDs work with the MOSFET without the switch. I tested the switch with serial output on the Arduino and it works fading a single LED without the MOSFET.
I am using:

Arduino Uno R3
Magnetic Switch
N-Channel MOSFET IRLB3034
5 Meter White LED Strip
12VDC 30W Power Supply
10k Ohm Resistors

My setup looks like this:

Schematic:

Code (if it helps):
const int buttonPin = 2;     // the number of the switch pin
const int ledPin =  9;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the switch status
int brightness = 0;
int fadeAmount = 5;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the switch value:
  buttonState = digitalRead(buttonPin);

  // check if the switch is ON.
  // if it is, the buttonState is LOW:
  if (buttonState == LOW) {
    // fade LED on:
    analogWrite(ledPin, brightness);
    if (brightness < 255) {
      brightness = brightness + fadeAmount;
    }
  }
  else {
    // fade LED off:
    analogWrite(ledPin, brightness);
    if (brightness > 0) {
      brightness = brightness - fadeAmount;
    }
  }
  delay(30);
}

I have a feeling the problem is with the common ground on the MOSFET and the switch. Any solutions/suggestions are appreciated.

are you able to turn on the FET via Pin D9 continuously on? With out PWM.. When D9 is high can you pls measure the voltage across drain and source of the NMOSFET? Check the voltage at D2 when the switch is closed and opened. Measure voltage at D9 when the Output of D9 pin is high. can you share the details of 5 meter LED strip? How are you powering on the Arduino? I have a feeling that issue is with the 5 meter strip LED...

I would expect R2, near the MOSFET, in the order of 100 ohm. You'll drive it hot otherwise. Also change the minimum and maximum tests from 255 resp. 0 to 250 and 5.

You do not say what problem you are having. What does it DO? | LED strip will power up over a voltage range near 12V. ie is probably off at about 9V and on at 12V. So IF voltage on strip is analog due to any filtering it will power on over end part of PWM range. If circuit IS as shown LED strip should modulate on and off at PWM frequency. This SHOULD work. Circuit as shown looks OK and code seems OK so you may6 not be doing what you think you are. Check everything. | And, what does it n fact do?

@As Jippie says- MOSFET gate resistor can be small 100 Ohms or even 10 Ohms OK. 10k as shown is probably not cause of problems but is too large.

THat's an AWESOME FET. Data sheet here

The microcontroller output is too weak to drive the gate of the IRLB3034 properly at PWM speeds (>=1 kHz). Without a resistor you'll have overcurrent at the PWM output, and with one you'll heat up the MOSFET. I solved it in a couple of my projects by building an NPN-PNP totem pole using a 2n2222 and a 2N3904 between the micro and the gate. I put one <1kΩ base resistor between the PWM pin and the totem pole, and a couple of ~10Ω resistors between each of the BJT emitters and the MOSFET gate. Works like a charm.

I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?

simulate this circuit – Schematic created using CircuitLab
How to make the diagram a bit smaller?

He's driving a 12V rated strip with internal resistors - no external LED r needed. He's using PWM because he wants a digital solution and not an analog one.

@lalamer To scale the diagrams on ESE you need to make them wider, I do this by placing a dot/segment/text to the left and/or right so it shrinks the whole diagram, works well.

@RussellMcMahon yes you are right, this is a led strip and there is a internal resistor. I have updated my answer. Thank you for committing.

There is no need for the 10KOhm. MOSFETs are voltage controlled devices unlike transistors which need controlled current. I think your problem might be in debouncing of switch. You are probably getting some false positives which might be making your software go awry.
I recommend having a small debouncing routine. For eg - only if you find 3 successive positives will the switch press be termed a true positive or so.

When switch is seen as active it does one action and then delays 30 mS before retesting so he effectively has a 30 mS debounce.

It is a good practice to have a resistor in series with gate to limit the inrush current. Remember the gate of MOSFET acts like a capacitor and needs to be charged/discharged.

To achieve this u should connect the gate of the MOSFET to the gnd(in case of NMOS).This will discharge the MOSFET gate capacitance quickly. Also, you should never leave a gate floating as it is susceptible to noise and can switch on causing a lot of damage. Always pull down the NMOS gate.


text:
What changed in the new Due?
I recently purchased a batch of Due boards and find that they are cosmetically different. After attaching the Atmel-ICE and reading the firmware from both processors, I find that the firmware is different. The green masked one had a sticker indicating a new IDE should be downloaded from arduino.
The back of the board shows silkscreen changes to the logo (DUE in an oval rather than rectangle) but both boards say BOARD MODEL DUE R3-E. The traces appear the same, the placement of parts appears the same, and other than different colored headers the parts are similar. The main processor has the same part number, but distinctly different markings. Internally the processors report the same device signature and revision.
What has changed in the firmware? Are there other changes I've missed? Other than needing an even newer IDE are there changes that will affect my sketches?
If I load the older firmware onto the newer Due processors, should it operate the same, allowing use of the old IDE, and in case my sketches do face a problem with the new version?

I obtained these from digikey, and both boards came in the same batch. They were packaged according to arduino's usual packaging with stickers, etc. I have no reason to believe I've received parts made by someone else.

It may have something to do with the fact that the arduino is no longer being made it Italy. The US ones are made by adafruit and the china ones by seeedstudio.

@evolutionizer Both are marked quite clearly in the back silkscreen MADE IN ITALY with the country's outline.

But looking carefully I see the 'new' one has ARDUINO.ORG and the other WWW.ARDUINO.CC So perhaps this is fallout from the founder breakup.  Which is which, though?  And why change the firmware?

I was right and wrong :)  The one you have is made by arduino.org who was already manufacturing the boards. I believe they have changed the silkscreen to differentiate. I believe Seeed Studio and Adafruit havent started selling it yet. As for the firmware, there will be no difference as they all still primarily maintained by arduino.cc

I believe the firmware changes are an attempt to lock out non-arduino.org boards from the arduino.org IDE, or the arduino.org boards from the arduino.cc IDE - one or the other.  Either way it's all because of the toys that are being thrown out of various Italian cots.

The 'new' board with green soldermask and the lighter headers is made by arduino.org.  The old one was probably made by the same company, but prior to the split in the founders.
Right now there is arduino.cc (the original website) and arduino.org (the website set up by the company that split from Arduino).  There is a lot of different perspectives about who really owns Arduino and I won't attempt to weigh in here.
The changes in firmware are still unknown.  It's likely that they are simple strings or response changes so the boards can be differentiated in software.  The new IDE is in alpha, and is yet another attempt to differentiate between the two Arduino groups.  I haven't attempted to program either with either group's IDE, but if I do I'll update this answer with the results.
At least there's a way to visually identify the difference once received - wish they had given them different part numbers so Digikey wouldn't have sent me a mixture...

Since the whole thing is a mess and there is only arduino.org still distributing the arduino, this is what you will be getting irrespective of where you order from.

it also looks like arduno.cc is only producing 2 boards https://www.arduino.cc/en/Main/GenuinoBrand


text:
Is serial modem routine written on the Arduino Leonardo bootloader?
I'm starting with Leonardo and I'm a bit confuse about the serial modem function. As you know on boot the Leonardo for the first 8 seconds wait for a program on the USB port and then it goes in serial modem mode while my program runs.
I'm designing a consumer product (open source) and I will like to make some modifications to my board in order to make it more friendly:

On boot it has to go into programming mode only if a jumper is set. Otherwise it goes directly into serial modem.
I need to change to modem name, instead of:

Have the operating system pickup the serial modem with no drivers request.

For 1 and 2, is it possible? should I try to modify Caterina or it will be easier to work with Optiboot? Number 3 works already in linux distributions, but in Windows some pcs ask for drivers are, and even worse, some windows 64bits + usb3 requires some minors hacks to pick up the Leonardo serial drivers, is it possible to improve? Ideally I want the board to be connected to a PC/Mac/Linux and get configured as a serial com with no user intervention.
I think this are questions that every person trying to create a consumer product with Arduino needs to answer before producing the actual product. So, and resources, references and where to start guides will help me and other people in the community.

Sounds like you need to be using the stock Atmel '32U4 firmware instead of any Arduino bootloader. Also, here's USB in a Nutshell so that you can handle items 2 and 3.


text:
PPM from remote control is very noisy

I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. But even this still doesn't seem to be a good way prevent the noise that is occurring when using my Remote. Is there any way to fix this?
Here is the code from the smoothing project. (Although i feel it's not really necessary to add it here, but here it is anyways.)
My code is using the PPMrcIn library. An int is created and then using if statements I make an object do work. My problem is that i have a very small window for work.
My values are between 50 and 200
Where 140 is the preferred midpoint i'd like to work with.
This is my somewhat cryptic number line.
140 is in the middle. Where my window of stability is between 130 and 150
and values below 100 and above 180 are where the robot does some work.

50 ---x---<100-----130--<140>--150----180>---x---200
  /*

    Smoothing

    Reads repeatedly from an analog input, calculating a running average
    and printing it to the computer.  Keeps ten readings in an array and
    continually averages them.

    The circuit:
      * Analog sensor (potentiometer will do) attached to analog input 0

    Created 22 April 2007
    By David A. Mellis  <dam@mellis.org>
    modified 9 Apr 2012
    by Tom Igoe
    http://www.arduino.cc/en/Tutorial/Smoothing

    This example code is in the public domain.

  */

  // Define the number of samples to keep track of.  The higher the number,
  // the more the readings will be smoothed, but the slower the output will
  // respond to the input.  Using a constant rather than a normal variable lets
  // use this value to determine the size of the readings array.
  const int numReadings = 10;

  int readings[numReadings];      // the readings from the analog input
  int index = 0;                  // the index of the current reading
  int total = 0;                  // the running total
  int average = 0;                // the average

  int inputPin = A0;

  void setup()
  {
    // initialize serial communication with computer:
    Serial.begin(9600);
    // initialize all the readings to 0:
    for (int thisReading = 0; thisReading < numReadings; thisReading++)
      readings[thisReading] = 0;
  }

  void loop() {
    // subtract the last reading:
    total= total - readings[index];
    // read from the sensor:
    readings[index] = analogRead(inputPin);
    // add the reading to the total:
    total= total + readings[index];
    // advance to the next position in the array:
    index = index + 1;

    // if we're at the end of the array...
    if (index >= numReadings)
      // ...wrap around to the beginning:
      index = 0;

    // calculate the average:
    average = total / numReadings;
    // send it to the computer as ASCII digits
    Serial.println(average);
    delay(1);        // delay in between reads for stability
  }

also link to my code in github
https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino
Since this is being asked. Let me clarify on this black voodoo thing called a PPM.
Many RC Transmitters and Receivers provide access to the PPM Stream, this is a single stream of pulses which includes the information for all of the receiver channels in a single connection.
The stream is made up of a series of short pulses, the first pulse is the start marker. The time between the start marker and the start of the next pulse defines the pulse length for channel one. The time to the next pulse defines the pulse length for channel 2 and so on. The end of the pulse stream is marked by a gap know as the frame space. This gap indicates that there are no more channels to receive and the next pulse will be the start of a new frame. Each frame contains the pulse widths for all of your receiver channels.
Note - unlike servo signals, in a PPM Stream it is the gaps between pulses that defines the pulse width for a channel, not the duration of the pulse itself which can be very short.
-http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html
As discussed above. My PPM signal is highly varied. I want to be able to just get a solid 140. However, the signal will jump irratically between 135 and 142 for reasons I do not completely understand. In an attempt to clear this fuzziness I tried to go for smoothing.

I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. Could you clarify that somewhat? PPM - is that pulses per minute? Why would you want to smooth it out? a good way prevent the noise that is occurring when using my Remote - what remote?

Sorry, Similar to PWM, but instead Pulse Position Modulation. It's a remote remote controller. I'd want it to smooth it out because i'm getting values that are not within my target range.

Perhaps add a link to what PPM is? And explain it as well? this still doesn't seem to be a good way prevent the noise that is occurring - what noise? Do you mean variations? Or actual noise that is completely different from what you are expecting?

The question has been edited

readings[index] = analogRead(inputPin); - why are you doing an analogRead? That's quite slow (104 µs). Why not digitalRead()? Personally if I was going for highly-accurate readings I would be using an interrupt to quickly note the time the next pulse arrives. delay in between reads for stability - delays here will add to your problems. I think the whole things needs a rework.

First, I want to thank you for making this post. I have a few remote-controlled cars/boats/helicopters, and I've often wondered how the remote control works. :)

To answer your question - and because I was too lazy to work out how to connect to an actual controller - I made a "remote simulator" like this:
// PPM generator

const byte SIGNAL_PIN = 3;
const int SIGNAL_COUNT = 6;
const unsigned long PULSE_WIDTH = 300;  // µs
const unsigned long BLANK_TIME = 25;    // ms
const int widths [SIGNAL_COUNT] = { 600, 2000, 1000, 1500, 2200, 2400 };

void setup ()
  {
  pinMode (SIGNAL_PIN, OUTPUT);
  }  // end of setup

void loop ()
  {
  delay (BLANK_TIME);
  digitalWrite (SIGNAL_PIN, HIGH);  // start
  delayMicroseconds (PULSE_WIDTH);
  digitalWrite (SIGNAL_PIN, LOW);   // end of start pulse

  for (byte i = 0; i < SIGNAL_COUNT; i++)
    {
    delayMicroseconds (widths [i] - PULSE_WIDTH);
    digitalWrite (SIGNAL_PIN, HIGH);  // start of pulse
    delayMicroseconds (PULSE_WIDTH);
    digitalWrite (SIGNAL_PIN, LOW);   // end of pulse
    }  // end of for loop

  delay (1000);
  }  // end of loop

This is intended to generate a series of pulses (six in this case) which might be generated by some fancy toy fun device.

Output from it:

As you can see from the cursor, it is doing what it is bid. The pulse width shown by the scope cursor is indeed 2000 µs, as per the table of widths.
Note: Output on pin 3 on the Uno.

Now we need a decoder. So let's use interrupts:
const byte SIGNAL_PIN = 2;
const int SIGNAL_COUNT = 6;

volatile unsigned long widths [SIGNAL_COUNT + 1];
volatile byte count;

unsigned long lastPulse;

// ISR
void gotPulse ()
  {
  unsigned long now = micros ();

  // a long gap means we start again
  if ((now - lastPulse) >= 25000)
    count = 0;

  lastPulse = now;
  if (count >= (SIGNAL_COUNT + 1))
    return;

  widths [count++] = now;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (0, gotPulse, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  }  // end of setup

void loop ()
  {
  if (count >= SIGNAL_COUNT)
    {
    Serial.println (F("Got sequence."));
    for (int i = 1; i < SIGNAL_COUNT + 1; i++)
      {
      Serial.print ("Channel ");
      Serial.print (i);
      Serial.print (" = ");
      Serial.println (widths [i] - widths [i - 1]);
      }
    count = 0;
    }

  }  // end of loop

This uses an interrupt (on pin 2 on the Uno) on the rising edge to detect the start of the pulses. It stores them, and then works out their widths later.

Results?
Got sequence.
Channel 1 = 612
Channel 2 = 2020
Channel 3 = 1016
Channel 4 = 1512
Channel 5 = 2220
Channel 6 = 2428
Got sequence.
Channel 1 = 612
Channel 2 = 2020
Channel 3 = 1016
Channel 4 = 1512
Channel 5 = 2220
Channel 6 = 2424
Got sequence.
Channel 1 = 616
Channel 2 = 2020
Channel 3 = 1012
Channel 4 = 1516
Channel 5 = 2220
Channel 6 = 2424
Got sequence.
Channel 1 = 616
Channel 2 = 2020
Channel 3 = 1012
Channel 4 = 1516
Channel 5 = 2216
Channel 6 = 2432

Highly consistent results, with a small error factor of around 16 µs compared to 600, 2000, 1000, 1500, 2200, 2400

In case it isn't clear, this test required two Unos. One to generate the pulses and a second one to decode them:

The one with the USB cable is the decoder, which writes to the serial port. The other one is powered by 5V/Gnd from the first one, and the white wire is the data with the pulses.


text:
Split a string as 2x16 for LCD
How do I split a string into two based on it's length to display on a 2x16 LCD?
I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?
Thanks

String::Substring does take a start and an end value. So you can do something like this:
String s1 = longtext.substring(0,15);
String s2 = longtext.substring(16,31);

That's what String::substring() is for. Simply take the first 16 characters and the characters from 16 to 32, and output them.

But,what about the rest of the string? I need 2 x 16 of the 32. Substring only provides one part right?

Use it as many times as you need in order to get all desired substrings.


text:
How to sense mobile signal coming to a room using arduino uno
How to make arduino sense mobile signal coming into a room and display the calling number on an LCD screen

So is not possible to use arduino to block a specific mobile number coming to a room before it gets to the phone and allowing  others ?

Use the configurations options of your phone to blacklist that specific number.

What you can do, if you really want your phone to change behaviour inside a certain room, is to use NFC tags, assuming the phone has an NFC reader: for example attach an NFC sticker on your nightstand, where you would usually put your phone when you sleep, and configure your phone to change profile to "siesta-time" when it touches said tag.
It's equally easy to make it go back to "Home" or "default" or whatever you like, when it unpairs from the NFC tag.

You can't.
Mobile phone signals don't respect artificial boundaries like a room's walls.  You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".
And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".
What you could do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.

So is not possible to use arduino to block a specific mobile number coming to a room before it gets to the phone and allowing others ?

Nope. You could jam all the signals in the local area but a) you'd be breaking the law, and b) you'd have people very pi**ed off coming around and smacking you up with baseball bats.


text:
Arduino, lcd 16x2 and UTP cable shows gibberish text?
I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.
I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen).
I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.
Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?
Thanks!

What is the protocol you are using? Which wires are you using for what function?

possible duplicate of 2,5m cable too long for LCD connected to Arduino UNO?

Please try using a multimeter and check the voltage in the + and - wires. Also try wrapping the wires in tinfoil, it should reduce the interference.

Until we know what protocol you are using (I2C? SPI Shift registers? UART?) and which pins you are using on the UTP cable (not all pins are equal - it's the way the wire is made) we can't make any serious recommendations.  There are specific things you can do in specific circumstances (decrease pullup resistance for I2C, use the pairs of the UTP properly as pairs with signal/ground, or even generate an LVDS for maximum performance).  All depend though on what you are doing and using now.

This might be of some help assuming that we are talking about I2C wiring; http://electronics.stackexchange.com/questions/106265/maximum-i2c-bus-length

Do you have access to a scope of some sort? It would also help us help you if you could add a link to the display you're using (or at least name it specifically).

Is the cable shielded?
Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?
What is the impedance of your total length of cable?
These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test)
a hardware limitation (Too much resistance for accurate data travel)
Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.


text:
Does the arduino board have to be always physically connected to the electronic device you are running?
If I have a basic electronic board with some LEDs and sound fx and I want to program them (I'm a beginner, learning about arduino), does the arduino board always have to be connected to the actual electronic board I'm running or is there a way to "upload" the programming to the circuit board?

If the "basic electronic board" is programmable, then yes, you can upload a program to it.
In general, though, "some LEDs" and similar devices are not programmable, and without something to drive them (i.e., the Arduino) they won't do anything at all.  The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing.  It is the brain of the operation.  Remove the brain from someone and you'll find their body no longer functions.

And Arduino UNO is basically a ATMega328 chip (with some extras) on a circuit board. So if you add an ATMega328 to your own circuitboard, you don't need an Arduino Uno.

If the question is "Can I program the Arduino without anything else connected to it?", then yes, you can program it with out the sound and light board connected. But the program will start running shortly after the upload finishes.
If some devices were connected to it and some were not, it's possible the program won't function properly at that point (and obviously the not-connected devices won't function at all!), so you should make sure the Arduino can't or won't try to do anything to the few connected ones that might be harmful when some others are not connected, in case that is possible (this would be an unusual, but plausible, situation).


text:
Cheap LCD with Few Pins
I am working on a project with an Arduino Nano that includes a keypad, screen, and the NRF4001 transceiver. The keypad requires 7 digital pins to operate, the wireless transceiver uses pins D9 - D13 with the RF24 library I am using. Now, that leaves me with 1 Digital Pin left for a screen unless there is an I2C screen I could use.
That would be easy enough to find except that I have some limitations. If at all possible I would like the screen to be under 5 dollars and about the size of a Nokia 5110. The Nokia uses to many pins and does not tolerate 5v logic levels I've heard. An OLED 0.96 inch is only a 4 bucks and is I2C, but it is too small. I could make a board for the keypad that used different values of resistors and one analog pin to detect different buttons but would rather not go that route if there is any easier way to get around this.
Are there any options out there that would suffice my pin, cost and size conditions or am I being too picky?

Has anyone seen a backpack for Nokia's that make them I2c capable for example?  I know its been done with the typical 16x2s.

You can also use the analog pins as regular digital pins. So you have 6 pins left. The Nokia 5110 seems to run fine on 5v, from what I've heard. But you could add a buffer chip to change the voltage levels (example).

How would you do that....use analog as digital?

Ok...I saw how they could be used as inputs 14 - 19 but can they be used as digital outputs too in the same way or do I have to say analogWrite(pin, 1023) to get the same result as a digital HIGH

http://www.avdweb.nl/arduino/hardware-interfacing/nokia-5110-lcd.html This link seems to suggest 3.3v opperation.

Just use pinMode(A3); and digitalWrite(A3, LOW); e.g.. 5v on the 5110 is out of spec, but appears to work with no problem. But use at own risk.

You can use a single analog pin to read an entire keypad.
First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.
A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.
Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F->G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.
You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: http://www.calculator.net/resistor-calculator.html and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.
DO NOT use any resistors under 1kOhm.
Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out * (5.0 / 1023.0) , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.
Then find the numbers exactly in between.
For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.


text:
How to do a software reset on MAX7456?
I messed around with the MAX7456 chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.
The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like this)

Can you clarify: The board used to work, and now -- using the same code -- it doesn't? Or it works for a while, and then not? Or it works with some code but not other code?

@NickGammon Yes, using the same code the board does not work any more.

Well, after powering the chip off it should reset. I don't think sending a software reset would achieve anything more than a power off. It is possible you damaged it, however without more information it is impossible to say.

Your answer seemed to fix the issue. It now works.

The datasheet says:

The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...

Thus, you need to write address / data after selecting the chip.
digitalWrite (SS, LOW);  // select the chip
SPI.transfer (0x00);     // select address 0x00 (Video Mode 0)
SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
digitalWrite (SS, HIGH); // done

According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.
  byte result;

  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    } while (result & bit (1));  // loop while not reset yet

Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?

I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.
  // reset chip
  digitalWrite (SS, LOW);  // select the chip
  SPI.transfer (0x00);     // select address 0x00 (Video Mode 0) - write mode
  SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
  digitalWrite (SS, HIGH); // done

  byte result;
  unsigned int counter = 0;

  // wait for it to become ready, or time-out
  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    if ((result & bit (1)) == 0)
      counter++;     // count times not ready
    } while ((result & bit (1)) && (counter < 1000) );  // loop while not reset yet

  if (counter == 0 || counter >= 1000)
    {
    // chip does not seem to be responding
    }
  else
    {
    // all OK!
    }

This sketch seemed to do the job. The hello world sketch started working (but for obvious reasons the character set is wrong).


text:
Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display
I just got my Arduino Pro Mini and GDEW0154T1 ePaper display (GDEW0154T1 display) and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.
I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?
Thank you for any advice!

You need to build a special driver board.  Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.
The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).
There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.
Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task.  You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it is the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.

Do you know what is component S11304BDL from Figure 7.5(4)? I can't find it anywhere.

@MattheW Any logic level N-channel MOSFET would do the job.

Thank you. Could you please help me once more? I recreated the circuit on the breadboard and I've got two doubts.

Do I connect 3.3V power to both VDDIO and VCI pins?
I look at both Figures 7-5 (2) and 7-5 (4) and I can see that VCI is on both of them. On none it is connected to 3.3V input. As far as I understand, it's connected to capacitor and ground on one side and to power control circuit on second side. Should I place 3.3V in between? Thank you for help!


text:
Hall Effect Current Sensor Wiring
I need help with wiring this current sensor so that I can read the output voltage as an analogue input. - http://www.tamuracorp.com/clientuploads/pdfs/engineeringdocs/L03SXXXD15.pdf
This is how I have it wired right now -
1 - +15v
2 - 15v ground
3 - output to arduino
4 - arduino ground
This seemed simple but reviewing the wiring diagram again I have a hunch that this is not at all how I should be wiring this up.
Thanks

Are you planning to measure AC current?

Have you looked at the "Electrical connection diagram" in the datasheet?

Looking at the datasheet the output is +/- 4 volts, so this is not suitable to connect directly to the Arduino, because the input pin will not tolerate -4 V.
I am no Hall Effect sensor expert, but a quick search on Google showed another potential problem: If you are planning to measure AC current, and you try to sample the output on the Arduino, the reading will average out to zero (half of the time positive, half of the time negative).
What may help - and this is a bit of a guess - is to put a diode in series with the sensor output, oriented so that you only get the positive pulses. That is, the anode connected to the Hall Effect sensor, and the cathode (with the black line) on the Arduino side.
Then you probably want to smooth the voltage so you can read the average voltage with the ADC converter, rather than what it is at a particular millisecond. A low-pass filter will take an average, which you can then read with analogRead.
Something like this:

I made up that circuit driven by a signal generator (8 V peak to peak, i.e. +/- 4 V) and found a 400 mV drop over the diode using a 1N4148 normal diode, and a 160 mV drop using a BAT85 Schottky diode.
With a 3 V peak-to-peak signal the voltage drop with the Schottky diode reduced to 120 mV, so it wasn't totally linear.

As Majenko pointed out, there is a voltage drop over the diode. You can make a Precision Rectifier out of an op-amp and a few other parts, like this:

This avoids the problem of the voltage drop (put this in place of the diode in the earlier circuit).
If the signal is AC then the smoothing circuit I described above will only give you an average voltage, not a peak one. You may want to sample rapidly in order to find the peak values.

Don't forget you would have to compensate for the diode voltage drop.

Good point. You could get a diode with a smallish voltage drop, like a Schottky.

To read the sensor properly you have to convert the output signal into something the Arduino can work with.
At full current the output will swing between +4V and -4V, and over-current will cause that to be nearer +6V to -6V.  The frequency of that swing will be the frequency of the input voltage - so typically 50 or 60Hz.
The Arduino can only read between 0V and 5V, so you will need to convert the provided voltage to fit.
You need to first reduce the voltage by about a half, so it fits into +/- 2V, and then you need to add a 2.5V offset voltage to it so that it swings between 0.5V and 4.5V.
Once you have done that you then need to sample the incoming signal fast enough that you can get the peak values, from which you can then calculate the incoming current.
Often for this kind of thing you would use a simple voltage divider with an offset voltage applied to it, but the output impedance of the sensor (set by RL) is 10KΩ which is around the upper limit for the input impedance of the Arduino's input.  A voltage divider that wouldn't adversely affect the output accuracy would be using resistors in the order of 1MΩ, which would be way too high for the ADC on the Arduino to be able to sample accurately.
So you need to buffer the signal with a high impedance buffer.  That can be achieved most simply with an inverting op-amp circuit with a gain of 0.5.  You want a rail-to-rail op-amp which is capable of running from a single supply voltage.

In this circuit the output current is converted into a voltage by the 10KΩ resistor RL.  It is then AC coupled to the rest of the circuit through C1 which has to be high enough in value as to not reject the frequency you are working with (it acts like a high-pass filter).  R1 and R2 set the gain of 50/100, or 1/2, so the voltage is halved.  R3 and R4 form a voltage divider to provide a VCC/2 offset voltage into the non-inverting input of the op-amp.  This is known as the virtual ground voltage and is the voltage the output of the op-amp will swing around.
The result is the input voltage inverted, halved and off-set by 2.5V, which can be read directly by the Arduino's ADC.
Note the magic word inverted there, though.  The values you read will be upside down.  Anything read above 512 from the ADC will equate to a negative voltage.  Anything read below 512 will be a positive voltage.  So it is necessary to first "invert" the reading, which can simply be done by subtracting it from 1023.
Then it's just a matter of sampling often enough and recording the peak (and negative peak) values over a short period.  The faster you can sample the better your results will be.
From those peak values you can then do all sorts of calculations and things.  You can use them "as is" to directly give you the "peak-to-peak" current, or calculate the RMS voltage to then give you the RMS current.

Why are you AC coupling?

I withdraw the question. I made up your circuit, and without the AC coupling it didn't work properly (it was biased too high and the positive output was clipped). I like your solution, Majenko, it gives a nice clean output signal without needing diodes.

You need the capacitor for the AC coupling to separate out the two ground levels - the 0V for the sensor and the 2.5V offset for the op-amp.  As you saw, if you don't have it the inverting input is pulled too low by the sensor's ground point and the output has to raise itself much higher to try and compensate (the output, through the feedback, tries to keep the inverting input at the same level as the non-inverting input), which results in the output being offset and clipped.


text:
Arduino code of making a LED digit display not functioning properly
I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup()
{
   for(int i = 2; i++ ; i<9)
   {
      pinMode (i, OUTPUT);
   }
}
void _1()
{
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _2()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _3()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _4()
{
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( b, HIGH);
   delay(1000);
}
void _5()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _6()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   digitalWrite ( d, HIGH);
   delay(1000);
}
void _7()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _8()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _9()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _0()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void wait()
{
   digitalWrite ( a, LOW);
   digitalWrite ( b, LOW);
   digitalWrite ( c, LOW);
   digitalWrite ( d, LOW);
   digitalWrite ( e, LOW);
   digitalWrite ( f, LOW);
   digitalWrite ( g, LOW);
   delay(100);
}
void loop()
{
   _0();
   wait();
   _1();
   wait();
   _2();
   wait();
   _3();
   wait();
   _4();
   wait();
   _5();
   wait();
   _6();
   wait();
   _7();
   wait();
   _8();
   wait();
   _9();
   wait();
}

The problem is that it stays at _0 and then never changes. Any suggestions?

Ohk the mistake was found and rectified. Thanks

The for loop in your setup() function isn't quite right. The condition (i<9) and the iterator (i++) need to be the other way round, like this:
for (int i = 2; i<9; i++)
{
  pinMode (i, OUTPUT);
}


text:
How can I detect a disconnected pin?
I'm trying to build a system where if a cable gets disconnected from a pin (any pin), an action is executed.
I am wondering how to set this up. Can I simply wire the 5V to a pin and read its status or will this mess up the Arduino? Should I use any resistors? How should I connect this to the GND?
Please bear in mind that I'm pretty new to all of this.

Please state whether these pins are going to be used for input or output. If output, what are they driving? eg. LEDs. If input, what is the device you are reading from?

I am not really sure if I should use them as an input or output. The idea is that it triggers a software event and not a physical event (hardware). All I really need is a signal to the computer (though USB for now) that says that the cable is disconnected.

The way to do this, since there is no digital value in between HIGH and LOW, is to actively create a signal on the pin you can recognise.  Note that if the signal coming in to the pin is a datastream (a sequence of HIGH and LOW) that runs all the time this may not work reliably, but it's good for things like buttons and other simple sensors.
Any signal on a wire has a drive strength.  This is basically how powerful the signal is and how good it is at overriding other things happening on the same wire.  It is closely related to the output impedance of the source (what is sending the signal).  For things like buttons and switches that is basically the value of the pullup resistor used.
To actively sense if a pin is disconnected or not you need to temporarily connect it to a known signal level at the same time as it's connected to the wire (or not connected if it happens to be not connected).  This known signal level has to be of a weaker drive than the source signal by several orders of magnitude.  This ensures that if you try superimposing your test signal over the incoming signal the incoming signal swamps out the test signal and you don't see it at all.  For instance, if your source has 10KΩ impedance (say a button with 10KΩ pullup resistor) then a test signal with source impedance of 1MΩ would be suitable.
Each pin to be tested can be connected to its own 1MΩ (in this example) resistor, and those resistors are all connected to the same extra IO pin:

In this example pin D2 is the test pin, and pins D4-D7 are your inputs.
So under normal circumstances pin D2 is set as an input and completely ignored.  When you come to test the pins, though, you set it as an output.
You then set D2 to be HIGH and read each of D4 through D7.  Any that read as HIGH are candidates for being not connected.
You then set D2 to be LOW and read the pins that read HIGH before.  Any that now read as LOW are disconnected.
You then set D2 back to being an input again so it doesn't interfere with normal operations.

If you just want to know if current is flowing in a wire you can use what is called a shunt resistor.  This is a small resistor (maybe 1Ω) that is placed in-line with the wire and you measure the voltage (using Arduino analog inputs) at both sides of the resistor.  The voltage dropped across the resistor is directly proportional to the current flowing through it thanks to Ohm's Law:

I=V/R

For instance:

If the voltage read by A1 should be 5V (the voltage the wire is connected to) and the voltage read by A0 should be 4.93V, the voltage dropped by the resistor would be 5-4.93 = 0.07v.  With the 1Ω resistor the current would be 0.07/1 = 0.07A, or 70mA.
With the wire at OUT disconnected there will be zero current flowing since there is no circuit.  So re-arranging the formula above we can prove that we can tell it's disconnected.
If I=V/R then V = RI.  Therefore V = 1Ω × 0A = 0V.  So the voltage dropped across the resistor would be 0V, so A0 and A1 would be equal (discounting any noise). A0 and A1 would both read 5V.  Similarly, if the wire IN was disconnected instead then A0 and A1 would both read 0V.
For sensing higher currents you use a smaller resistance, and for sensing smaller currents you use a larger resistance - this allows for a voltage drop to be generated that is within a suitable range for the sensitivity of the ADC doing the reading.  For the Arduino that's a 10-bit ADC, so it can sense (with a 5V VREF) 5/1024=4.882813mV per LSB.
Note that if you are working with voltages above that at which the Arduino operates you will need to separate or otherwise scale those voltages.  There are special devices designed especially for this task called high side current shunt amplifiers.  They also allow you to use a smaller resistance than you would otherwise need which is less intrusive to your circuit (less voltage drop).

You can connect all pins through a 1M resistor to a rail. Once in a while you set all your outputs to inputs and toggle the rail HIGH and LOW, if the inputs are HIGH and LOW in the sequence you toggled the rail, there is no wire. The same question was asked at Arduino Forums so read this thread.
This question's answer was provided by johnwasser@forum.arduino.cc.

Thank you, but this looks way more complecated than it should be for my purpose. I am not using any external devices and/or sensors. What I am looking for is a way to detect if current is flowing from 5V to GND (cable connected) or not (cable disconnected).
You could think of it as a weird electronic necklace that will make sound once it is disconnected. Now how do I determine when to make the noise?

Alternatively, if this is a digital input, you can just use a pull-up or pull-down resistor to give the input pin a default value. Let's say you use a pull-up resistor to make the default high. Then you connect a low cable to this input so that the input reads low. Now, if the cable goes high or if it is disconnected, you get a high value in the input pin.
I know this was not quite what you were asking but maybe such a solution could help with your original problem. In my case, I have a flame detection module that gives low output by default and turns high when there is a flame. I don't want to miss the flame because of my cable disconnecting, so I use a pull-up resistor that will make the input high not only when there is a flame, but also when there is a disconnection. This way I make sure that I don't miss a fire because of the sensor cable disconnecting.


text:
Replacing Atmega8a pu 1440 arduino Ic with 1337
I have one Arduino uno, and one atmega8a 1337 ic. Can i replace the Arduino uno ic with 1337 to program the 1337 one?

That second number is the date code. 40th week of 2014 vs. 37th week of 2013. They're the same chip (although they may be different revisions).

@IgnacioVazquez-Abrams Thanks man. I had no idea.

If you have a bootloader installed on the 8A then yes, you can.  The two chips are pin and electrically compatible.

How do I check for it? Sorry but I am new to this.

Did you buy it with a bootloader installed, or did you install a bootloader? If the answer to both those is no then you will need to install a bootloader. You can use your existing Arduino Uno to do it - google for tutorials, there's plenty.


text:
Help Connecting MicroSD Module with Arduino Uno
I am Trying to make a MicroSD .wav file player using Arduino Uno. I have ordered a MicroSD Card Module from ebay today.
Product Link : http://www.ebay.in/itm/Micro-SD-Card-Module-SD-Storage-Board-TF-Card-Memory-Shield-SPI-For-Arduino-/161696480012?
As You can See in the Product Image, there is not mentioned on the PCB that which Pin Is ground or VCC Or any other SPI pin.
1. How will I identify the correct pins of the MicroSD Module ?
2. How can I connect a speaker to arduino to play .wav files. Is Amplifier neccessary? I am weak when it comes to electronics.
I have listened that when I connect a Capacitor in series with speaker, it will boost the output volume. There will not be music but only voice recordings in .wav files. I want to listen it clearly only.

this listing has the labels printed on the bottom. Probably identical to your.

OMG, what a vile listing!
Anyway, I think you'll probably find they are in the order listed in the description when the connector is facing south. It's probably printed on the rear of the board which they don't show.
That is, from left to right, GND, VCC, MISO, MOSI, SCK, CS.
As for connecting a speaker, that depends if you want low quality (PWM) audio, or high quality (DAC) audio.  The latter requires the addition of an audio shield, most of which have an SD card slot on them already thus alleviating the need for this SD card breakout board.
For the former there is a library and instructions here: http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio

I got my MicroSD Module today. The labels were printed At the bottom side. Dont confuse, CLK = SCK. The VCC goes to arduino 5v.