text:
How to sleep a whole circuit?
I have just completed my first project, a clone of the Simon game of the eighties. The main parts of the circuit are an ATMega328, a 1602 2x16 LCD, and a small joystick.
It is powered directly from 3x1.5V batteries with solder bridges connecting all power pins on each part directly to the batteries. Therefore, if I sleep the ATMega, it won't change a thing comsumption-wise, as the LCD will still be powered.
What are (my first project, I am very unknowledgeable) the possible strategies to sleep the whole circuit?
I thought of using an ATMega pin as a positive lead for the joystick and LCD. Is that feasible?
Another strategy would be to interface some component (a relay?) between the battery and LCD, and command that component from an ATMega pin. Does someone know the right part for the job (I have a 220V relay in my parts, but it seems overkill)?
Lastly, even though it seems unlikely, is there a possible strategy without using any ATMega pins, as I currently use every single one (4 buttons, 4 leds, joystick x, y, and button, 1 buzzer, and 6 pins for the LCD, for a total of 18) except Rx and Tx?

The LCD should use that much current, as long as you turn of the backlighting. By the way, are you using a bare ATMega328, or are you using an arduino board, like e.g. an UNO?

You could use an NPN transistor between the battery and the Gnd for the circuit.  As soon as you want to sleep the circuit just take the Base pin down to Gnd.

I am using a bare ATMega328, Gerben. Thanks for the NPN transistor hint, Matt; I didn't know of their existence until this moment :)

@Matt there is just a problem with your approach: to take the pin down to ground you need, well, ground. If you detached it you will have problems. In this case, you'll have to use a pair of complementary transistors (PNP and NPN) to invert the logic. Then, I think it is much better to cut the positive rail instead of the ground one. And.. I tend to prefer MOS transistors over bipolar ones ;) Check my answer for what I think is the best solution

@frarugi87 I think picking fault with an answer just because it won't work is mean :)  I'll give your answer a try next time I get chance.

See my post about power saving.

@Matt sorry, I didn't understand your comment ;) Anyway I know that the single transistor solution doesn't work because, well, I actually implemented it in one of my circuits. Then I told myself "you are stupid!", threw away the circuit (which, since there was no ground, was never really off) and started using a dual transistor solution every time I needed it ;)

The first and most smart solution is to use a switch between the batteries and everything else. This way, you slide the switch in the off position and the whole circuit is completely detached from the batteries: power consumption: 0.
If you can't (because, for instance, you want it to automatically power off after a while) you can use a transistor (PMOS, for instance) instead of the switch. you have then to put a complementary transistor (NMOS) on its gate, then a button in parallel to it. Just another passve component is required: a resistor (value e.g. can be 100k). When you press the button, the circuits becomes momentarily powered on. You will have to pull the nmos gate to a logic 1 with the atmega to keep the circuit powered. When you want to turn everything off, pull the pin to a logic 0 and your circuit will immediately shut down.
If, third solution, you want to give the atmega complete control over the powering, it needs to be always on. You can then omit the complementary transistor and use a reverse logic on the pin (so 0 = on, 1 = off) and then you can do whatever you want with the power (turn on and off whenever you want).
edit: as a comment suggests, it can be better to put a resistor to set the appropriate voltage on the gate at power up. Even if the commenter told to put a pull-down, I suggest you to put a pull-up (pull-down = normally on, pull-up = normally off). edit 2 as Paul suggested, there could be cases in which you need to be able to turn on and off automatically the circuit, and then store it for longer times without consuming battery. In this case it could be a good idea to put something (a mechanical switch, a jumper, a detachable wire) to completely detach the battery even from the arduino (even if, in this case, you can just remove the batteries from the housing).
Here is a small paint-made sketch to show the solutions. If you have any questions just ask ;)

EDIT: If you want to let the atmega control the power, you'll have to give him a way to do so. Which means.. You should use a pin. If you want you can use safely the RX and TX pins, as long as you don't enable the serial interface. If you need more pins, you can try to optimize your pins usage (for instance using a 4:1 multiplexer for the buttons you will have 2 control pins and 1 input, for a total of 3 pins, instead of 4), even if I think that the best solution is to use a port expander. for instance in the past I used the MCP23017, which has a I2C interface, or the MCP23S17, with a SPI interface. You will have to use the serial interface you choose (I2C: 2 pins - SCL and SDA, SPI: 4 pins - MISO, MOSI, SCK, SS, but they are the same pins used for programming), and then you will have 16 more pins for your uC
EDIT BY foivaras:
The same result can be achieved utilizing an NMOS instead of a PMOS.This would have an advantage over PMOS solution if power line was >5v and arduino was powered by a dc to dc converter. On this scenario, PMOS solution would need one more transistor to work.
Notice that the NMOS has to be placed on the low side of the power line and it will cutoff the power to joystick and lcd with 0v  and enable the power with 5v on its gate.(See 4th image)

COMMENT BY fra87
This solution is not a valid alternative in my opinion. Usually interrupting ground is a bad idea, because usually the rest position of the I/O pins is ground: if you interrupt the ground for the LCD, for instance, you will have +5V on the VCC pin, and a floating ground, but you will have 0V on all the I/O pins, possibly damaging the internal circuits. Moreover having a floating ground is bad in terms of noise protection.
The only advantage COULD be in the particular case explained by the editor, which is a DC/DC converter powering the arduino but not the LCD and the Joystick. This is a strange setup, though, and the proposed solution is better at a first glance (requires one less transistor), but is wrong. For instance, let's suppose the joystick is powered at 12V. If you detach the ground, the joystick will "shut down", which means that all its pins will float up to 12V. This means that on the arduino pin you will see 12V: you can damage it.
So, in the end, I discourage this solution. The only case when you can need it is when you are in a hurry and do not have any feasable PMOS: even in this case, however, I suggest you to replace the NMOS with a PMOS as soon as possible.
Just one more note: edits to the posts, in my opinion, should be done to improve the quality of the answer, by better formatting the content, removing orthographic errors and so on. If someone needs to add some comments or other solutions, it's better to use the comments or add another answer to the thread

I 'd consider putting a pull down resistor on the gate of the PMOS(3rd image) as the pins of arduino on power on or restart, are on high impedance state hence PMOS's gate state will be undetermined until the corresponding arduino's pin is declared output.

I would also consider adding a physical switch in front of the Arduino, to avoid draining your battery.

@foivaras I definitely prefer a pull-up, to keep everything powered off until requested. Anyway thanks, I added this to the answer

@Paul the physical switch solution is the first one I proposed (and the one I think is the best). In the third solution a switch is completely useless in my opinion, because the only reason to implement it is when you want to power up everything automatically, and switching off would prevent you from doing it

@frarugi87, it's actually pretty common on TV's.
You can put them on standby, to allow switching it on with a remote.
And you can totally power them off, with a physical switch.
If you don't use any sleep modes, and use an Arduino board, your battery will get drained significantly, so you can't really store it (withouth disconnecting the battery).
If you use a barebones microcontroller with the deepest sleep options, a switch might not be needed, since the current draw can be lower as the self-discharge rate of a battery.
But yea, it's a combination of the options you gave, but well.

@Paul In this case usually you can just, well, take the batteries out ;) if they are not soldered, of course. Anyway I added your contribution to the answer, so the reader can think at what is the best solution (and maybe think about this before doing the whole circuit) ;) thank you. And, BTW, I haven't seen a power switch on TVs for years ;) with modern TVs you have to pull away the power cord if you want a complete shut off

@frarugi87, old ones indeed. But yeah, fair enough ;)
Standard 1800mAh batteries will "only" last 150u with 12mA load.
(https://www.avrprogrammers.com/howto/atmega328-power) "At 8MHz the ATmega328 draws 11.68mA @ 5V. (1Mhz will be half of it).
So indeed, use sleep modes (or a switch). If you don't want to unplug the battery everytime. (having to change batteries every 8-16 days is not going to be nice)

You wrote: “if you interrupt the ground for the LCD [...] you will have 0V on all the I/O pins, possibly damaging the internal circuits.” You should obviously tri-state the I/O pins on the ATmega side before disconnecting the LCD ground. “a floating ground is bad in terms of noise protection”. Just as bad as a floating Vcc.

@EdgarBonet I've always been taught that ground should be only one; having different gnd (except when you have analog and digital ones) is a bad idea. All the noise immunity methods presume you have a common ground; the vast majority of circuits have ground planes, not vcc planes (only 4+ layer boards also have power planes), DC/DC converters create Vcc with respect to ground, not vice versa, if you have a shielding it should be connected to ground, never to vcc. Then, there are a lot of cases when interrupting gnd or vcc is the same, but I always try to interrupt gnd only when strictly needed

@Paul of course you need to have to possibility to set a deep sleep mode on the uC if you want to permanently power it from a battery; the only time I used such an approach was with a Texas Instruments uC which consumed around 0.8uA in sleep mode. Powering a uC not in sleep permanently is always a bad idea, unless you are a battery manufacturer ;)

In CMOS circuits, GND and Vcc (or rather, Vss and Vdd) play symmetrical roles. The fact that we always take the negative side of the supply as the reference, and call it GND, is essentially a matter of convention and history. Like or choice for the direction of the “current”, which is actually backwards relative to the electron flow.

@EdgarBonet sure, for standard CMOS circuits everything is highly symmetrical. But as soon as you take something else (analog circuits, RF, power supplies) things change. Switching DC/DC are an example: you can safely detach VCC from it, but you can't detach GND without careful thinking at every possible drawback. Even CMOS logic ports can have problems: for instance the AHC family has no parasite diode from the input pins to vcc: this means, for instance, that you can apply a 5V voltage to a 3.3V powered device without damaging it. This also means that if you power it off detaching vcc you

won't have to tri-state the input pins controller. If you detach ground, however, a logic 0 of the controller means -5V for the input pin, thus possibly damaging it.. Usually powered off means at ground, so everybody designing circuits will refer to this as the common powered off condition: if you pull everything to vcc, well, maybe it's the same, maybe not

thanks frarugi87 for the answer and everyone for the lively discussion. I'll be less dumb today than yesterday :)


text:
ESP8266 reset problem
I am trying some AT commands with ESP8266 but it resets continously when it stop resetting, i can't get any response from ESP8266.
Example :
AT

OK
AT+CWMODE=1

OK
AT+CIPMODE=0

OK
AT+CIPMUX=1

OK
AT+CWJAP="..",".."

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

I have upgraded my firmware and I tried GPIO0 and GPIO2 are active but it still does not response fine. It worked yesterday but today it is working like crazy..

What power source are you using?

Arduino's power source

Which Arduino?  (if it's not a genuine Arduino please provide a link not just the model).

It is arduino uno aliexpress clone

Where is the link?

Arduino için UNO R3 MEGA328P CH340 CH340G UNO R3   USB KABLOSU
http://s.aliexpress.com/EZNfmaa

That link doesn't get me anywhere useful.

Try this please, http://tr.aliexpress.com/item/high-quality-UNO-R3-MEGA328P-CH340-CH340G-for-Arduino-UNO-R3-NO-USB-CABLE/32394695799.html?spm=2114.010208.3.39.Zxfgbq&ws_ab_test=searchweb201556_9,searchweb201602_5_10017_10034_10021_507_10022_10020_10018_10019,searchweb201603_7&btsid=2d1749bf-72f9-478f-bfc6-2c8c15b51787

Wild surmise, because with no schematic or BOM it's impossible to say, but I would guess the 3.3V regulator isn't up to the job. On a genuine Arduino you have 150mA to play with. On that board it's anyone's guess.

yes . I had the same problem and the capacitor is solved the problem

Arduino can not provide enough current for ESP8266 operations. Use external 3.3V power supply, I would recommend 500ma. Also don't forget to put a small cap between vcc and ground. 100uf should do it.

Okay i will try but why sometimes esp8266 works fine, sometimes doesnt work i cant understand it. Can it be broken too ?

not likely, in extreme cases yes but its more probable that its current issue . If you can issue AT commands, the module itself is fine. Acording to ESP8266 power consumption chart, in transmit mode it takes +100ma, Arduino 3.3v pin can output about 50ma. So, everything is fine until you try to connect or turn on the wifi radio. At that time there is not enough current for ESP to properly function and it resets. Once reset it once again uses less current and could reboot and present itself as nothing happened. That could be whats misleading you.

I had the same problem. My esp8266 is powered by FTDI USB to serial module. Since this module can provide a limited amount of current to 3.3V. I use to get frequent reset.
I resolved it by adding a 1000ufd electrolyte capacitor near the power connection of the esp8266 module. And issue resolved like never been there.
I am sure that can also be done by a smaller capacitor. Try with 470 or 220ufd.
enjoy
Rauf

source: Stack Exchange

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

sort: votes


text:
reading pwm signal doesn't work correctly
my goal is to read a pwm signal from a rc receiver. For that i tried to use an arduino.
i ran this code on the arduino:
#define Pin 3

int pwm_value;

void setup() {
  pinMode(Pin, INPUT);
  Serial.begin(9700);
}

void loop() {
  pwm_value = pulseIn(Pin, HIGH);
  Serial.println(pwm_value);
}

Now i connected the 3rd pin with the output of the receiver. But instead of printing the correct pwm values they get printed completely crazy. Sometimes they are under 10 and sometimes they are over 10000. The receiver outputs the correct signal.
I also noticed that if i just touch the pin with my finger or if i only connect a single jumper cable without anything at the end, the arduino will read a pwm signal.
I have realy no idea to solve that. Can you please help me?
Thank you!

Are you sure it's PWM and not PPM?

Did you also connect the GND of the Arduino to the GND of the receiver? In case you did you could try using pinMode(pin, INPUT_PULLUP);

check if the problem is the fact you have set 9700 baud rate on your sketch while the commonly used 9600 is supported from arduino IDE.

I slightly modified your code and it works for me. Check if this works for you:
#define Pin 3
#define Source 5
unsigned long  pwm_value;

void setup() {
    pinMode(Source,OUTPUT);
    pinMode(Pin, INPUT);
    Serial.begin(9600);
    analogWrite(Source,500);
}

void loop() {
    pwm_value = pulseIn(Pin, HIGH);
    Serial.println(pwm_value);

}

when you connect pin3 with pin 5 you should get a consistent value on Serial(=967).
About getting signal on floating pins
Getting a signal on a floating pin is normal.
When you have a cable attached it acts like an antenna. When you touch it, you are the antenna!

the serial connection over 9700 was the problem. with 9600 everything worked just fine. Thanks so much for the answer!

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


text:
Proper use of * and & when passing objects in methods
Coming from C#, pointers are somewhat foreign although I am grasping the concept.
Is it proper to construct methods in the following manner and passing the object (as a parameter) constructed by reference? If not, then please answer how to do this properly.
Initialize the object
Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

Method: (use the * for pointer?)
boolean initializeMusicPlayer(Adafruit_VS1053_FilePlayer *mp, uint16_t baudRate) {

    musicPlayerSerialPort.begin(baudRate);
    // initialise the music player
    if (!mp->begin()) { // initialise the music player
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        return false;
        //while (1);
    }
    Serial.println(F("VS1053 found"));

    mp->sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        return false;
        //while (1);  // don't do anything more
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    mp->setVolume(20, 20);

    if (!mp->useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
        Serial.println(F("DREQ pin is not an interrupt pin"));
        return false;
    }
    return true;
}

Call the method (Use the ampersand to pass the currently created one by reference?)
if(initializeMusicPlayer(&musicPlayer, 9600) == true) {
    tempString = tempString + "MusicPlayer initialized!";
    Serial.println(tempString);
    //when adding lcd, print the above to lcd and remove the serial print
}

The method you have implemented, passing by pointer, is one of the two normal methods, yes. The other is passing by reference and is specific to C++, not C.
Under the hood the end result is the same between the two methods, by the syntactic "sugar" is very different and the latter can be preferable for that reason alone.
Your method:
void function(whatever *ob) {
    ob->method();
}

function(&myObject);

The pass by reference method:
void function(whatever &ob) {
    ob.method();
}

function(myObject);

As you can see the need to convert the object into a pointer with & is now gone. That makes it much easier for people lacking in programming skills to use it since it hides the whole pointer mechanism from them.
Also, internally your function now treats ob as just another object using ., rather than a pointer to an object and needing to use ->.  Note that you can only use the reference operator in a function prototype, not a variable or anything like that - it's purely for passing objects and variables to functions.  If you want to then go and store the pointer in a variable you still then have to get the address:
void function(whatever &ob) {
    myObjectPointer = &ob;
}

As you see it gets confusing with the two different uses of &. Basically though: if it's in a function prototype, it's the pass by reference operator. If it's anywhere else, it's the get the address of operator (or a logical AND of course).
Storing the pointer can be useful if you want to then do other things later on with the same object, especially if you are yourself working with a class.  For instance, I often write code similar to the following:
class foo {
    private:
        bar *ob; // Pointer to other object of type "bar"
    public:
        foo(bar *inob) : ob(inob) {}
        foo(bar &inob) : ob(&inob) {}

        void something() {
            ob->doSomething();
        }

        void somethingElse() {
            ob->doSomethingElse();
            ob->evenMoreThings();
        }
};

You then have a choice of constructors:
bar myBar;
foo myFoo(myBar);

// ... later ...
myFoo.something();

or
bar myBar;
foo myFoo(&myBar);

// ... later ...
myFoo.something();

and the user doesn't have to remember which they need to use - whichever they try will work.

So what I have done is correct, although not necessarily the best method. My thought with the pointer, was since that player can be called dozens of times, I want it to call the same object every time. Is my code written properly for that intent?

Looks fine to me.  Although I tend to pass an object to the constructor and store it as a pointer in the class I am making, then access the object through that pointer - means you don't have to then keep passing the same object over and over again.

@Majenko...Thank you, one other item. Put the class in the projects header file?

It depends how you are going to use the class. If you want to use it in other places it can be worth turning it into a library - have a .h file with the class declaration in it, and a .cpp file with the actual class methods. If you don't want to split it into separate declaration and definition then you should keep it in your sketch. It can still be useful to split it even then though if you have multiple source files in your sketch that all want to use it.

I think it would be worth mentioning the important difference between a pointer and a reference: a pointer can be NULL (i.e. 0 meaning that it points to nothing) whereas a reference shall always refer to a real variable (although technically it is possible to trick the compiler but nobody would do that). Personally I always prefer using references if I don't want to allow NULL.

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


text:
Voltage divider producing unexpected voltage
I'm trying to run a neopixel strip and an arduino from the same power supply using a voltage divider to get 5V to the strip.
Here are the values for my voltage divider:
R1 = 1500 Ω
R2 = 1000 Ω
Vin = 12 V
resulting in:
Vout = Vin*(R2/(R1+R2)) = 12*(1000/(1500+1000)) = 12*(1000/2500) = 12*0.4 = 4.8
When the divider is connected at its inputs but not at its outputs, I measure the expected 4.8V across R2. But as soon as I connect the neopixels, I only get about 1.6V.
Could anybody explain this || Suggest a possible solution?

You cannot use a voltage divider to supply power. It does not work. It can not work. Learn Ohm's Law and you will know why it can not work. Use a voltage regulator.

I guess that would be a power limitation of the resistors. Unable to take the current load. That's a great shame, I would like to be able to construct a functional level shifter from compon components. Thanks for pointing me towards a voltage regulator.

It is not a power limitation. It is Ohm's Law. Edgar's answer tells you why in brief.

hmm .. rookie mistake. I certainly belive that it's not possible, but I don't understand why... I have some reading to do.

I should point out here that NeoPixels can draw up to 60 mA each at full brightness. You need quite a hefty 5V power supply to power a lot of them. I suggest a suitable 5 volt DC regulated wall-wart (or similar) rated at a few amps. Even only 20 of them will require 1.2 amps.

Since you are connecting your pixel strip in parallel with R2, the
correct formula is
Vout = Vin × (R2∥Rp) / (R1 + (R2∥Rp))

Where Rp is the resistance of the pixel strip and
R2∥Rp = R2 × Rp / (R2 + Rp)

is the combination of R2 and Rp in parallel. From this you can see that
an output voltage of 1.6 V is consistent with a strip resistance of
300 Ω.
This is, however, somewhat oversimplified, as the I(V) characteristic of
the LED strip is probably non-linear, thus not really equivalent to a
resistor.

Thank you, that explains the output nicely. Though I'm not familliar with this use of '||' double pipe.

@xeuari It means "In parallel with"

@xeuari: It's not a doubled pipe character: it's single character, namely U+2225 PARALLEL TO. Compare: “||” vs. “∥”.

authors: ฆอยรูดิน คมขํา


text:
How to set float to variable with 7 digits after the decimal point in arduino?
Example:
float x = 3154681.124 / 100000; //x = 31.54;

I want x to be:
x = 31.5468112;

When you write 3154681.124 / 100000, you are accumulating two rounding errors: first, in representing the numerator as a float, then in the division. Total error ≈ 1.09e-6. If you write instead 31.54681124 you have a single rounding error, and the total error is 25% lower.

An IEEE 32 bit float has only 23 bits for the fractional part, so you only get about log(2^23)/log(10)=6.9 decimal places total.  Maybe you want a double?

The float type has slightly over 7 digits of precision. See https://en.wikipedia.org/wiki/Floating_point.

I want x to be:
   x = 31.5468112;

Bad luck. That's 9 digits of precision. You can get around 7 digits by converting it appropriately, eg. as Majenko said:
  float x = 3154681.124 / 100000; //x = 31.54;
  Serial.println(x, 7);

However that printed:
31.5468101

It got 7 digits right, as advertised.

You can use the BigNumber Library that I wrote. Available from GitHub.
Using that, you can get all the precision you want, within reason:
#include "BigNumber.h"

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

  BigNumber::begin (7);  // 7 digits after the decimal place

  BigNumber x ("3154681.124");
  BigNumber y = x / BigNumber ("100000");

  Serial.println(y);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output:
31.5468112

float x = 3154681.124 / 100000; //x = 31.54;

x is now 31.5468112 (or close to).
Serial.println(x);

Output: 31.54
Why? Because Serial.println defaults to 2 decimal places for floats.

Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
val: the value to print - any data type
format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

So the solution: specift 7 decimal places when you print:
Serial.println(x, 7);

I don't want to print x , I want to send it as a parameter in URL to web service. when I send it as x its value became 31.54

Then whatever your code is that is doing the sending is truncating it. I can't see that code, so I can't advise on it. The simple fact, though, is a float doesn't have a fixed number of decimal places, that's not how floats work.

when I send it as x its value became 31.54 - you need to post that code. We can't answer questions about code we can't see.


text:
Wifi101 ad-hoc network
I've reviewed the WiFi101 library but have found no way to make the 101 an ad-hoc network.  Am I missing something?  I'd like to be able to emulate the RedFly example:
http://notebook.kulchenko.com/embedded/storing-wifi-configuration-in-eeprom-on-arduino
Can the 101 become an ad-hoc network?  I understand the security problem with the ad-hoc capability so it would make sense that Arduino prohibits it.

Apparently you can have an ad-hoc network, you can see the example on the github here:
https://github.com/arduino-libraries/WiFi101/blob/master/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino
It shows how to create an open ad-hoc network, for a secured one, you might need to check the datasheet + the method implement "beginAP".

It does not need to be secured.  Thank you!


text:
Switching Many Switches with one Input
I have a situation where I need to select between two signals, lets say 1A or 2B and route it to output 3C. I need to do this six times (2A or 2B to output 2C, 3A or 3B to output 3C, etc.).
These all need to switch based on one output from my chip.
What sort of component do I need for this? I think it's something like a 2:1 spdt multiplexer, but something doesn't seem quite right.
I've been looking at a bunch of data sheets and I cannot seem to find a chip which switches many 2:1 switches based on ONE input. Does such a thing exists? Or am I just way of the mark here? Not sure.
Any help appreciated.
Thanks.

One output from the Arduino can go to many SELECT pins of multiplexers or switches. So where's your problem?

Almost, you will need two 74157 (or similar chips) to switch 8 pairs of TTL level logic signals down to 8 individual signal.


text:
wrong leds lit in matrix display - wrong coding?
I wrote the following code for displaying a bitmap (small size) on a  LED matrix (formed using APA102 led strip):
//for 24-bit bitmaps

// the header files for the RGB data

 #include <FastLED.h>
 #include "redarray.h"
 #include "greenarray.h"   //g data header file (hex or dec)
 #include "bluearray.h"   //b data header file (hex or dec)*/

//matrix parameters

#define MatrixWidth 36 //columns
#define MatrixHeight 7 //rows
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

 void setup() {

     FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
     FastLED.clear();
  }

void loop() {

  for(uint8_t x=0 ; x<MatrixWidth ; x++)  {

      for(uint8_t y=0; y < 3; y++) {

            leds[XY (x, y)].setRGB(redarray[x][y],greenarray[x][y],bluearray[x] [y]);

           FastLED.show();

           delay(1);
         }
      }
   }

      uint16_t XY( uint8_t x, uint8_t y)
 {
   uint16_t i;

     if( MatrixSerpentineLayout == true) {
       if( y & 0x01) {
        // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
     } else {
       // Even rows run forwards
          i = (y * MatrixWidth) + x;
    }
   }

  return i;
}

The following is the data in one of the header files - its of same type for the other two colors.
const unsigned char redarray[36][3] PROGMEM  = {
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
};
The matrix is in a serpentine form (evident from the XY function in code). I am using an Arduino Due. The problem is that the code compiles and runs...but the bitmap is incorrect. Although I am sure, I am somewhat along the correct path because some LEDs do light up as they should as per the bitmap. But most of them are wrongly lit.
Could you somebody plz guide where I am going wrong with the coding? I fear there is some mistake in reading the color data from array and allocating it to leds[XY(x,y)].I do not know how a 2D array is read or dealt with by Arduino.
Thanks!

Your code is hard to read.  Please try to indent is better.

Why is your LED matrix 36 by 7 but your array is 36 by 3?

@st2000 Insuffcient power supply. On taking all LEDs into use, it doesnt work, I am working on this power supply thing but for testing took 3 rows of 36 LEDs each. sorry for the improper code. Will edit it.

It might help if you created a test array that only lit 1 LED.  Then walked that LED through all positions.  Knowing when the lit LED does not appear in the expected location may provide hints as to where to look for problems in the array or your code.

Initialize your arrays like this:
int a[3][4] = {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

...you can read more about it here.
Added later...
The following explanation came from here:
Arrays that are not explicitly divided into rows:
int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};

...are filled like this:
int M[4][5] =
{
  {10,  5, -3, 9, 0},
  { 0, 32, 20, 1, 0},
  { 0,  8,  0, 0, 0},
  { 0,  0,  0, 0, 0}
};

As only you understand your data you will have to verify if your data is populating the array as you expect.

the problem is that - the color data I generated is not in the format arduino wants 2D array to be declared. Its tedious to put everything in brackets like this and I somehow realised that this is not the way c++ reads arrays. I can just declare the array like charlie[] [] = { }; With no individual bracketing on the elements and it reads it correctly. And also when I did like you told me, I am getting this error - expected unqualified-id before .... and it took me 20 minutes to arrange data like this.....Is the reading of the color data and consequent allocation to LEDs correct????

..Thanks bro..As per your links of declaring an array, I managed  to get it working (after resolving some array indexing problem - here it is - https://arduino.stackexchange.com/questions/24103/what-does-this-error-mean-arduino-due-loop-warning  - I got it working now...the pattern is displayed....Thanks for links :)


text:
How to calibrate a load cell?
I'm working with a load cell and HX711. There was no weight on the sensor but I kept getting strange values, I thought it was broken or something so I used my second load cell but the same thing happened again.
I'm wondering what is wrong with it ?
If anyone have worked with it or have an idea how to work with it, please don't hesitate to give your opinions.
 #include "HX711.h"
#include <Wire.h>

#define DOUT  A0
#define CLK   A1

#define DEC_POINT  2
#define STABLE  1

float offset=0;
float calibration_factor = 1;
//float real_weight = 1.560;//kg
float real_weight = 0.5;//kg

HX711 scale(DOUT, CLK);

unsigned char state=0;
long  FindZeroFactor();
float get_units_kg();
void  ReadWeight();
void  FindCalibrationFactor();

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println("Auto Calibrate Program");
  Serial.println("Send 'a' to Find Zero Factor (Please Remove all weight from scale)");
  Serial.println("Send 'b' to Find Calibration Factor (Please insert know the weight on the scales)");
  Serial.println("Send 'c' Show weight on the scales");
}
void loop()
{
  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp=='a')
      state=1;
    if(temp=='b')
      state=2;
    if(temp=='c')
      state=3;
  }

  switch(state)
  {
    case 0:
    break;
    case 1:
      FindZeroFactor();
   //   ReadWeight();
      state=0;
    break;
    case 2:
     FindCalibrationFactor();
     state=0;
    break;
    case 3:
      ReadWeight();
      delay(200);
    break;
    case 4:

    break;

  }
}

long FindZeroFactor()
{
     Serial.println("Find Zero Factor");
     Serial.println("Please wait .....");
     scale.set_scale();
     scale.tare();
     long zero_factor = scale.read_average(20);
     Serial.print("Zero factor: ");
     Serial.println(zero_factor);
     return(zero_factor);
}

void FindCalibrationFactor()
{
  unsigned char flag_stable=0;
  unsigned int decpoint=1;
  for(unsigned char i=0;i<DEC_POINT+1;i++ )
    decpoint = decpoint*10;
  while(1)
  {
      scale.set_scale(calibration_factor); //Adjust to this calibration factor
      Serial.print("Reading: ");
      float read_weight = get_units_kg();
      String data = String(read_weight, DEC_POINT);
      Serial.print(data);
      Serial.print(" kg");
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();
      long r_weight      = (real_weight*decpoint);
      long int_read_weight = read_weight*decpoint;
      Serial.print(r_weight);
      Serial.print(" , ");
      Serial.println(int_read_weight);
      long x;
      if(r_weight == int_read_weight)
      {
        flag_stable++;
        if(flag_stable>=STABLE)
        {
          Serial.print("Calibration Factor is = ");
          Serial.println(calibration_factor);
          break;
         }
        }
       if(r_weight > int_read_weight)
          {
            x = r_weight - int_read_weight;
            if(x > 100)
              calibration_factor -= 1000;
            else if(x > 100)
              calibration_factor -= 10;
            else
              calibration_factor -= 1;
            flag_stable=0;
          }
          if(r_weight < int_read_weight)
          {
            x =  int_read_weight-r_weight;
            if(x > 100)
              calibration_factor += 1000;
            else if(x > 10)
              calibration_factor += 10;
            else
              calibration_factor += 1;
            flag_stable=0;
           }
  }
}

float get_units_kg()
{
  return(scale.get_units()*0.453592);
}
void ReadWeight()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.print("Reading: ");
  String data = String(get_units_kg()+offset, DEC_POINT);
  Serial.print(data);
  Serial.println(" kg");
}

Could it be power fluctuations or a dodgy ground?

Or could it be your (unspecified) circuit?

The typical examples show a zeroing on startup.  Once zeroed calibration can be as simple as a known mass, or several to check linearity.  If you have another scale found objects will do, otherwise you can get a crude kit of calibration weights.  If you have a beam sensor make sure it is not upside down.  Beware there will always be noise - you probably want some filterung in what you display, again see typical examples.

@Matt i'm aware of that and I checked everything

@Majenko what do you mean ?

@ChrisStratton I found some code samples and i'm using one but now I'm getting zero even when I put a wait on the sensor. PS: i'm using a tension compression load cell

@geniusme I am saying maybe there is something wrong with the circuit you are using to interface your load cell to the Arduino - however you haven't shown us that circuit so we are unable to tell. Please show your circuit, and also your code. Without that we cannot help you.

@Majenko I'm wiring my circuit like this link

@geniusme That means nothing to me. What are those connections? Where do they go? What is the circuit you have there? I assume there must be some form of Wheatstone bridge there somewhere, yes?

@Majenko yes it is

@Majenko I'm using a load cell to weight stuff that other board represent a A/N converter and an amplifier (the variation is very small so we need to amplify it to have a noticeable result)

Could you add some sample output to the question? In the question you said you were getting strange values, but in the comments you said you were only getting 0s.

because I started using a library, now when I have nothing on the sensor t it display zero and when I put a known weight it gives me a value but not the weight. I'm trying to figure out a mathematical formula to give me the correct weight

Is the value consistent?  If it is, and you are in the linear range, then the mathematical formula is to multiply by a constant.  Are you asking how to calculate the constant?  If so, What is the known weight and what is the displayed value.

@DaveX I found the mathematical equation, thank you ! I was wondering if I have a lot of load cells, would I have to calibrate each one of them every single time?

@genuisme To get very high levels of accuracy, yes.  Load cells, and the electronics are subject to mechanical, manufacturing variation, creep, etc., and using a common calibration factor would make your systems susceptible to those factors.  For the highest levels of accuracy, you would recalibrate with known weight standards in the range of interest before measurement and then re-check afterwards for drift.

The first thing that about Load Cells that always comes to my mind is the circuit which amplifies the load cell's signal, Usually the load cell signal changes in a low mv range, so you have to put a high gain circuit in the way of the signal, which amplifies signal and NOISE. You have to use an instrumentation amplifier for this purpose, otherwise, your signal would become so noisy.
And try to implement a low pass digital filter too, it should compensate the fluctuations and would give you smoother signal.

scale.set_scale(calibration_factor);

needs to be changed to :
scale.set_scale(calibration_factor/[the reference weight you have used]);

Hi Reza, and welcome to Arduino.SE! While your answer may be correct, it is a little terse. Could you expand upon our answer and explain why that change is required?


text:
Cannot directly connect Arduino Ethernet to PC
I have been following various tutorials (especially: this) to connect an Arduino Ethernet board to my Ubuntu PC via Ethernet directly.
The IP address of the computer was found to be 10.100.31.128, and so I tried addresses in this range (10.100.31.67, 10.100.31.121, ...) without success. DHCP also doesnt seem to work. For the MAC address I used the sticker on the back of the board. I am using a patch cable, maybe that's the problem?

Did you tell your system that it needs to expect another client on the end of the cable?

No, how do I do that, or where can I find information on that?

uhm.. did you set a static IP on your PC? And then, how do you check the connection?

Who is the DHCP server?  The Ubuntu box?  Or a router?  If a router did you check to see if the router has issued an IP to the MAC of the Arduino Ethernet shield.  Maybe you can monitor the /var/log file w/a "tail -f" while you try to ping the Arduino (sorry, can't remember the exact system log file on a Ubuntu box, please look it up).  In the end, it's much easier to debug network problems on a Linux box as Window boxes tend to give up with out telling you (i.e. window boxes will say they are pinging but actually send nothing out on a failed network).

Also, I doubt you need this, but older Ethernet ports will not automatically detect a cross over problem.  So for direct connections (i.e. w/o a hub or switch between devices) you many need a cross over cable.

I created a new wired connection with a static IP, now this example is running.

So the problem was that your PC was configured to use a DHCP server, but no DHCP server was present. In this case, the PC displays an IP, but no routing tables are created and so you are not able to use any connection over that link. For direct connecitons, either activate a DHCP server on your PC or use static IPs

Network problems can be complex.  If these suggestions are not right I can change the answer later if other solutions present themselves.
If you are connecting two Ethernet devices directly you may need a cross over cable.
To test your connection with out using IP addresses, try to follow what is discussed in this answer where the MAC address is used on a Ubuntu system instead of the IP address.
You also might try using wireshark to monitor the Ubuntu box's Ethernet port.

When you connect your Ethernet Shield to your Ubuntu PC your PC 'looks' at the Ethernet shield as if it were a router and therefore tries to connect to it as an internet source, thus it tries to get an IP and other related stuff from the Ethernet shield.
BUT
What you want is that the Ethernet shield should use the ubuntu PC as an internet/local network source. For this you must have active internet on your PC from Wifi/ USB data etc.
You will have to BRIDGE the connections of your Ethernet shield and your internet source in order to do so.
The link to accomplish Bridging networks in Ubuntu is here
When you bridge two Ethernet networks, the two networks become one single (larger) Ethernet network. Thereby making the Ethernet shield a part of the larger network (Internet in this case). You can now upload any of your sketches onto the Arduino as per your requirements and accomplish your task.


text:
Is it possible to increase the Arduino's input and output pins?
I am undergoing a BSc (Hons) Degree in Computer Science and working on an Arduino project.
I am using the Arduino Mega and even though this microprocessor has plenty of input and output pins I am running out.
In the event that there are no more I/O pins available for me to make use of, and I am also referring to both analog and digital pins, is it possible to increase them?
I did some research, however the solutions are too vague... One of the suggestions was to use one or more of the following: 74HC595 8-Bit Shift Register DIP-16.

I am good at coding however when it comes to hardware sometimes I'll need some push.
Thanks a lot.

Could you give us some specific numbers? Like how many output-pins? How many input-pins? How many analog pins? Also what is connected to the different pins. E.g. leds can be placed in a matrix, and multiplexed to massively reduce the number of pins needed.

Posting an image of an IC package is not a meaningful way to propose an idea, use the part number and a functional description

There are lots of multiplexer ideas, the port expanders people have mentioned will help or you can do a search for "arduino multiplexer" or similar. (the 74HC595 you have linked is a very common device used for this sort of thing.)

Also do a search on this site, by doing something like: http://arduino.stackexchange.com/questions/tagged/multiplexer

Hi Chris Stratton the part number of the attached image is: 74HC595 8-Bit Shift Register DIP-16 IC CF.

Part number is all we need. A generic photo of an unkown chip doesn't give any useful information.

IMHO if you don't tell us what you want the pins to do it'll be very difficult to give you more than basic ideas. Are you driving LEDs? if you need independent channels, use a matrix arrangement or charlieplexing. Are you using buttons? definitely matrix arrangement. Analog pins? maybe an analog multiplexer, or external serial ADCs. lots of parallel wires? maybe you can serialize them (for instance LCDs use 7-11 pins, but you can find easily serial LCDs which use only 2-3 pins, and are highly expandable). Different scenarios? use one, two, three port expanders. Just explain what you need

You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.
Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library
This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf
As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.

Hi Jerry, thank you so much for the informative answer.
In addition what would you recommend as an effective programming language to interface with the arduino. At this moment in time I am considering to use ASP.NET and creating a web application.
The reasoning behind this is to create a website and display and store some of the data read from the arduino's sensors in a database.
Thanks again.

You might want to look into ready-made IoT services. Thingspeak.com is a popular free one. You could download the Thingspeak library for Arduino, attach an ethernet shield, and have the Arduino upload the data by itself. When I don't do it like that, I like to use a Python daemon that grabs the Arduino data via the serial port (pyserial module) and uploads it to the IoT site. Thingspeak has easy to use Python examples too.

You can either use external hardware or communicate to a 2nd Arduino and control the 2nd Arduino's digital and analog ports.  Being good at coding would suggest you would prefer communicating to a 2nd Arduino.  Also, most hardware solutions only add digital pins, not analog pins.

The beauty of a 2nd Arduino is that you can add logic (beside pins), offloading some work from the main Arduino. You can not only read an analog value, but also convert it to a domain problem value (temp, light) before sending it to the master Arduino.

You can use a CD74HC4067 Mux multiplexer to increase the number of inputs/outputs. This IC will convert 4 analog or 4 digital pins to 16 inputs and outputs.


text:
How to put 2 variables in a macro?
In a previous question (Append Text to Variable Names: Please Help Me Shorten This Code) I learned that in order to shorten this code:
fanSpeed = readEEPROM(AT24C32_ADDRESS, 1, fanSpeedPos);

I could define a macro at the top of the script like this:
#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

And then just use the following shorter code:
readEE(foo);

Which would be expanded out to:
foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

My current question is: How can I write a macro that accepts 2 arguments instead of just 1? I couldn't find much information about this concerning Arduinos, so I studied about how to do it in C++ (like from here: http://en.cppreference.com/w/cpp/preprocessor/replace) but it was too complicated for me to understand.
In particular, I would like to learn if it's possible to shorten the following code:
void writeToEE(byte location, bool value, bool &var) {
  writeEE(loc, value); var = value;
}

(Sidenote: the writeEE function looks like this: void writeEE(uint8_t entry, uint8_t data) { writeEEPROM(AT24C32_ADDRESS, 1, entry, data); }. Since the first 2 arguments are almost always constants, that's why I shortened it with another function).
Since whenever I'm using writeToEE, the "entry" variable name is always the "data" variable name with "Pos" appended, I would ideally like to do this (pseudo-code):
#define wrEE(VAR, VAL) VAR = writeToEE(VAR ## Pos, VAL, VAR)

so that when I write this:
wrEE(fanSpeed, 3);

it will be expanded out to:
writeToEE(fanspeedPos, 3, fanspeed);

I just don't know how to pass the 2nd argument ("VAL") into the macro, which is the value being stored in the "fanSpeed" variable, in the "fanSpeedPos" location in the EEPROM. When I try to compile my pseudo code example (was hoping to get lucky!), I get the following error message: "void value not ignored as it ought to be"

... Did you mean to put "VAR = " in front of it?

I really don't know what I'm doing, and I took the "VAR = " part from the first link in the first sentence of the post.

But the return type is void. Which means it doesn't return anything.

Thanks for the guidance! Now I understand that in the first example (from the other thread), the readEEPROM was returning a variable, which is why VAR = was needed. I removed it so that the macro then became: #define wrEE(VAR, VAL) writeToEE(VAR ## Pos, VAL, VAR), and it seems to work! It seems like it's storing my variable correctly. Is it really that simple? Does it look like that's the correct way to do it?

Small side question: since the writeToEE function is calling the writeEE function, would the code run faster if I skipped the writeToEE function and just had the macro expand out to the writeEE function? (Sorry for the confusing similar names). Or does it all end up to be the same after it goes through the compiler?

In the parameter list of the #define for the macro, separate the second argument from the first with only a comma.  For example:
#define wrEE(speed,var) writeToEE((etc))

The "void value not ignored as it ought to be" error message is a consequence of trying to store the void result of writeToEE.  The solution is to not try to store it.
In C, variable, parameter, and constant names are case-sensitive.


text:
arduino teensy no true HI-Z available?
I am using this https://github.com/watterott/SilentStepStick stepper driver to drive a stepper motor.
I am having trouble setting pins to HI-Z/floating to configure the stepper driver.
To set the driver to 16 micro steps and full interpolation, one has to set 2 configuration pins to HI-Z/floating (datasheet, p.9).
The example code on github (TMC2100.ino) just doesn't touch the pins at all, this works fine for me.
However, if I only add the lines:

pinMode(11, INPUT);  //connected to CFG1
pinMode(10, INPUT);  //connected to CFG2

which should set the pins to HI-Z/floating, the result is different.
The motor turns at the same speed, but makes more noise, I believe the driver is using the 16 step method with no interpolation. This corresponds to both pins being interpreted as high.
This makes me believe, that the Arduino uses a different code at startup than being used in pinMode(x, INPUT) to configure all pins. I am using a Teensy 3.1/3.2.
How can I solve the problem? Pins 11 and 10 are hard wired to the driver, as it replaced the well known A984.
Apart from the obvious "don't configure the pins then", I would like to know what's going on here.

Examine your circuit for possible pulling resistors.  Check the Teensy code details or look up and directly query the relevant raw kinetis gpio configuration registers.

If there were any pulling resistors, then it should not work when the pins are not configured in code.

Then check the implementing code for the function you are calling and raw register values, or move this to the PJRC support forum.

The Teensy has internal pull-up/pull-down resistors which can be enabled or disabled through software, see e.g. p. 231 here. You may want to check the "pull enable" (PE) bit in PORTx_PCRn.

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


text:
Ethernet shield/WebServer problem: 'server is at 0.0.0.0'. Any suggestions how to debug it?

Ethernet shield problem. When running the WebServer example sketch, the Serial Monitor shows that server is at 0.0.0.0. Any suggestions how to debug it?

That's what it's supposed to be. It's called INADDR_ANY. Read an introductory text on networks and you'll understand what that means.
If you try to connect to the IP address you specified, you'll see that you can indeed connect.

Unfortunately this is not the case in my case :/

The arduino only tells what it reads from the ethernet module and 0.0.0.0 is what you get when Arduino is not connected to it. It's a hardware problem, you either didn't connect the wires right or something's fried. I think it can also happen if your ethernet cable is unplugged.
This is absolutely not a sign that your module is accepting all connections. It would be the case if you set it that way but you are obviously expecting another ip adress. Someone should delete that answer.

If another answer is incorrect then it should be downvoted

If possible, try running the same code on an identical Arduino. I had a similar issue, and it turned out one of my ICSP pins were burned.
Contrary to other answers here, the IP address will show the correct value in the Serial Monitor even though nobody is connected.


text:
split serial.readString() output
I'm trying to read a string like this one:
2;12;42;43;34

over a serial connection and split this string afterwards by a ";".
So the output would be this array:
(2,12,42,34)

All the stuff runs on an arduino uno. So I made some code:
String read_input;
char read_input_char[20];
char *read_values;

void setup() {

  Serial.begin(9600);
  Serial.setTimeout(10);

}

void loop() {
  if(Serial.available()){
    read_input = Serial.readString();
    read_input.toCharArray(read_input_char, 20);

    read_values = strtok(read_input_char, ";");
    Serial.println(read_values[2]);
  }
}

However now instead of outputting the 3rd array element it outputs only an '1'. What's wrong?

strtok() doesn't do that.  And the characters available to Serial.readstring() may not have the full string in the buffer when loop() first calls it.

This is a C question, not an arduino question, but anyway:
From the man page:
DESCRIPTION
   The  strtok()  function  breaks a string into a sequence of zero or more nonempty tokens.  On the first call to strtok() the
   string to be parsed should be specified in str.  In each subsequent call that should parse the  same  string,  str  must  be
   NULL.

You are only calling strtok() once, so it only parses the first value. You need to keep calling it until there is nothing left to parse.

Your code as is checks for a non-empty Serial buffer (the Serial.available() bit), and then reads it all into a String. Be careful doing this, as if this happens to execute part-way through the data arriving, you will get a partial data String. This may be cut off part way through one of your integers.
Also, the String object is very memory-intensive. Maybe not an issue for you, but try to use char arrays, or read directly from the Serial buffer.
In your case, there is a great function that you could use; parseInt().
Details are at; https://www.arduino.cc/en/Serial/ParseInt
More or less, this reads successive chars from the serial buffer, and once digits are encountered, forms an int. This continues until a non-digit char, or a (configurable) timeout. Something like this might do the job for you;
int data[10]; // Or however long you need it to be!
int arrayPointer = 0;

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

void loop() {
  if (Serial.available()) {
    int incomingInt = Serial.parseInt();
    Serial.println(incomingInt);
    data[arrayPointer] = incomingInt;
    arrayPointer++;
  }
}

Hope this helps!


text:
What is the output of Software Serial .read() function
Hi I am new to arduino development i was using esp8266 using software serial library

here is the code

#include<stdlib.h>
#include <SoftwareSerial.h>

SoftwareSerial monitor(2, 3); // RX, TX

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

  sendDebug("AT");
  delay(5000);
  Serial.println("Hello");
  if(monitor.find("OK"))
  {
   Serial.println(monitor.available());
   Serial.println((int)monitor.read());
   Serial.println((int)monitor.read());
    Serial.println(monitor.available());
   Serial.println("RECEIVED: OK");
    //connectWiFi();
  }
  else
  {
    Serial.println("RECEIVED: None");
  }
}

void loop(){

}

void sendDebug(String cmd){
  monitor.println(cmd);
  Serial.println("Command: "+cmd);
}

Output

Command: AT
Hello
2
13
10
0
RECEIVED: OK

All I know is monitor.available() return the available bytes that can be read and i can also deduce that these two bytes are O and K but the integer value doesn't corresponds to the ascii value of O and K
can anyone explain what is actually getting printed on the serial monitor what is 13 and 10 ? ??

It is just like https://www.arduino.cc/en/Serial/Read :
The monitor.find("OK"); already consumed the 'O' and the 'K' bytes, (see https://www.arduino.cc/en/Serial/Find ) then there were two bytes .available(), a 13=CarriageReturn and a 10=LineFeed, both returned by successive monitor.read()s, then zero more bytes in monitor.available().


text:
Is ATMEGA328P the same as 16U2?
I've been playing with my Arduino for a few months.
But, I just bought a shield that says it needs to be used with ATMEGA328P.  My box says I have a 328P, however, reading the chip, it's inscribed with "ATMEL MEGA16U2".
Does that mean the box is wrong, or is that the same as 328P somehow?
Thanks!!

Could you post a picture of your board?

The 16u2 is related to the ATmega328p, and includes USB, but is more limited in resources.   While it would be possible to make an Arduino-type board from alone, this is unlikely to be what you have.
Rather, it is likely that you have a board with an ATmega328p as the main processor, and also a 16u2 which serves as a USB interface for it.
You could know for sure from what board type you select in the dropdown menu of the Arduino IDE.  If you are selecting something like "Uno" or "Duemilanove" you have a 328p as the main processor.
(The other presently common type of board is the "Leonardo" style where a 32u4 - essentially a bigger version of the 16u2 - is used as a single-chip solution that is both the primary processor and the USB interface.  But if that is what you had, it would not say 16u2 on it, unless it was an attempt to make a more limited "budget" version).

You are correct - when I plug it in and use the IDE, I can connect to it as an Uno.  Thank you, @Chris Stratton!

the 328p is the microcontoller. It's the larger chip located in the middle of the arduino board surface. This one handles the code/ sketch/ programme that you write). The 16u2, on the other hand, is the smaller chip located near the USB port. This handles data communication through the USB port.


text:
Arduino Pro Micro clone clock cycle issue
I have several Arduino Pro Micro clones that are giving me an issue where they work immediately after being programmed while the USB cable is still connected, but as soon as I disconnect and reconnect the USB cable the program fails. I was able to break it down to the simplest form and found that the clock cycle is off by what I estimate to be almost a factor of 10.
For testing, the only command in the loop is Serial.println(millis());. Immediately after programming you can watch the milliseconds scroll by in the serial monitor at the expected rate. Unplug and plug the USB, reconnect the serial monitor and now the milliseconds scroll by at about 1 second interval.
The Arduino IDE version is 1.6.8 and have tested it from both a Mac and Ubuntu with the same results. Also tested on 4 different boards with the same results. I also tested the latest Arduino beta with no change. Next I'm going to download some older Arduino IDE versions.
Any suggestions?

The fix for this issue was to reload the bootloader.  I used the SparkFun Caterina bootloader.


text:
How do I connect velostat to an arduino?
I have some velostat that I'd like to hook up to an Uno. At the risk of sounding dense...how do I do that?
Ultimately wanting to get readings of pressure from the velostat, just not sure how or what wires to connect where.

Usually a variable resistance sensor is used in a voltage divider circuit:

In the above example a thermistor is connected to the positive supply and a pull down R1 is connected to ground.  The voltage where they meet is measured using one of the Arduino's analog inputs pins.
Choosing R1 is tricky.  If it is too large compared to the variable resistance sensor the voltage fluctuation at Vout will be too small to measure.  The same problem exists if R1 is too small compared to the variable resistance sensor.  Also, you need to mind the current through the sensor.  If the combined resistance of R1 and the sensor is too small the current may damage the sensor, over heat R1 and / or put a heavy drain on your power source.


text:
How would I refactor this code, given how similar most of the lines are?
I have a set of buttons and a set of NeoPixel LEDs. There's lots of very similar constants (button1pin, button2pin, etc) so there's almost certainly a more efficient way of coding this.
Any ideas?
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);

// Buttons
const int button1pin = 3;
const int button2pin = 4;
const int button3pin = 5;
const int button4pin = 6;
const int button5pin = 7;
const int button6pin = 8;
const int button7pin = 9;
const int button8pin = 10;
const int button9pin = 11;

const int led1 = 0;
const int led2 = 1;
const int led3 = 2;
const int led4 = 3;
const int led5 = 4;
const int led6 = 5;
const int led7 = 6;
const int led8 = 7;
const int led9 = 8;

void setup() {
  strip.begin();
  strip.show();

  pinMode(button1pin, INPUT_PULLUP);
  pinMode(button2pin, INPUT_PULLUP);
  pinMode(button3pin, INPUT_PULLUP);
  pinMode(button4pin, INPUT_PULLUP);
  pinMode(button5pin, INPUT_PULLUP);
  pinMode(button6pin, INPUT_PULLUP);
  pinMode(button7pin, INPUT_PULLUP);
  pinMode(button8pin, INPUT_PULLUP);
  pinMode(button9pin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(button1pin) == LOW){
    strip.setPixelColor(led1, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button2pin) == LOW){
    strip.setPixelColor(led2, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button3pin) == LOW){
    strip.setPixelColor(led3, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button4pin) == LOW){
    strip.setPixelColor(led4, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button5pin) == LOW){
    strip.setPixelColor(led5, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button6pin) == LOW){
    strip.setPixelColor(led6, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button7pin) == LOW){
    strip.setPixelColor(led7, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button8pin) == LOW){
    strip.setPixelColor(led8, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button9pin) == LOW){
    strip.setPixelColor(led9, strip.Color(20, 55, 0, 0));
  }

  strip.show();
}

int buttons[9]={3,4,5,6,7,8,9,10,11}; int leds[9]={0,1,2,3,4,5,6,7,8,9};...

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);
// The maximum pin number for the buttons
const int MaxButton = 11;
// The value if the pin is not connected to an LED
const int NotConnected = -1;
// The connections from buttons to leds.
const int Connections[MaxButton+1] = {NotConnected, NotConnected, NotConnected, 0, 1, 2, 3, 4, 5, 6, 7, 8};

void setup()
{
  strip.begin();
  strip.show();
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        pinMode(pinNumber, INPUT_PULLUP);
    }
  }
}

void loop()
{
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        if (digitalRead(pinNumber) == LOW)
        {
            strip.setPixelColor(Connections[pinNumber], strip.Color(20, 55, 0, 0));
        }
    }
  }
  strip.show();
}

I can't test it, so I have no idea if it works, but it should do.

+1 for using const int instead of #define.


text:
ESP8266 - CIPSEND & external power supply Hangs program
Updated:
I connected my esp to external power, the blue light stays on, I start getting garbage data.
I used voltage regulator which was giving 3.4v, power supply tested with 1A &  2A.
Old problem :
I have been trying to make ESP8266 since my last semester exams & now 2nd semester exams are going on. So i've been trying to make ESP8266 work for very long time.
Earlier it was firmware problem, i updated it.
After a lot it worked. I tried many libraries - but none worked, either some are using specific port or some want specific firmware version which is really hard to find & then flash.
I am using telnet to check.
When i disable code to send data - i can send data madly, it works & never hangs up. But as i use AT+CPISEND after 1-2 read/write - it stops responding.
I am powering using arduino with/out voltage divider. Its firmware - 0020000903, AT Firmware v1.5, 4mb flash size, I changed baudrate to 9600.
Below is code i worte :
( I intentionally didn't remove comments)
#include <SoftwareSerial.
#define DEBUG true

SoftwareSerial esp8266(9,10); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different

Serial.print("Sending at..");
  sendData("AT",2000,DEBUG);
  //sendData("AT+RST",2000,DEBUG); // reset module
  sendData("AT+CWMODE=1",1000,DEBUG);
 // sendData("AT+CWLAP",1000,DEBUG);
 //sendData("AT+CIOBAUD=9600",1000,DEBUG);
 //sendData("AT+UART=9600,8,1,0,0",1000,DEBUG);
 //sendData("AT+IPR=9600",1000,DEBUG);
 // sendData("AT+CWJAP_DEF=\"mad\",\"agentis47?orBond?\"",15000,DEBUG);
 //sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80",1000,DEBUG); // turn on server on port 80
}

void loop()
{

  if(esp8266.available()) // check if the esp is sending a message
  {

    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }

    //Serial.println("IPD Search "+(len));
    if(esp8266.find("+IPD,"))
    {

     delay(20); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.read(); //skip the comma ','
     //(CIPMUX=0): + IPD, <len>:
     //(CIPMUX=1): + IPD, <id>, <len>: <data>
     int len = (readUntil(":")).toInt();
     if(len>500) len = 500; //prevent extra data we won't be sending more than 500bytes in one go.
     char data[len];

     esp8266.readBytes(data, len);
     //data[len-2]='\0';

      int pinNumber = (data[0]-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += ((data[1])-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

       digitalWrite(pinNumber, !digitalRead(pinNumber));
    Serial.println(String(len));

     /*Serial.println("===");

     Serial.println("--");
*/
    //cleanBuffer();
    //delay(10);
     //Serial.println("Sendddiddding data");
     //sendData(connectionId,String("OK"));
     //Serial.println("Sent");
     //closeConnection(connectionId);

     //digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     //String closeCommand = "AT+CIPCLOSE=";
     //closeCommand+=connectionId; // append connection id
     //closeCommand+="\r\n";

     //sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

void cleanBuffer(){
  while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }
}

String sendData(int connectionId, String data){
  //Serial.println("AT+CIPSEND="+String(connectionId)+ ","+String(data.length()));
  //sendData("AT+CIPSEND="+String(connectionId)+ ","+String(data.length()),1000,DEBUG);
  //sendData(data,100,DEBUG);
  //closeConnection(connectionId);
  String webpage = "
Hello
&lth2>World!
<button>LED1</button>";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     webpage="<button>LED2</button>";

     cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id

     sendData(closeCommand,3000,DEBUG);

 /*
  Serial.println("finding prompt");
  if(esp8266.find(">"))    //prompt offered by esp8266
  {
    Serial.println("Sending data");
   // Serial.println("found > prompt - issuing GET request");  //a debug message
    esp8266.println(data);  //this is our http GET request
  }
  else
  {
    closeConnection(connectionId);
    Serial.println("No '>' prompt received after AT+CPISEND");
  }
*/
}

String closeConnection(int connectionId){
    sendData("AT+CIPCLOSE="+String(connectionId),100,DEBUG);
}

String readUntil(String delimiter){
  String response = "";
  char c;
  unsigned int dLen = delimiter.length(),n=0;

    while(esp8266.available()&&(c= esp8266.read())){
      n= (c==delimiter[n])?n+1:0;
      if(n==dLen) break;
      response+=c;
    }
   return response;
}

void sendRaw(String data){
esp8266.print(data);
}

String sendCommand(String command){
  esp8266.print(command); // send the read character to the esp8266
  esp8266.print("\r\n");
  esp8266.flush();
}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "";
    esp8266.print(command); // send the read character to the esp8266
    esp8266.print("\r\n");
    esp8266.flush();
    long int time = millis();

    do
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }while( (time+timeout) > millis());
    if(debug)
    {
      Serial.print(response);
    }
    return response;
}

Please help, I am stuck, Is there any other cheaper & better solution ? I am only looking for Wifi.

If you are powering it using Arduino 3.3V pin it is no wonder it does not work.
ESP8266 uses more power than Arduino can provide. Power pin on arduino is about 50ma. ESP8266 in receive or send mode uses much more and either halts or restarts.
A table of ESP8266 power consumption can be found here

can you suggest power regulator which is easily available ?

any Buck Step Down Converter. There is literally gazillion of them on ebay and on... Use it to step down 5V that you get from any phone charger to 3.3V. You could also use something like this for use with breadboard

@m11404 you can easily buy a cheap 3.3V linear regulator LM1117T and use it with the Arduino 5V pin, which can supply up to 500mA; a separate 1A supply would be even better.

I already had that... I used 5v,1A adapter... &  connected esp without voltage divider... The led in esp was dim... &  not responding

I am getting yyyyyyyyy.... Similar as response if I connect external power.

make sure that your terminal baud speed is set correct. go from 9600 and up. See if that fixes it. And put the capacitor between vcc and ground.

Wait ? You connected the ESP to 5V without the voltage divider? ESP is 3.3V. You fried your ESP module.

@NccWarp9 Hey, No...Its not fried, i used voltage regulator. I also tried using 3A DC-DC Converter Step Down buck http://www.ebay.in/itm/Supper-mini-3A-DC-DC-Converter-Step-Down-buck-Power-Supply-Module-3V-5V-16V-/331854215553?hash=item4d440d7981:g:1ywAAOSwt7pXNFQz
ESP echoes back whatever i type. No error.
& it works fine if i correct directly to uno.
Baud rate is 9600 as i changed it using AT, Should i reflash & use 115200 with external power ?

I will try a 100uf capacitor.
I also monitored current  - while connected to uno it was fluctuating from 70mA to 30mA..i  don't remember exactly but there was lot of fluctuations but when i connect to external no fluctuation  , blue blinks once, red light is OK.   this is result when i connect to external power & directly to serial.
The source is rated to 2A, 5V.

If i use arduino promini with esp, it keeps resetting i believe because of less power.  & once it worked but there was lots of garbage text. & then it started resetting.
I am really thankful to you.  Thank you for replying. I didn't get notification for your comment so this was late reply.

older modules come with only 9600 and to get it to work with higher baud rates you will need to flash it with newer firmware. did you flash it with 0.9v of the firmware that has baud watchdog? http://www.xess.com/blog/esp8266-reflash/

Yes I used 0.9 of expressif. The latest one.  Initally it was 115200.. I changed it to 9600.

@NccWarp9 hey Yes I used 0.9 of expressif. The latest one. Initally it was 115200.. I changed it to 9600

Im sorry but there is nothing else. I do wonder why you use AT commands  from code.

@NccWarp9 i wonder is there any other way to communicate ?

Sure there are, Many. Currently Im testing out MQTT for ESP and it works perfectly. Also you have WebSockets and so on. You can put your own telnet on it, webserver, or program another arduino over the wifi.

@NccWarp9 I checked for mqtt, etc earlier but i thought its just build upon at library, i will try flashing it again. Really thankyou.
the mqtt firmware didn't work well in past. I will try again.
I just want to communicate arduino with ESP8266, any how.

If you wish only to communicate they I would suggest looking at ESP-Link. I find it one of the most impressive and useful pieces of code out there for ESP

@NccWarp9 I will give it a try & update you, really thankyou.


text:
Send Photo with Arduino Uno
I'm new at Arduino projects. I googled but I couldn't quite get an answer.
I've got:

Arduino Uno R3 clone
4 pin push button
3 color RGB LED Module
HC06 Bluetooth-Serial Module Card
Arduino PIC Camera Module OV7670

In my project, when the button is pushed, the Arduino takes a photo from the camera module and sends it with an HC06 Bluetooth Module to an Android device. And it receives the answer to turn on the Led green or red.
The main problem is how can I capture the photo and send it with bluetooth? I can handle the Android side.
EDIT 1
I reviewed that code: OV7670 FIFO on GitHub.
In the "Take Picture" method, I understand that the OV7670 continuously grabs frames and stores them in itself. I send it a signal to load a frame on Data Out pins. (D0-7) It loads first 8 bytes on the pins and in Arduinoo, in the for loops for height, width and byte for each pixels, I read in it from D0-7 and send a signal for next byte array.
But I can't understand how to connect the OV7670 to the Arduino. In code, there are conts called WRST, RRST, WEN, VSYNC and RCLK. On the OV7670 I've got SIOC, SIOD, VSYNC, HREF, PCLK, XCLK, D0-7, RESET and PWDN pins. How can I connect these pins like in the github link?
By the way here is my OV7670, I read there are different versions of OV7670:

Ok, so in this project I can see three main topics: 1) acquire a photo from the OV7670, 2) send data through the bluetooth module, 3) what is the best way to acquire and transfer a big image with poor hardware. So, what is your questoin related to? Did you already perform some of these steps?

Button, connectin Android and receiving-transmittin data and turn leds is okay. I cannot connect Arduino and OV7670 and can not capture frame (photo) with it.

It doesn't seem that that library is the correct one for you, since the signals are quite different. Maybe you can see what are the differences, but then you should integrate them by reading the datasheet of the OV7670 module..

Okay, there are differences between code and datasheet. But how can I use this card with Arduino? This is the subject of my question..

I have looked into something very similar and I think the reason you are finding it difficult to find information is you are viewing the full system.  Break it down into smaller chunks and you will get more chance of finding a match.  So lets look at the camera and then the rest of it.
I think that the reason you can't get an answer for this is that you can't do what you want with what you have.  My research seems to say that the OVO7670 camera needs a separate micro processor and 'special' RAM to work (can't remember what is special about the RAM at the moment).  There is a board that does this called a 'PIXY', but its not cheap.
On the plus side, connecting an Arduino to Android via blue tooth should be quite simple there should be lots of examples on how to set up the Arduino side.  You then need to define to convey your messages between your server an client and I know you aren't asking how to turn a LED on and off from an Arduino. (If you are please see the Example Blink).
Hope that helps
EDIT
I think you should have 18 pins on you OV7670.

3v3 - 3.3v
Gnd - Ground
SIOC - Input - I2C Clock
SIOD - I/O - I2C Data
VSYNC - Output - Vertical Synch
HREF - Output - Horizontal Synch
PCLK - Output - Pixel Clock
XCLK - Input - System Clock
D7 - Output - Data bit 7 (MSB)
D6 - Output - Data bit 6
D5 - Output - Data bit 5
D4 - Output - Data bit 4
D3 - Output - Data bit 3
D2 - Output - Data bit 2
D1 - Output - Data bit 1
D0 - Output - Data bit 0 (LSB)
RESET - Input - RESET - Low to reset
PWDN - Input - Power Down - High to activate


text:
Parsing using the ArduinoJson library
I am trying to parse JSON using the ArduinoJson library. The problem is that I can’t parse www.read() because it’s declared as a char. I think www.read() needs to be a string? How can I convert www.read() into a format that jsonBufffer.parseObject() can understand? Please excuse any lack of terminology. I am new to using JSON.
When I run the code I get to the point where it prints "-------------------------------------” then it does nothing.
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include <ArduinoJson.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "WLAN_SSID_HERE" // cannot be longer than 32    characters!
#define WLAN_PASS       "WLAN_PASS_HERE"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  300000      // Amount of time to wait (in milliseconds) with no data
// received before closing the connection.  If you know the server
// you're accessing is quick to respond, you can reduce this value.

// What page to grab!
#define WEBSITE      "wefeel.csiro.au"
#define WEBPAGE      "/api/emotions/primary/totals"

StaticJsonBuffer<200> jsonBuffer;

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  Serial.print(F("\nAttempting to connect to "));
  Serial.println(WLAN_SSID);
   if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
//  while (! displayConnectionDetails()) {
 //    delay(1000);
//  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE);
  Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
   }

  cc3000.printIPdotsRev(ip);

}

void loop(void)
{
  char c;
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  delay(300);
  if (www.connected()) {
    www.fastrprint(F("GET "));
    www.fastrprint(WEBPAGE);
    www.fastrprint(F(" HTTP/1.1\r\n"));
    www.fastrprint(F("Host: "));
    www.fastrprint(WEBSITE);
    www.fastrprint(F("\r\n"));
    www.fastrprint(F("\r\n"));
    www.println();
  }
  else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    //Serial.print(www.available());
    while (www.available()) {

      //Serial.print(c);
      //char json[] = www.read();
    }
  }
  c = www.read();
  Serial.print(c);
 JsonObject& root = jsonBuffer.parseObject((char*)c);
 if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
    }

  long love = root["love"];
  long other = root["other"];
  long sadness = root["sadness"];
  long anger = root["anger"];
  long joy = root["joy"];
  long surprise = root["surprise"];
  long fear = root["fear"];

  Serial.println(love);
  Serial.println(other);
  Serial.println(sadness);
  Serial.println(anger);
  Serial.println(joy);
  Serial.println(surprise);
  Serial.println(fear);

  www.stop();
  delay(100);
  www.close();
  delay(200);
 }

First you never setup the HTTP header with "Content-Type: application/json", so the data return might not be in json as you want. Secondly, you need to create a buffer to store the response back from the server within the while(www.available()) { buffer[i++]=www.read(); } (i.e. read the data char by char and store in the buffer), then you can parse the return data in the buffer with JsonObject& root=jsonBuffer.parseObject(buffer);.

There are two read methods. One that returns a single character (or error), and one that populates a buffer; you want the latter, with method signature int read(char* buf, size_t len) or some such. Read the source.
When allocating the json buffer in StaticJsonBuffer<200> jsonBuffer;
, make sure your expected json data fit in 200 bytes.

Thank you for responding to my problem. I'm assuming you would use  jsonBuffer as uint8_t *buf but what value do I use for size_t len?

no, jsonBuffer has to still be a StaticJsonBuffer. It's what you read() into that should change. Something along the lines of:
char buf[256];
size_t n_read = www.read(buf, 255);
buf[n_read] = '\0';

You need the third line because parseObject expects a nul-terminated string.

I really appreciate your help. I think Im following you but am still unclear what I need to do next. Im thinking it is calling jsonBuffer.ParseObject but I was thinking that I would have it parse n_read which seems to be incorrect? What variable should I perform the parse on?


text:
How to use printf with Arduino's serial ports without an intermediary buffer?
How to use printf with Arduino's streams without an intermediary buffer? The following seems unnecessary:
char buf[256];
sprintf(buf, ...);
Serial.print(buf);

Is there a way to connect HardwareSerial or SoftwareSerial to a libc stream or is there a custom implementation of printf that does this?

Sure - here's a Hello, World program that uses printf(). Everything that mentions "uart" is what connects printf() to your output stream. uart_putchar() does the actual outputting to ... someplace. That's what you'd modify to direct the C standard output to a different device - SofwareSerial, for instance:
// Hello, World program using printf()

#include <Arduino.h>

static FILE uartout = { 0 };   // FILE struct
static int uart_putchar(char c, FILE *stream);

void setup() {
   // For printf: fills in the UART file descriptor with pointer to putchar func.
   fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
   stdout = &uartout;

   Serial.begin(9600);
   printf("Hello, World!\n");
}

void loop( void ){
   printf("Elapsed time: %ld\n", millis());
}

// uart_putchar - char output function for printf
static int uart_putchar (char c, FILE *stream)
{
   if( c == '\n' )
      Serial.write('\r');
   Serial.write(c) ;
   return 0 ;
}


text:
What would the total current requirements be for these items?
I'm using 5 of those 8mm NeoPixels + a 5V Trinket.
I'm trying to get a rough estimate of the current requirements that would have, assuming all 5 NeoPixels were running at full brightness "white" (255 RGB).
I'm voltage-regulated to about 150 mA from the Trinket and my current hunch is that those NeoPixels need more than that, but trying to confirm it.

According to the data sheet each LED takes a maximum of 3*20mA, so you are pulling 300mA.  You  are going to need a bigger power supply :(


text:
Arduino Mega pin conflict
I am building a rather complicated model railroad crossing signal and have moved to using the Mega since I need more pins than the Uno. Upon reading the specs of the Mega on the Arduino.cc website I noticed a potential pin conflict, or not, maybe they serve a dual purpose?

External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2).
I2C: 20 (SDA) and 21 (SCL).

SDA and Interrupt 3 both function on pin 20? Likewise with Interrupt 2 and SCL?
I assume this is true, how/why do they share the same pin?

Lots of things share pins. It's normal. The "how" is that those pins are connected, internally, to multiple bits of the circuitry.
The "why" is simply because if you had a discrete pin for each possible function you would end up with a chip the size of your desk.
Pretty much every single pin on the chip has multiple functions on it.

Then can you define two things with the same pin? #define INTERRUPT_3 20 and then #define I2C_SDA 20?

You can define anything to anything. You can only use one function at a time though. After all - how would you wire the pin to both the I2C device and the interrupt source and differentiate between them?

So if I plan on using interrupts AND I2C, then effectively I can't use interrupt3?

And interrupt 2. Still, you have pin-change interrupts on every single other pin on the board...

Not on the Mega you don't.

@NickGammon Hence the "pretty much" in my answer. True, I forgot it was a Mega in the comments. I do find it bizarre that Atmel "forgot" to provide PCINT on an entire port...

Maybe they hit some complexity in the internal state machine that the processor uses, that it would take more trouble than it was worth to support it.


text:
fatal error: ESP8266WiFi.h: No such file or directory
I used platformio IDE
I did "platformio lib install 1101"
(http://platformio.org/lib/show/1101/ESP8266wifi),
I installed this: http://platformio.org/lib/show/549/WebSockets (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:

fatal error: ESP8266WiFi.h: No such file or directory fatal error:
ESP8266WiFiMulti.h: No such file or directory fatal error:
ESP8266Webserver.h: No such file or directory

Have you overridden lib_dir in platformio.ini? If yes, please remove it.

While Bhushan Patil's answer should work, it would still make future projects tedious. Instead you can add the header files to the hardware library, and use them at will, with the #include <library> syntax every other library uses in C/C++.
The PlatformIO IDE has a config file you can modify that tells the IDE where to look for libraries. You could read this file, and determine where to put your header files, such that PlatformIO could find them, or add a location to look for header files in. See this page from the PlatformIO documentation:
http://docs.platformio.org/en/latest/projectconf.html
Beyond that, you could also use the absolute path for the header file (library) you are trying to use, by doing something like
#include "/home/user/path/to/user/library.h"

Make sure ESP8266WiFi.h, ESP8266WiFiMulti.h, ESP8266Webserver.h files are located in the same directory where your *.uno file present.

I symbolic link them. It seems getting over compiled errors. Do you know how I can install arduino into platformio ide? Currently, I git clone: https://github.com/esp8266/Arduino and symbolic link in my project. Not a good idea.

Note the different capitalization: ESP8266wifi vs ESP8266WiFi. Confusing as it may be, these are actually two completely different libraries.
ekstrand/ESP8266wifi is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.
ESP8266WiFi is a library bundled with the ESP8266 core for Arduino. It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.
The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware.


text:
Can Arduino be used as an FDTI Programmer?
I would like to program my ESP 8266 WiFi module. But I don't have an FDTI right now is there any way to use Arduino Uno as FDTI Programmer then use ESP without it.

Yes. Tie the reset pin on the ISP connector low to keep the ATmega328P in reset, then you can connect pins 0 and 1 to the ESP module to communicate using the Uno's USB-UART bridge. Since the pins are labelled from the perspective of the '328P, connect TX to TX and RX to RX.


text:
My serial Monitor of the Arduino ide does not show up when running Gui?
I have created an gui in python using pyserial to communicate with Arduino but my serial monitor does not show up it says (Serial port busy) whenever I run the gui.
The gui works fine but when I want to see the printed data for that, I am using an external LCD but I was wondering if there was a way to see the data in serial monitor. If not could you explain why? I have no idea whatsoever why is this happening.

AFAIK each serial port can only be open from at most one program at a time. are you sure that arduino IDE or another application is not using this port whan you try to open it?
have you tried opening this serial port from a program like hyperTerminal? what happened?
have you tried opening with your python application another serial port?
what happened?

The problem is simple, you are dealing PySerial using the serial communication port arduino, so you can not communicate with Arduino IDE and python at the same time.
Solution:
In the program you should print python q values you need, with the Print command, so you'll see in the CMD same as you see in the Arduino serial monitor.

If an application is already using the serial port then you won't be able to reopen it.  In this case you Python GUI is communicating with the Arduino over the serial port, so the IDE can't.  Think back to when you are just using the IDE, the serial monitor is closed whenever you upload a new version of the code to the board.
So, how do you solve it.  The simplest answer is to use another serial port for the Python app to talk to the Arduino and leave the default port free for the Arduino IDE/Serial monitor.  Software serial should work, you might need to print to both serial ports from the Arduino, but you can do that by adding another function.
An alternative might be to modify your python app to rebroadcast the debug data to another serial port and then connect to this via hyper terminal.
Hope that helps.


text:
Can I use arduino's 3.3 V output directly to esp8266?
I just bought esp8266 and ftdi usb driver, I want to power the esp8266 with Arduino's 3.3 V output, is that possible?
I saw some tutorial on youtube in that they are suggesting us to use 3.3v regulator ic instead of directly power 3.3 V of Arduino or ftdi driver's 3.3 V output.
If I connect my ftdi or Arduino output directly into esp8266 is there a chance to damage the esp8266?

Which Arduino ?

arduino uno which i bought from amazon

You should search for this data yourself, but since you are saying you are a newbie I'll tell you how to find this.
First of all you should search for a document called "datasheet". On a datasheet the producer writes all the relevant data about his product.
In your case, you should search for the electrical characteristics of the ESP8266. For instance here you have one of the datasheets. On page 13, there is the "Power consumption" chart, which says that the worst case has a typical current of 170mA. I suggest you to raise it a bit; let's say you need 250mA for the ESP.
Now, the arduino. You should search for the schematic of the board or read the part number of the 3.3V regulator. Since it's easier from the schematic and they released it on the web, you can see that the part number of the 3.3V regulator is LP2985. Searching for it on google will lead you to the texas instruments webpage, with the datasheet. Here you can see that the maximum output current is 150mA, so below the required current. Answer: you can't with arduino.
As for the FT232 cable, you should search for it because there are different models. Search on google and pick the first link pointing to the ftdi website.
As an example, the TTL-232RG has this datasheet. On page 9 they say that the TTL-232RG-VSW3V3-WE has an output current of 50mA, so you can't use it. The TTL-232RG-VREG3V3-WE, on the other side, has a maximum output current of 250mA, so you can use it.
If you have further questions, just ask here ;)

The specs for the Uno say that it does not provide as much current on the 3.3V line as the specs for the ESP8266 requires. You will need to provide another regulator that can supply enough current.

Im also have a ftdi usb driver in that there is a 5v and 3.3v out ,is that possible to get that amount of current from ftdi or arduino's 5v (using a voltage devider).Im a software developer im new to arduino and esp so if i say something wrong please forgive me

Voltage dividers are not voltage regulators.

Sorry, is it possible to that by using lm1117 ic and 9v battery ?

Check this for the lm1117: http://i.imgur.com/bD1ZDU2.png

And on a side note, you can also use the lm1117 to the 5v of the Arduino like so: http://3.bp.blogspot.com/--C-w5vILMi0/VTAvOct-fKI/AAAAAAAAO5w/76zXAWUR20c/s1600/ESP8266_arduino_power_lm1117_bb.png

i know It's a delayed reply .but it might help some one else.The answer is yes. I powered up esp8266 with ardino 3.3V directly and it works fine for me.