text:
if(Serial) not working correctly on micro or pro micro
I have an arduino micro and several clone "pro micro"'s both of which are based on the 32u4, i'm trying to make my project have a debug mode which is only active when the serial port is open, the documentation states that using:
if (Serial)

on these boards should only return true if the port is open (on uart based connections it always returns true), i wrote my sketch to take advantage of that but it didn't seem to be working properly, so i stripped back to basics and wrote this sketch:
void setup() {
    // put your setup code here, to run once:
    pinMode(2, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
    if (Serial){
        digitalWrite(2, HIGH);
    }
    else{
        digitalWrite(2, LOW);
    }
}

I connected an LED to pin 2 and then tested it by connecting and disconnecting the arduino from the PC, and opening and closing the com port.
after freshly connecting the arduino to the PC the LED is off, when i open a connection to the virtual com port the LED turns on.
however i would expect the LED to go out once the port is closed, but it remains on.
My questions are:
1) have i got an out of date bootloader?
2) if so how do i check?
3) is this intended behavior and if so why?
4) is this a bug in the arduino bootloader or libraries?
5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?
Edit:
should have mentioned i'm seeing this behavior with or without a call to Serial.begin

Might need to call Serial.begin() first.

see edit to question, i get this behavior with or without a call to Serial.begin

I'd say this is intended behavior. https://www.arduino.cc/en/Serial/IfSerial

why would this be intended? "On 32u4 based boards (Leonardo, Yùn, ecc) , if (Serial) indicates wether or not the USB CDC serial connection is open. " that sounds to me that it should only return true while the port is open, so once i close it it should start returning false, yet it doesn't

It would be far simpler to enter debug mode if a certain pin was jumpered to Gnd, as that is something you can quickly set up, and test easily.

it would, if not for the fact that i'm using every last pin available for my project, thats why i'm after something else

1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

2) if so how do i check?

See above.

3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere.  See below.

5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.
The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not.  That functionality was just never designed into the protocol.
However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.
The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.
Now comes the tricky part:  You have little or no control over when those signals are asserted or not.  There are three separate factors that decide what happens:

The software being run can manually control the signals.  The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
The drivers on the computer can decide to automatically control the signals when the port is opened or closed
The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.
So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.

Thank you, this is exactly what i was trying (and failing) to find any information on

have you got any information on how i check the RTS/DTR lines in the arduino? i can't seem to find anything about it: https://www.arduino.cc/en/Reference/Serial

@JamesKent It took me many months (on and off) of research and experimentation, reading USB specifications, other peoples' source code, etc, to find just this out ;) It's not something that is commonly known.

@JamesKent The if(Serial) does it. The Arduino side is fine. It's the computer's end that is at fault.

if (_usbLineInfo.lineState > 0) result = true; is the bit of code in CDC.cpp that does it.

what does if(Serial) check? both asserted, both deasserted? how do i need to leave the port to have the arduino see it as closed?

If either are asserted (lineState is 1, 2 or 3) then it is true (connected). Otherwise if lineState is 0 (all de-asserted) then it is false (disconnected).

This is known as "hardware control" most terminal applications has support, but the default for enabled or not varies. If you want to know if USB is connected, checking for VBUS seems more stable?

I am experiencing the same problem. My environment is Windows 10 on the host side and Arduino 1.6.7 with a genuine Arduino Micro board.
In the OP's sketch, after compiling and uploading, the light does not go on until you open the serial monitor. This is as expected and shows that the Arduino side has some way of knowing that the serial monitor has started.
However if you close the serial monitor, the light stays on. It also stays on if you unplug the USB cable. It goes off when you plug the cable back in and goes back on when you restart the serial monitor.
With some further experimentation and poking around the code, I found that _usbLineInfo.lineState > 0 and thus Serial returns True if either DTR or RTS from the host is nonzero. DTR goes to 0 when the serial monitor is closed but RTS stays HIGH so Serial stays True.
The fix is to use the (undocumented) method Serial.dtr(). This is True only if the serial monitor is running.
[edit] If your system has external power so that it should keep working with the USB cable unplugged, testing Serial.dtr() works as long as you you always close the serial monitor before unplugging the USB cable. However it will remain True if the cable is unplugged before closing the serial monitor.
To detect the cable being unplugged, add the line
USBCON |= 1<<OTGPADE;
to setup(). This enables detection of an unplugged USB cable. Then in your loop
(USBSTA & (1<<VBUS))
will be True if the USB cable is plugged in and has power.

i wouldn't describe this as a fix, more of a workaround, long term i think that the CDC.cpp file needs modifying to handle different OS's ways of leaving the ports  better, which may well be only checking the state of the DTR line


text:
CAN communication with Arduino
I'm a member of a Formula SAE team and we use the Performance Electronics ECU which uses the CAN protocol with a speed of 250 kbit/s and works fine with our 2D Recording Systems Data logger, but we're trying to build a telemetry system which gathers the same data from the CAN bus using an Arduino Uno and CAN shield provided by SparkFun Electronics.
However the CAN shield we're trying to use has failed to initialise the communication with the bus. Kindly help me out on what can be done or are there any alternatives of communicating using CAN with Arduino?
P.S. The link for the CAN shield: CAN-Bus Shield Hookup Guide

Have you shecked the shield pins match the ECU connector pins? The shield is configured to match the pins on their OBDII->DB9 cable and may not match the "vanilla" CAN pinout. This will require desoldering jumpers

You may also try to add termination to the BUS

Hi Crasic, according to the schematic of the shield already has termination resistance to the bus, and regarding the connections, yes the ECU Connector pins match with the shield pins. Our data logger works fine but the shield isn't working. Also could you provide me with the info on ODBII-> DB9 cable and the "Vanilla" CAN Pinout. Thanks

I also forgot to tell that the communication protocol is SAEJ1939 and the Baud rate is 250KBPS

Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

pin 3/5 CAN bus shield schematic
pin 2/7 (Vector tools for example).

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?

I found this wiki particularly useful: CAN-Bus Shield Wiki
And yes, like CQuinson said, you have to pay attention to the pins used. I know Sparkfun is known for having an issue with which pin the CS pin is assigned to (D9 or D10).

source: Stack Exchange

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

sort: votes


text:
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?
This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

Here is the bluetooth chip I am powering:

VCC is likely an input.  What is on the other end of the yellow wire that goes off the pic?

If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.
If you use external power it provides 5v since that is what the regulator provides.
The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).

Where can I find the USB 5v pon? I've been having a hard time finding the data sheet for that particular board. Maybe I'm looking in the wrong places? I've just tried typing in the specs of the board in google but havn't gotten the specs for that board.

If it is a genuine arduino the schematic will be on the arduino website. If it is a cheap chinese copy, you are on your own. It looks like an LM1117-5, and as such will most likely be 800mA. Pon = pin translated through my tablet's onscreen keyboard. Edited it.

And then there are these concerns:  https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/

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


text:
Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?
I have an Arduino.
I'm not sure if RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?
For example, do I treat RX1 and TX0 as RX and TX in the Arduino IDE when coding?
This is the chip I have. On the chip it says "ProMini R160JAC6v" and when I program it, it programs under 5V 16MHz with ATmega 328. Notice RST RX1 and TX0 are on the top left corner.

It's not RX1 and TX0 but RXI and TXO
That is receive input and transmit output,
Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.

No, it is not mnemonical. It is about PIN numbers: 0 for RX and 1 for TX, as seen in the table here: https://www.arduino.cc/reference/en/language/functions/communication/serial/. However, you invented a good one.

Yes you treat them the same, they are the same pins.
It looks like (in the photo) you're connecting a bluetooth module.
Be careful when uploading your sketch.  If you connect something to TX/RX (pins 0 & 1) it may be necessary to disconnect it for arduino-uploading to work.
You may find it a more convenient solution to declare a SoftwareSerial on different ports and use that for the bluetooth communications.


text:
Driver shield providing 24+ pins at 100mA (for Mega 2560)
Do any shields (or similar boards) exist to let the Mega 2560 (or Due) output a full 100mA per pin on at least 24 pins, in a digital on/off fashion? I know there is a motor shield, but it looks to have only a handful of outputs. It seems very common that people need to output higher current than the MCU can provide safely (if at all), but there do not appear to be any shields for this. Of course individual transistors are fine for a few outputs, and some chips can do up to 8, but what about the rest of us who want to use all those nice pins on the Mega, Due, or similar but who need more power?

You can:

use a driver chip, e.g. ULN2803 which gives you 8 outputs of up to somewhat 500mA from 8 digital pins
use a serially addressible power+logic chip, such as TPIC6A595NE which gives you 8 outputs, each can drive 350mA, and has a built-in short circuit protection. You can cascade these, 3 chips give 24 outputs, and need only three pins to drive all 24 (or more if you use more chips) outputs.
There are 24 output devices, however not in this current range. 24 output devices are usually i2c or spi based led controllers - some of them gives you goodies like rock solid hardware PWM on all 24 ports - but none of them gives you 100mA output.

You'll likely have to use an https://www.arduino.cc/en/Main/ArduinoProtoShield with 3+ of those chips you like that do up to 8.

I was considering that. I see that the board has only one place dedicated for such a chip though. Hence, I would think this would require putting jumpers on all the pins of the 2nd and 3rd chip.


text:
Using Arduino IDE as an API
I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.
Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?
The ideal would be a self-contained library that could be linked to my C/C++ program.

Have you tried Arduino C Scaffold project?

...the scaffolding lives on Github in the Throw The Switch organization as the Arduino C Scaffold project. This should have everything you need to deploy a C project on an Arduino UNO without the Arduino IDE. If you know your way around Git, you can clone this repository and get to work. If you’d rather not mess with Git right now, you can download the latest revision of the scaffold in a zip file. Once you have the scaffold, take a look at the README. This will walk you through getting the AVR toolchain setup on your environment and describe some of the different ways to use the scaffold.
  -- https://spin.atomicobject.com/2011/10/15/taking-the-training-wheels-off-the-arduino/

Will check it out!

This seems to be targeted at plain C, not Arduino code.

For compiling and uploading Arduino code, you do not need Java, nor the
Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and
avrdude. With a proper Makefile, your program just needs to
system("make upload");

C.f. the tutorial Compiling Arduino sketches using
Makefile.
On an Ubuntu or other Debian-like OS, you would just
sudo apt-get install arduino-mk make to get everything you need installed.


text:
Arduino Due Port Not Found
I've got an arduino due and I'm having great difficulty connecting to it. The problem seems to come and go, I was using it just fine only 3 or 4 hours ago but now it just won't connect. I've got the board set to the Arduino Due Native Port and the port set to the /dev/cu.usbmodem1421 (Arduino Due Native Port). Every time I try and upload the sketch however, it gives me this error:
    Arduino: 1.6.6 (Mac OS X), Board: "Arduino Due (Native USB Port)"

Sketch uses 10,316 bytes (1%) of program storage space. Maximum is 524,288 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:130)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.Sketch.upload(Sketch.java:1178)
    at processing.app.Sketch.exportApplet(Sketch.java:1152)
    at processing.app.Sketch.exportApplet(Sketch.java:1124)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2452)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.usbmodem1421'.
    at processing.app.Serial.touchForCDCReset(Serial.java:87)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:119)
    ... 6 more
Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem1421; Method name - openPort(); Exception type - Port not found.
    at jssc.SerialPort.openPort(SerialPort.java:167)
    at processing.app.Serial.touchForCDCReset(Serial.java:81)
    ... 7 more
Error opening serial port '/dev/cu.usbmodem1421'. (Port not found)

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

Not sure what all that was but a simple restart of my computer seemed to fix it.


text:
Iterate an Object Array
I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.
Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.
#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {
    //code intentionally removed
}

void Train::move() {
    //code intentionally removed
}

const int trainCount = 2;
Train train1;
Train train2;
Train trains[trainCount] {train1, train2};

void setup() {
    Serial.begin(9600);
    train1.numOfCars = 5;
    train1.init();

    train2.numOfCars = 5;
    train2.init();
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train tr = trains[n];
        Serial.println(tr.numOfCars); //always prints 0
        tr.move();
    }
}

You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)
Train trains[trainCount] = {train1, train2};

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with new[] and use them. Like this:
#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {}
void Train::move() {}

const int trainCount = 2;
Train* trains = new Train[trainCount];

void setup() {
    // initialize trains
    for (int i = 0; i < trainCount; ++i) {
        trains[i].numOfCars = 5;
        trains[i].init();
    }
    Serial.begin(9600);
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Serial.println(trains[n].numOfCars); //always prints 0
        trains[n].move();
    }
}

Unless the Train constructor depends on other things being initialized first (in which case you would new in setup()), there is no point in using dynamic memory allocation: just declare Train trains[trainCount];.

As uint128_t has already put it, your problem is that you are creating
an array of copies. You should really avoid copying trains around,
especially if you are going to put a significant amount of data in them.
Instead, just create them once in the array, and then you can either
invoke them as array members directly (e.g. trains[0].init();) or use
references.
For example, if you initialize your trains like this:
const int trainCount = 2;
Train trains[trainCount];
Train &train1 = trains[0];
Train &train2 = trains[1];

Then the "real" trains live in the array, and train1 and train2 are
references to them. The rest of your code should work fine unchanged. I
would however suggest to avoid copying the trains in loop:
void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train &tr = trains[n];        // notice the '&'!
        Serial.println(tr.numOfCars);
        tr.move();
    }
}


text:
What isthe best programming language for embedded systems?
I would start to learn the best programming language for embedded systems to control devices. What I have heard about that is Assembly Language. I want to know if there is any better languages to code for embedded systems?

This question is doubly off topic, first, because it is not about Arduino, and second because "what is the best" questions are off-topic on all stack exchange sites as a matter of general principle.

AFAIK, only assembly, C and sometimes C++ are supported by microcontrollers. VHDL or others by FPGA's. And then you also have PLC's with their languages.
Microprocessors (i.e) Raspberry Pi or other embedded PC's run almost anything.

Try to formulate a less "opinion based" question, and ask it on general Stack Exchange, since this isn't that interesting for Arduino.SE

What I have heard about that is Assembly Language - where from? C++ is much easier to learn, and compiles into efficient code. Asking about "the best" assumes you specify criteria. What is the "best" car to buy? Depends on how many people you plan to transport, how far you plan to go, your budget, etc. Asking for "the best" without specifying any parameters makes your question unanswerable. I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

Before your question gets closed:
There is no such thing as "the best"
Assembly
Assembly can be a very powerful language. But at the cost of some:

Assembly is different per machine. https://cs.stackexchange.com/questions/46935/is-a-universal-assembly-language-for-all-computers-possible
Assembly is somewhat less readable as other programming languages in my honest opinion.
I personally feel that assembly should only be used for optimalization rather than standard use of code.

C C can be as powerful as assembly, only when used correct. In fact, in C (and C++) you can actually inline assembly. https://en.wikipedia.org/wiki/Inline_assembler
C++ C++ is mostly backwards compatible with C, any C compiler (should?) be able to interpret/compile C code. Which also means you could use inline assembly.
C++ also comes with a lot of usefull tools, though, when used wrongly it can actually backfire you. (Which is with most programming languages that allow a lot, but also give you the possibility to do a lot)
I believe, that C++'s Object Oriented code, with the somewhat backward compatiblity and a little abstraction from the machine (being able to port it to other machines) would be the way to go.
Though, a good C/assembly programmer will out-play an average C++ programmer.
What about the other languages
C/C++ could be considered as the standard for embedded devices.
Best thing would be, to ask for individual programming languages, and why one would be better than the other. Or what the differences are.
I havent yet found anything that could "compile" Java for embedded devices. Java typically runs in a "run-time evironment". Which would come down to the fact that it needs an OS or atleast some resources for the code to be run-time interpreted.
C/C++ is also known for being "hard real-time" or atleast deterministic qua timing. Which is probably because of the same reason, not needing another layer and being pre-compiled. (And not having an runtime environment)
By these arguments, I believe C++ or C or Assembly would be the best. Or atleast most widely accepted.
You should check per project, which languages are known by your developers and which other requirements there are (porting to other platforms).
And it's a bit of a taste issue. I think Object Oriented code is very usefull. But some may see it as excessive/annoying.


text:
3-Way Bluetooth Communication?
I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?
To reiterate what is going on here:
I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.
I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.
Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.
Thanks a lot!

Just a thought: If you store data in Bluetooth advertising data, you won't need to do anything fancy with Arduino 2. Have Arduino 1 update its advertising data as often as you want. Have Arduino 2 scan and get the data stored in Arduino 1's advertising data. Then, Arduino 2 can update its own advertising data with the updated data. Scanning and getting Arduino 2's data from Android is do-able. I didn't add this as an answer because I don't know if the HC-06 supports bluetooth scanning (it probably does).

Why Bluetooth? Why not WiFi? Having direct experience with both, WiFi (nodeMCU) is 100% reliable, simpler (not need to "pair" anything) and versatil (HTTP, MQTT or whatever protocol you like) and you can have multiple connections simultaneously. Bluetooth, is a little PITA.

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

Ok
So From Whatever I can Understand you could do this.

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

Why don't you change  your approach

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

Arduino to Arduino Bluetooth- http://www.martyncurrey.com/arduino-to-arduino-by-bluetooth/
Arduino to phone via Bluetooth- http://www.instructables.com/id/Connect-Arduino-Uno-to-Android-via-Bluetooth/
PS: - USE DIFFERENT PINS!


text:
Serial Monitor not displaying anything
I have a very basic script that is supposed to display something to the serial monitor but no matter what I try the serial monitor won't display anything...I;ve watched about 5 tutorials now and each one has failed to display anything. Any ideas what I'm doing wrong?
Here is my code:
char rx_byte;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

Are you typing anything into the serial monitor? What baud rate is the serial monitor set to?

I'm typing just the number 1 and 0, according to the tutorial I watched that should turn the LED on/off. The baud rate is set the same as what is in my code.

I'm typing just the number 1 and 0 - and then you pressed the Send button? Please add Serial.println ("Hello, world"); after the Serial.begin line and see if that appears in the serial monitor.

Yes then I pressed the send button. I tried putting that line in after Serial.begin and still nothing...

Well, solve that first. No point typing and pressing Send if nothing appears. What Arduino do you have? What version of the IDE?

I've got the arduino due, I can't find the version of the IDE, where would I find it? (I'm using osx)

Found it, its 1.6.6

I've got the arduino due - you might have mentioned that earlier. That has two USB ports. Which one are you using?

The one closest to the reset button, I believe its the native...

See: Getting started with the Arduino Due

Interesting, I'll try the programming port then!

Bingo, that did it, working perfectly now!

I've summarized this discussion, and my findings, in a new answer below.

Which one are you using?
The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

Programming port
For programming, the programming port is easiest to use. And you can "talk" to the serial port using Serial, like this:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Hello, world!");
  }  // end of setup

void loop ()
  {
  }  // end of loop

Native USB port
This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class SerialUSB like this:
void setup ()
  {
  SerialUSB.begin(115200);
  while (!SerialUSB) ; // wait for it to become ready
  SerialUSB.println ("Starting ...");
  }  // end of setup

unsigned long i;

void loop ()
  {
  SerialUSB.print ("Hello, world! Count = ");
  SerialUSB.println (++i);
  delay (1000);
  }  // end of loop

It also helps to wait for the serial port to become ready, as I did in setup. Otherwise you may miss the first 10 lines or so of serial output.

You have to change the baud rate at the right bottom corner of the serial monitor to 115200 which you have assigned initially.
I have tested it  and
It doesn't matter if its int/char

I have done that, still no luck.

Try replacing the line char rx_byte; with int rx_byte=0;. Use Serial.println(rx_byte,DEC);
int rx_byte=0;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte,DEC);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

Same again, nothing...


text:
MATLAB - Read from 2 SPI inputs synchronously
I am using the MATLAB Arduino Support Package to create a setup where I can read force data from a load cell and positional data from an incremental encoder - then plot them on MATLAB. It must be done at the same time in order to produce a material stress-strain curve.
I am thinking of using the SPI Device functions to do this.
Can the data from the load cell and encoder be read synchronously?

Hint: What sample frequency do you wish to achieve? Can you synchronize sampling and then read in sequence? Can you read with a higher frequency and then average to match a wanted synchronized frequency?

Yes and No.
 Synchronously in development slang means step-by-step execution. Asyncronously mean by some event.
Arduino has only one core. Even if you use interrupt, Arduino can only execute one command at once.
Best way for you I guess would be read both on Arduino and combine into single value to read at once. Just reading both with readDigitalPin  would give huge latency.

If I were to read both data inputs on Arduino and combine into a single value would there still be differences in time for those read values? Or can Arduino execute one command to both peripheral devices at the same time?

It is impossible to read both values at once with one microcontroller. Only if you combine it with external digital logic into single analog signal. But latency of reating both one by one on arduino microcontroller would be close to its frequency.

Truly parallel sampling is rarely needed.  Especially if you can separate the triggering (latching) of a reading in the peripheral from the act of subsequently transferring the latched value over SPI, it is likely you can merely trigger both in quick turn and then read them out in slightly slower turn.
But if you truly need simultaneous reading, then you will need a workaround.  The ATmega used in classic Arduinos only has one hardware SPI engine.  But you can also implement a software or "bit bang" SPI master using arbitrary digital I/O pins.
Typically this is done with single-bit GPIO operations, but if you place the critical SPI signals for both chips (probably SCLK, the others are usually only sampled at changes in that) on distinct pins of the same GPIO port, then you can use whole port operations at raw AVR level (below the Arduino API level) to drive them at effectively the same time.
To make this work, you would do the following:
1) For each SPI peripheral, figure out exactly at what transition of what part of what access sampling occurs. Make sure to include any internal setup or latency within the chip in the determination.
2) Start the access to whichever peripheral takes longer using port-wide operations which preserve the status of bits not related to this peripheral.
3) Add the access to the peripheral which takes less setup before the sampling instant by starting to include the bits connected to that in the values to be changed in the port wide GPIO operation.
4) Use a similar port-wide operation to trigger the critical sampling operation for both devices at the same time
5) Continue with whatever followup each device needs, and stop updating its pins when no more operations are needed by that device.
Do be aware that some SPI devices, particularly those which are ADC's or having ADC type behavior internally, can be quite sensitive to jitter or timing variation in the clock edges.  You may want to look at using an interrupt or even a hardware counter/time or the SPI peripheral to generate the SCLK edges, and operate the other signals with interrupt driven software slaved to that.
Again, in most cases true parallelism will not be needed.  But if it is needed methods such as this can achieve it at the cost of intricate software.


text:
Arduino Vending Machine problem
Currently I'm working on a vending machine project. The vending machine works using 3 button on LCD Keypad Shield DFRobot where 1 button of it assigned as 0.10 cent,the other two 0.20 cent and 0.50 cent respectively. My problem here is how can my system keep track on the balance/coin inserted so that whenever I pressed button 1 = balance 0.10 then later I pressed button 2 = balance 0.30 (because 0.20 cent added to the system). Or if you have a better idea for my code, that should be great. This is my code so far:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5
    volatile float balance = 0.00;
    float number1 = 0.10;
    float number2 = 0.20;
    float number3 = 0.50;
    int read_LCD_buttons()
    {
    adc_key_in = analogRead(0);      // read the value from the sensor
    if (adc_key_in > 1000) return btnNONE;
    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 195)  return btnUP;
    if (adc_key_in < 380)  return btnDOWN;
    if (adc_key_in < 555)  return btnLEFT;
    if (adc_key_in < 790)  return btnSELECT;
    return btnNONE;
    }

    void setup()
    {
    lcd.begin(16, 2);
    lcd.setCursor(0,0);
    lcd.print("TouchNGo Machine");
    }

    void loop()
    {
    lcd.setCursor(0,1);
    lcd.print("Balance=");
    lcd.setCursor(10,1);
    lcd_key = read_LCD_buttons();
    balance = 0.00 ;

    switch(lcd_key)
    {
    case(btnLEFT):
    {
    balance = balance + number1  ;
    lcd.print("RM");
    lcd.println(balance);
    break;
    }
    case(btnRIGHT):
    {
    balance = balance + number2 ;

    lcd.print("RM");
    lcd.println(balance);
    break;
    }
    case(btnUP):
    {
    balance = balance + number3  ;
    lcd.print("RM");
    lcd.println(balance);
    break;
    }
    }
    }

I would love to hear any comment from you guys.Thanks for the help!

What's wrong with your current code?

Remove "balance = 0.0;" from you main loop.  It's always clearing your balance.

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


text:
Regarding using I2C with Arduino for Silicon Micro-structure 5852 D 1.5 psi
I am trying to get output from a sensor (micro-structure 5852D), but I only get two outputs: 11 and 255 for even applying pressure.
The following is my code, please show me how to over come this problem.
#include "Wire.h"
#define addrs 0x5F // I2C bus address

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

void loop()
{

   byte lobyte;
   byte hibyte;
   int Press;

   Wire.beginTransmission(addrs);
   Wire.write(1);
   int x = Wire.endTransmission();

   Serial.print("endTransmission: ");
   Serial.println(x, DEC);

   Wire.requestFrom(addrs, 2); // contents of your first two registers
   while(Wire.available() < 2 );          // Check for data from slave
   {
      delay(1000);
      lobyte = Wire.read();       // Read press high byte
      Serial.println(lobyte, DEC);
      hibyte = Wire.read();      // Read press low byte
      Serial.println(hibyte, DEC);

      Press = toPressure(hibyte, lobyte);
      Serial.print("Pressure: ");
      Serial.println(Press);

      delay(1000);
   }

}

float toPressure(byte hi, byte lo)
{
  int a = (hi * 256 + lo) & 0x3FFF;  // see pdf, mask 14 bit

  float rv = (a - 116)* 0.8606; // faster //(t - 1638.0) / 30.84 + 600.0
  return rv;

}

It's Silicon Microstructures SM5852, not "micro-structure 5852D".

You need to tell us more about the specific sensor you are using. There are currently 7 SM5852 variants for different measurements and pressure ranges being sold. Where did you find the I2C specifications? I have looked at all the datasheets I could find and there is no mention of the I2C addressing or of the internal registers and commands.

Thanks James For your kind replay, here we are sending your link for your reference

http://www.datasheetlib.com/datasheet/1139457/sm5852-015-d-3-lr_smi-silicon-microstructures-inc.html?page=5#datasheet

Sensor gives 2 out put 1 Analog ( 2.5 to 4v for 1.5psi) and digital. ( which include SCL and SDA pins ) we tried hard but we dosent get proper variable signals proportional to pressure. At same time Analog signal shows variation in V. so its sign that sensor is in working condition. As per digram we used all R and Capacitors in VDD and SCL,SDA took out sensor addres at I2C we got it 0x5F . but dosent indestad that what is went wrong in whole system, and its not working as per expectation. please give us your support to overcome problem.

I have previously seen that datasheet too. It doesn't explain anything related to the I2C interface (except the pinout). Which SM5852 variant do you use out of that list of seven,  "SM5852-015-D-3-LR"? If I understood you correctly, you don't know how to access the I2C interface, and so you are trying to reverse engineer it?

I finally found it. Here is an application note on how to access the sensor digital interface: http://www.servoflo.com/download-archive/application-notes/download/373/788/17

Did you ever get it working? I'm going to build an arduino library to handle the SM58XX series of sensors, but it will take at least 10 days for it to get here. What are you building with this sensor?

Try using HEX values to access the device and its registers. Ex. Instead of 95, use 0x5f

The issues in your code:

When communicating with the sensor, the sensor expects a register address after the device address. Instead of providing it the register address, you sent the number of bytes you would like to receive. Good guess, but unfortunately the device was not designed that way.
You did not combine the least significant bits and most significant bits of the sensor output correctly. The LSB contains the 6 (not 8) least significant bits, while the MSB contains the 6 most significant bits. You first combined them like 00MMMMMM00LLLLLL (where bits marked L come from the LSB and bits marked M come from the MSB), and then masked off the upper two bits as in MMMMMM00LLLLLL. The proper way would have been to only left shift the MSB 6 bits, producing 0000MMMMMMLLLLLL, and then masking away the upper 4 bits leaving MMMMMMLLLLLL.
You should avoid 32 bit floating point math on 8-bit microcontrollers at all costs unless you have a huge amount of processor cycles to spare.

In order to read data from the sensor you must first select the register you want to read. To select a register you must first send the device address (95 in decimal, 5F in hexadecimal) with the write request bit set, and then the register address of the byte you want to read.
You can then read the contents of the selected register by first sending the device address, this time with the write request bit clear, and then receiving one byte of data immediately followed by a not acknowledge (NACK) to end the transmission.
The internal registers are organized as in the following table:

Here is my take on the code. It compiles fine, but obviously I cannot test if it actually works as I don't have the sensor. I removed the scaling routine, as it would be wise to first get it working to some level before implementing less essential features.
#include "Wire.h"
#include <stdint.h>

#define SENSOR_I2C_ADDR 95
#define SENSOR_REG_PRESSURE_LSB 128
#define SENSOR_REG_PRESSURE_MSB 129

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

void loop()
{
    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the least
    Wire.write(SENSOR_REG_PRESSURE_LSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, false);    //Request 1 byte of data, followed by a repeated start

    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the most
    Wire.write(SENSOR_REG_PRESSURE_MSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, true);     //Request 1 byte of data, followed by a stop, ending the transaction.

    uint16_t pressureRaw;

    //There should now be two bytes of data in the receive buffer.
    if(Wire.available() == 2)
    {
        uint8_t lsb = Wire.read();                  //The first byte contains the 6 least significant bits
        uint16_t msb = Wire.read();                 //The second byte contains the 6 most significant bits
        pressureRaw = (msb << 6 | lsb) & 0x0FFF;    //The most significant bits are aligned and combined with the
                                                    //..least significant bits. As the resulting value only has
                                                    //..12 bits of precision the upper 4 bits are masked to zero.

        Serial.print("Raw pressure value: ");
        Serial.println(pressureRaw);
    }
    else                                            //If more or less than 2 bytes have been received something isn't right.
    {
        while(Wire.available())                     //Clear the buffer
            Wire.read();
        Serial.println("I2C transaction error");
    }
    delay(1000);
}

For some unfathomable reason Silicon Microstructures decided to not include the I2C interface specification in the datasheet itself. The information is instead found in a separate application note.
EDIT:
Apparently Wire.flush() does absolutely nothing. Implementation from Wire.cpp:
void TwoWire::flush(void)
{
    // XXX: to be implemented.
}

And no, the implementation isn't in the base class either: virtual void flush() = 0;. To work around this, I replaced the flush call with a read() loop.

Thanks I do try this , and replay you what dose come it out!!!!!

Hi james we were working as per your solution but got result as lsb going increasingly form 3 to 61 at 0 mbar pressure and msb remains constant 65535 cont.so got confused how to get exact output.Please help in another way. Thanx in advance.

@ShripadPuntambekar I cannot help in any other way, as I don't have the sensor. My code only outputs the combined value, so you must have modified the code to get a separate byte with the high bits and another with the low bits. Could you please test if my code works, without modifying it? I found a possible source for bugs in the arduino Wire library which I worked around in the update of the above code, so please copy the above code again.

Sorry if I'm late to the party. I solved this years ago. Here's my YT video demo with a google drive link to the code in the video description. It works with the entire SM58XX series of sensors. Just input the parameters for your particular model in the top lines of the code and you'll be off to the races.
https://www.youtube.com/watch?v=Xb2J1puSOwk

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


text:
Multiple non-blocking countdown timers?
I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.
Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking delay() function is no longer feasible.
How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?

Would a non-blocking timer solution work?

Yes.  Your "timer" doesn't have to be anything more than a start time from millis() and a flag.  Then your loop just compares the start time to the current millis() value, and if it's more than the interval you wanted, do the "thing".  In code:
uint32_t startTime;
bool waiting = false;
const uint32_t PUMP_DURATION = 30000UL;

void setup()
{
  // start the "timer"
  startTime = millis();
  waiting = true;
}

void loop()
{
  if (waiting && (millis() - startTime >= PUMP_DURATION)) {
    waiting = false;
    // do something now!
    foo();
  }

The flag keeps it from checking when the pump isn't running.
If you have multiple timed things, just make another set of variables (i.e., startTime2 and waiting2).  Give 'em better names, eh?
There are also Arduino libraries that encapsulate this common design pattern.  TimeMark is one.
Here's some sample code on the Arduino forum.

30 seconds after the program starts the condition (millis() - startTime >= PUMP_DURATION) will always be true.

Yes... and?  This is a technique for (re)starting the timer and detecting the expiration.  It should be casual to the most obvious observer that this is the minimal demonstration of the technique.  Different intervals, different starts, restarting, multiple timers, etc., are left as an exercise for the reader.  -_-

The "blink-without-delay"-pattern shows how this can be solved but with several time periods and logic this becomes complex. Some abstraction is needed. The Timemark library provides a solution. Belows is the logic for a single sensor-relay pair with a state trace to serial:
#include <Timemark.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
Timemark turnOff(TURN_OFF_TIMEOUT);
const int sensorPin = 2;
const int relayPin = 3;

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

  pinMode(sensorPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  trace.start();
}

void loop()
{
  if (trace.expired()) {
    Serial.print(millis());
    Serial.print(F(":sensor="));
    Serial.print(digitalRead(sensorPin));
    Serial.print(F(", relay="));
    Serial.println(digitalRead(relayPin));
  }

  if (digitalRead(sensorPin) == LOW) {
    digitalWrite(relayPin, HIGH);
    turnOff.start();
  }
  else if (turnOff.expired()) {
    digitalWrite(relayPin, LOW);
  }
}

Expanding to three sensor-relays becomes:
#include <Timemark.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
const int CONTROL_MAX = 3;
Timemark turnOff[CONTROL_MAX];
const int sensorPin[CONTROL_MAX] = { 2, 4, 6 };
const int relayPin[CONTROL_MAX] = { 3, 5, 7 };

void setup()
{
  for (int i = 0; i < CONTROL_MAX; i++) {
    turnOff[i].limitMillis(TURN_OFF_TIMEOUT);
    pinMode(sensorPin[i], INPUT_PULLUP);
    pinMode(relayPin[i], OUTPUT);
    digitalWrite(relayPin[i], LOW);
  }
}

void loop()
{
  for (int i = 0; i < CONTROL_MAX; i++) {
    if (digitalRead(sensorPin[i]) == LOW) {
      digitalWrite(relayPin[i], HIGH);
      turnOff[i].start();
    }
    else if (turnOff[i].expired()) {
      digitalWrite(relayPin[i], LOW);
    }
  }
}

An alternative solution is to use the Scheduler library. Below is a rewrite using template functions and a controller task per sensor-relay pair.
#include <Scheduler.h>

const uint32_t TURN_OFF_TIMEOUT = 30000L;
const uint32_t DEBOUNCE_TIMEOUT = 40L;

template<const int sensorPin, const int relayPin> void setupController()
{
  pinMode(sensorPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);
}

template<const int sensorPin, const int relayPin> void loopController()
{
  if (digitalRead(sensorPin) == LOW) {
    digitalWrite(relayPin, HIGH);
    while (digitalRead(sensorPin) == LOW) delay(DEBOUNCE_TIMEOUT);
    delay(TURN_OFF_TIMEOUT);
    digitalWrite(relayPin, LOW);
  }
  yield();
}

void setup()
{
  Scheduler.start(setupController<2,3>, loopController<2,3>);
  Scheduler.start(setupController<4,5>, loopController<4,5>);
  Scheduler.start(setupController<6,7>, loopController<6,7>);
}

void loop()
{
  yield();
}

Please note that the Scheduler requires yield() or delay() to switch between the tasks.
Cheers!

You might use something like this:
#define AMOUNT_OF_TIMERS 10
unsigned int timer[AMOUNT_OF_TIMERS];
unsigned int sensors[AMOUNT_OF_TIMERS];
unsigned int pumps[AMOUNT_OF_TIMERS];
void setup()
{
  sensors[0] = 1;
  sensors[1] = 2;
  sensors[2...
  ......s[9] = 12;
  pumps[0] = 13;
  pumps[1....
  ....s[9] = 22;
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    PinMode(sensors[i],INPUT);
    PinMode(pumps[i],OUTPUT);
  }
}

void loop()
{
  checkPins();
  decreaseTimers();
  delay(1000);
}

void checkPins(){
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    if(digitalRead(sensors[i])
    pump[i] = 30;
  }
}

void decreaseTimers(){
  for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
    if(timer[i]>0)
    timer--;
  }
}

Personally, I think, handling the timing events in an interrupt is way better. Which might also be for the sensor inputs.
It's not the neatest thing, but it will do.
Using interrupts should make it even more efficient.

You should use interrupts.
You might use unsigned chars to preserve extra RAM.
You should adjust the timers/delay. (set timer to 300, and delay to 100ms) for better result.

Using info from every suggestion, I've so far come up with the following.  I may not need to touch this code again for years and years (or a new house owner may need to look at it should I move out), so I tried to comment it as much as possible.
I don't like that I've repeated so much code in the readFloatSensor functions, but this is where I am so far.  How can I eliminate the code duplication?  I believe I could use arrays and for loops but now I've entered another grey area for my knowledge level.
// PumpController.ino

// ----CONSTANTS
// ----Edit these if you need to change the pin layout or pump duration

#define RELAY_ON 0                     // The pump relays are active-LOW; on when LOW (0)
#define RELAY_OFF 1                    // and off when HIGH (1). These #defines just help keep track.

const int pumpRelayPin1 =  12;         // Pin numbers for the pump relays
const int pumpRelayPin2 =  11;
const int pumpRelayPin3 =  10;

const int floatSensorPin1 = 7;         // Pin numbers for the float sensors
const int floatSensorPin2 = 8;
const int floatSensorPin3 = 9;

const int pumpDuration = 500;          // Number of millisecs that the pumps run
                                       // after the float sensors no longer detect water

// ----VARIABLES

byte pumpState1 = RELAY_OFF;           // Used to record whether the pumps are on or off
byte pumpState2 = RELAY_OFF;           // (default to HIGH/OFF)
byte pumpState3 = RELAY_OFF;

unsigned long currentMillis = 0;       // Stores the value of millis() in each iteration of loop()

unsigned long pumpTimerMillis1 = 0;    // Stores the times when the float sensors were last triggered
unsigned long pumpTimerMillis2 = 0;
unsigned long pumpTimerMillis3 = 0;

// ----SETUP (Sets up the pins at startup/reset)

void setup()
{

    // Debug
    Serial.begin(9600);
    Serial.println("Starting PumpController.ino");

    // Pump relays are active-LOW. Initialize pump
    // pins HIGH so the relays are inactive at startup/reset
    digitalWrite(pumpRelayPin1, RELAY_OFF);
    digitalWrite(pumpRelayPin2, RELAY_OFF);
    digitalWrite(pumpRelayPin3, RELAY_OFF);

    // THEN set the pins as outputs
    pinMode(pumpRelayPin1, OUTPUT);
    pinMode(pumpRelayPin2, OUTPUT);
    pinMode(pumpRelayPin3, OUTPUT);

    // Set the float sensor pins as inputs and use the built-in pullup resistors
    pinMode(floatSensorPin1, INPUT_PULLUP);
    pinMode(floatSensorPin2, INPUT_PULLUP);
    pinMode(floatSensorPin3, INPUT_PULLUP);

}

// ----MAIN LOOP

void loop()
{
    // Get the current clock count

    currentMillis = millis() + pumpDuration;       // We add the countdown timer duration to
                                                   // the clock to prevent the pumps from
                                                   // running at boot time, while the clock
                                                   // counter is still below the timer value

    // Call the functions that do the work

    readFloatSensor1();             // check each float sensor and decide whether
    readFloatSensor2();             // to start the pump and countdown timer
    readFloatSensor3();
    triggerPumps();                 // Actually toggles the relay pins based on
}                                   // the data from the above functions.

// ----WORKER FUNCTIONS

void readFloatSensor1()
{
    if (digitalRead(floatSensorPin1) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState1 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis1 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis1 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState1 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis1 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void readFloatSensor2()
{
    if (digitalRead(floatSensorPin2) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState2 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis2 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis2 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState2 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis2 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void readFloatSensor3()
{
    if (digitalRead(floatSensorPin3) == LOW)   // If the float sensor is tripped (pulled low)
    {
        pumpState3 = RELAY_ON;                 // then trigger the pump relay pin
        pumpTimerMillis3 = currentMillis;      // and set the pump countdown timer to the current clock time
    }

    if (currentMillis - pumpTimerMillis3 >= pumpDuration)   // If the countdown timer has expired,
    {
        pumpState3 = RELAY_OFF;                             // then turn off the pump relay pin
        pumpTimerMillis3 = 0;                               // and reset the timer to 0 for the next trigger
    }
}

//========

void triggerPumps()
{
    // Toggle the pump relay pins on and off based on
    // pumpState from the readFloatSensor functions

    digitalWrite(pumpRelayPin1, pumpState1);
    digitalWrite(pumpRelayPin2, pumpState2);
    digitalWrite(pumpRelayPin3, pumpState3);
}

//=====END

With your regard to the concern about duplication, you can make a generic sensor function and pass it the pins for the sensor of interest - see for example how so many peripheral libraries are instantiated with pin assignments in their constructor.  Or you could put all of each pumps information in a struct, or go a step further and define a pump object you instantiate three of.  Then you put those in an array and call the appropriate methods in turn...


text:
Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350)
I am working on a project for tracking cars. I am using an Arduino UNO to receive the position from GPS/GPRS shield. I am OK on obtaining the coordinates position.
Now I need to send the position to a webserver and then show it on a webpage using the Google Maps API. Which accepts it in a POST or GET method.
Here is the shield model:
U-blox Sara G-350
and this is its manual here
Here is my approach:
#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial gprsSerial(7 ,8);

void setup() {
  // put your setup code here, to run once:
  gprsSerial.begin(19200);
  Serial.begin(19200);
  delay(2000);

 gprsSerial.println("AT+CGDCONT=3,\"IP\",\"weborange\"");
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UHTTP=2,1,\"www.navtec.16mb.com\"");
                   //AT+UHTTP=<profile_id>,<op_code>,<HTTP_server_name>
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0,5,80");
 toSerial();
 delay(2000);

}

void loop() {

 //gprsSerial.println("AT+UHTTP=2,1,\"submit\"");
                    //AT+UHTTP=<profile_id>,<op_code>,<param_val>[,<param_val1>]
 //toSerial();
 //delay(2000);

 gprsSerial.println("AT+UHTTPC=2,1,\"/add.php\",\"filename\"");  //Problem here!!!!!!!!
                   //AT+UHTTPC=<profile_id>,<http_command>,<path>,<filename>[,<param1>[,<param2>[,<param3>]]]
 toSerial();
 delay(2000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }

}

This is what I get:

+CGDCONT=3,"IP","weborange"
OK
  +UHTTP=0
OK
  +UHTTP=2,1,"www.navtec.16mb.com"
OK
  +UHTTP=0,5,80
OK
  +UHTTPC=2,1,/add.php,filename
ERROR
  +UHTTPC=2,1,/add.php,filename
ERROR
  +UHTTPC=2,1,/add.php,filename
ERROR
  +UHTTPC=2,1,/add.php,filename
ERROR ...

Thanks for your time, I am waiting for your support, any ideas could help. Sorry for my bad English

The examples in the manual have quotes around the PHP file and the filename - just like you have for the FQDN entry. Maybe you should add them...?

Thank you for your support, but my problem is in the meaning and  perpose of responseFilename and how could i work with it?

Your problem is that you have an error. The filename is where to store the response in the internal filesystem, and the word filename is perfectly valid - as long as you use quotes around your strings.

even when  i add the quotes it still giving me an error. please check my new modification in code.

Try using AT+UHTTPER to get the error code from the request, see if that helps.

it work perfectly for me right now,I just get my error with this command.Thanks again @Majenko .I will add the new code.

I worked on a project similar to yours. I think you forgot to establish a connection first.
Just add those lines of code at the top of setup() method:
 gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
 toSerial();
 delay(2000);
  gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSDA=2,3");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSND=2,0");
 toSerial();
 delay(2000);

I hope it works for you. Else, you can use AT+UHTTPER=2 after all to check for error source.


text:
Did I fry my ESP8266 module or was it something wrong with it?
I was trying to connect my Arduino Nano to my home Wi-Fi. To do that, I connected my Arduino to ESP8266 module.
I connected pins
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | RXD
D11      | TXD
GND      | GND

to connect to Wi-Fi, I used code which I found on internet.
What I'm getting is "FAILED - Timeout exceeded" which indicates there is no response from the ESP module. Is it possible I did something wrong and I fried it, or I connected it wrong? Or maybe it does not have enough power (I'm powering my Arduino via computer USB port)? I also read reviews which indicates customers who bought similar product from different vendors they had issues with firmware. Is it possible I have same problem?
Code
#include <SoftwareSerial.h>
SoftwareSerial softSerial(10, 11); // RX, TX
String WSSID = "xxxxxxxxxxxx";
String WPASS = "xxxxxxxxxxxx";
bool r;

void setup() {
  /* SETUP SERIAL COMMUNICATION */
  espSerialSetup();
  delay(2000); // Without this delay, sometimes, the program will not start until Serial Monitor is connected
  r = espSendCommand( "AT+CIFSR" , "OK" , 5000 );
  if( !r ) {
    r = espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
    r = espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
  }
}

void loop(){
  r = espSendCommand( "AT+CIPSTART=\"TCP\",\"108.59.11.102\",80" , "OK" , 5000 );
  String getRequest = "GET /shiznic/ HTTP/1.1\r\nHost: www.rootpower.com\r\n";
  int getRequestLength = getRequest.length() + 2; // add 2 because \r\n will be appended by SoftwareSerial.println().
  r = espSendCommand( "AT+CIPSEND=" + String(getRequestLength) , "OK" , 5000 );
  r = espSendCommand( getRequest , "+IPD" , 15000 );
  //r = espSendCommand( getRequest , "world" , 15000 ); // page should respond with Hello, world.
  if( !r ) {
    Serial.println( "Something wrong...Attempting reset...");
    espSendCommand( "AT+RST" , "ready" , 20000);
    espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
    espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
  }
  delay(3000);
}

void espSerialSetup() {

  // change baud rate so SoftwareSerial works better -- need a certain version of ESP for this to work and be retained after power cycle
  // make sure Serial Monitor port speed is set to 9600
  softSerial.begin(115200); // default baud rate for ESP8266
  delay(1000);
  softSerial.println("AT+CIOBAUD=9600");
  delay(1000);
  softSerial.begin(9600);
  Serial.begin(9600);
}

bool espSendCommand(String cmd, String goodResponse, unsigned long timeout) {
  Serial.println("espSendCommand( " + cmd + " , " + goodResponse + " , " + String(timeout) + " )" );
  softSerial.println(cmd);
  unsigned long tnow = millis();
  unsigned long tstart = millis();
  unsigned long execTime = 0;
  String response = "";
  char c;
  while( true ) {
    if( tnow > tstart + timeout ) {
      Serial.println("espSendCommand: FAILED - Timeout exceeded " + String(timeout) + " seconds" );
      if( response.length() > 0 ) {
        Serial.println("espSendCommand: RESPONSE:");
        Serial.println( response );
      } else {
        Serial.println("espSendCommand: NO RESPONSE");
      }
      return false;
    }
    c = softSerial.read();
    if( c >= 0 ) {
      response += String(c);
      if( response.indexOf(goodResponse) >= 0 ) {

        execTime = ( millis() - tstart );
        Serial.println("espSendCommand: SUCCESS - Response time: " + String(execTime) + "ms");
        Serial.println("espSendCommand: RESPONSE:");
        Serial.println(response);
        while(softSerial.available() > 0) {
          Serial.write(softSerial.read());
        }
        return true;
      }
    }
    tnow = millis();
  }
}

UPDATE
I changed connections to
  D11      | RXD
  D10      | TXD
and i also simplified my code
#include <SoftwareSerial.h>

SoftwareSerial esp(10, 11);

void setup() {
   Serial.begin(115200);
  while (!Serial);
  Serial.println("Started");
  esp.begin(115200);
  esp.write("AT\r\n");
}

void loop() {
  if (esp.available()) {
    Serial.write(esp.read());
  }

  if (Serial.available()) {
    esp.write(Serial.read());
  }
}

now I'm sending basic AT command to test connection, and still not getting any response. LED on ESP module is on, so I'm assuming it is working.

What kind of ESP8266 module? There are about 8 of them and they all have different wiring requirements.

@Majenko I'm using ESP-01

By the looks of the information you have provided, it looks as though you have not made the crossed serial connection: rx-tx tx-rx.
Your wiring:
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | RXD
D11      | TXD
GND      | GND

And when you intialize the software serial library:
SoftwareSerial softSerial(10, 11); // RX, TX

You declare D10 as RX and then connect it to the ESPs RX and ditto for the TX line.
What you need to do is the following:
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | TXD   //change to this
D11      | RXD   //change to this
GND      | GND

Also you need to ensure that the arduino TX line does not exceed 3.3V you can use a voltage divider, logic-level shifter board or a 74LVC245. This is important as the 5V arduino pins will damage a 3.3V device. This is a note as arduino nano is a 5V device from what I know(I may be corrected).

I swap connections, and i connected D10 to TXD and D11 to RXD as you suggested, but there is no change. I'm not an expert on Arduino, and I heard same thing about voltage, but i have two power pins, one with 3.3V and one with 5V. So I assume 3.3 from board should be fine.

If it is a 5V arduino, as in the voltage that the pins on the microcontroller go when set to HIGH, you will need to have a voltage divider as 5V WILL damage the ESP. Could you specify the exact model of you Arduino board? The 3.3V form the boards power is fine for the ESP power. The problem is if the 5V pin was exposed to the ESP pin.

I have clone of Arduino Nano v3, which as I said has 3.3v output. By any chance do you know best way to check is my ESP is fried or is it firmware problem?

You can use an arduino as a USB to serial device by bypassing the MCU and then using the terminal to send commands to the esp and see the response, also you can change baud rates to see where it is. This article would describe what I suggested, and I think there are programs people have made to reflash the firmware on theses things.

I tried to recreate same thing what was in that question, and i failed. When he cross cennected RX and TX, and he got something in response, and i didn't got anything. I don't think it is something which i did , as i got another one from same vendor, and i have same problems. I also tried to connect ESP directly to PC using FTDI module, but same issue, no response. do you have any idea what should be my next step?

What I could recommend then is attempt to see if you can flash new firmware onto the esp, follow http://www.esp8266.com/wiki/doku.php?id=loading_firmware, its from the esp forums so it is probably the most reliably source. Also I think there is probably a FAQ there to you can also check if it has any other ideas not mentioned here, might be worth a shot if the firmware doesn't fix it.

As far as I know, the 3.3v on the Arduino board might not have enough current for the ESP module, as it is very 'power hungry'.
I've had some hard time making my modules work properly, and your problem could be a number of things.
I will stick to Ockam's razor principle and go by the simple side.
In your code you are using 9600 baud,but the ESP8266 'base' speed is 115200. Try that speed (and CR+LF) also on your Usb cable and it might work.

have you looked at update? in that code i'm using 115200baud. I also connected to external power source which was around 3.15V and 0.65A. Still same result.

Oh, sorry, I haven't noticed. I still think it is not fried, it might have something to do with firmware update, my modules were stuck for a while untill I figured how to do it properly. Check this page for some details: http://www.electrodragon.com/w/Category:ESP8266_Firmware_and_SDK . Also, take a look at the ESPlorer IDE, http://esp8266.ru/esplorer/  (you need to connect GPIO0 to GND when flashing)

actually i'm getting somewhere, i think previous arduino was duff, now i'm getting some response, but it is meaningless crap. I tried using different boudrates  but still nothing.

That's a good sign, I am even more convinced it is about firmware update.


text:
ESP 8266 web server using arduino
I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.

"I do not want to use only the ESP" -- you know you can use the Arduino tooling and all with it? Also, "It gets rgb values through URL and changes an rgb led's value" sounds like it's not a web server, but a client?

Yes but I want a lot of pins like an arduino mega

The ESP communicates using the UART, not SPI. It uses modem-like AT commands. Unless you write your own ESP firmware, in which case how it communicates is up to you - and so is the accompanying Arduino library.

So, the spi pins on the ESP are for master? And what libraries are there to use with serial?

Yes, the SPI pins are for use when you write your own firmware for the ESP. There are a number of libraries around for serial - google is your friend. Or you can just do it manually without a library, the protocol is simple enough.

The following link is a great resource for learning how to use the WiFi module.  It has all the commands you are likely to need.  The guide is written with the intent that the user will use the module as a standalone device without the Arduino, but at the end of the guide the commands given are all the same.  This is the reference I use for projects like this.  ESP8622 Quick Start Guide


text:
error parsing data from server using arduino uno and cc3000 shield
I'm using arduino uno with cc3000 shield and I'm trying to get some sort of data from my server but I only get some of it and the remaining part is delivered after so long, when I send the request I get this:
HTTP/1.1 200 OK.
Date: Sun, 14 Feb 2016 14:00:46 GMT.
Server: Apache.
Last-Modified: Sun, 14 Feb 2016 11:58:31 GMT.
Accept-Ranges: bytes.
Content-Length: 16.
Keep-Alive: timeout=2, max=100.
Connection: Keep-Alive.
Content-Type: application/json.

and the full data should look like this:
HTTP/1.1 200 OK.
Date: Sun, 14 Feb 2016 13:59:26 GMT.
Server: Apache.
Last-Modified: Sun, 14 Feb 2016 11:58:31 GMT.
Accept-Ranges: bytes.
Content-Length: 16.
Keep-Alive: timeout=2, max=100.
Connection: Keep-Alive.
Content-Type: application/json.
{"light": "off"}

the {"light": "off"} part takes too long to get parsed to my code.
I'm using this code:
#include <SPI.h>
#include <SFE_CC3000.h>
#include <SFE_CC3000_Client.h>
#include <ArduinoJson.h>

// Pins
#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       5   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Connection info data lengths
#define IP_ADDR_LEN     4   // Length of IP address in bytes

// Constants
char ap_ssid[] = "xxxxx";                  // SSID of network
char ap_password[] = {0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX};          // Password of network
unsigned int ap_security = WLAN_SEC_WEP; // Security of network
unsigned int timeout = 30000;             // Milliseconds

#define SERVER "XXXXX"
#define DIRECTORY      "/esp8266pir/light.json"

const int pin        = 2;
#define IDLE_TIMEOUT_MS  5000

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

void setup() {

  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);

  ConnectionInfo connection_info;
  int i;

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("---------------------------");
  Serial.println("SparkFun CC3000 - WebClient");
  Serial.println("---------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Connect using DHCP
  Serial.print("Connecting to SSID: ");
  Serial.println(ap_ssid);
  if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
    Serial.println("Error: Could not connect to AP");
  }

  // Gather connection details and print IP address
  if ( !wifi.getConnectionInfo(connection_info) ) {
    Serial.println("Error: Could not obtain connection details");
  } else {
    Serial.print("IP Address: ");
    for (i = 0; i < IP_ADDR_LEN; i++) {
      Serial.print(connection_info.ip_address[i]);
      if ( i < IP_ADDR_LEN - 1 ) {
        Serial.print(".");
      }
    }
    Serial.println();
  }
}

void loop() {
  send_request();
}

void send_request () {

  client.connect(SERVER, 80);
  if (client.connected())
  {
    client.print(F("GET "));
    client.print(DIRECTORY);
    client.print(F(" HTTP/1.1\r\n"));
    client.print(F("Host: ")); client.print(SERVER); client.print(F("\r\n"));
    client.print(F("Connection: keep-alive\r\n\r\n"));
    client.println();
  }
  else
  {
    Serial.print(F("failed to connect"));
    return;
  }
  // read response
  String section="header";
  unsigned long lastRead = millis();
  while (client.connected()&& (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
    // we’ll parse the HTML body here
    if (section=="header") { // headers..
      Serial.print(".");
      if (line=="\n") { // skips the empty space at the beginning
        section="json";
      }
    }
    else if (section=="json") {  // print the good stuff
      section="ignore";
      String result = line.substring(1);

      // Parse JSON
      int size = result.length() + 1;
      char json[size];
      result.toCharArray(json, size);
      StaticJsonBuffer<200> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }

      // Make the decision to turn off or on the LED
      if (strcmp(json_parsed["light"], "on") == 0) {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      }
      else {
        digitalWrite(pin, LOW);
        Serial.println("led off");
      }
    }
  lastRead = millis();
  }
  }
}

and here is my light.json code:
<?php
$light = $_GET['light'];
if($light == "on") {
  $file = fopen("light.json", "w") or die("can't open file");
  fwrite($file, '{"light": "on"}');
  fclose($file);
}
else if ($light == "off") {
  $file = fopen("light.json", "w") or die("can't open file");
  fwrite($file, '{"light": "off"}');
  fclose($file);
}
?>

Turn On
Turn Off

  <?php
    if($light=="on") {
      echo("Turn LED on.");
    }
    else if ($light=="off") {
      echo("Turn LED off.");
    }
    else {
      echo ("Do something.");
    }
  ?>

thanks in advance.
Edit
memory statistics:
Global variables use 1,187 bytes (57%) of dynamic memory, leaving 861 bytes for local variables. Maximum is 2,048 bytes.

Edit
I did some enhancement to my arduino code and used adafruit library but still the server response takes too long to get it (up to 10 seconds).
this is my new code:
/***************************************************
  This is an example for the Adafruit CC3000 Wifi Breakout & Shield

  Designed specifically to work with the Adafruit WiFi products:
  ----> https://www.adafruit.com/products/1469

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Kevin Townsend & Limor Fried & Rick Lesniak for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

/*

This example does a test of the SNTP (Simple Network Time Protocol) client:
* Initialization
* SSID Scan
* AP connection
* DHCP printout
* SNTP time synchronization
* Extract and print current time and date information

*/

#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
//#include "utility/NetTime.h"
#include <string.h>
#include "utility/debug.h"

#include <ArduinoJson.h>
#include <TextFinder.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_DIV2); // you can change this clock speed but DI
Adafruit_CC3000_Client client;
TextFinder finder(client);

#define WLAN_SSID       "XXXXX"   // cannot be longer than 32 characters!
const char WLAN_PASS[] = {0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0x00};
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WEP

#define SERVER "XXXXX"
String DIRECTORY   =   "XXXXX";

uint32_t ip;

const int pin        = 2;

/**************************************************************************/
/*!
    @brief  Sets up the HW and the CC3000 module (called automatically
            on startup)
*/
/**************************************************************************/
void setup()
{
  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  /* Optional: Update the Mac Address to a known value */
/*
  uint8_t macAddress[6] = { 0x08, 0x00, 0x28, 0x01, 0x79, 0xB7 };
   if (!cc3000.setMacAddress(macAddress))
   {
     Serial.println(F("Failed trying to update the MAC address"));
     while(1);
   }
*/

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  }

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  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!
  }

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

  cc3000.printIPdotsRev(ip);

  client = cc3000.connectTCP(ip, 80);
}

void loop()
{
  if(!cc3000.checkConnected())
  {
    cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
    Serial.println("connection was lost but succefully retrieved");
  }
  if(!client.connected())
  {
    client = cc3000.connectTCP(ip, 80);
    Serial.println("client lost connection but succefully retrieved it");
  }

  String request = "GET " + DIRECTORY + " HTTP/1.1\r\n" +
               "Host: " + SERVER + "\r\n" +
               "Connection: keep-alive\r\n\r\n";
  send_request(request);
}

/**************************************************************************/
/*!
    @brief  Tries to read the CC3000's internal firmware patch ID
*/
/**************************************************************************/
uint16_t checkFirmwareVersion(void)
{
  uint8_t major, minor;
  uint16_t version;

#ifndef CC3000_TINY_DRIVER
  if(!cc3000.getFirmwareVersion(&major, &minor))
  {
    Serial.println(F("Unable to retrieve the firmware version!\r\n"));
    version = 0;
  }
  else
  {
    Serial.print(F("Firmware V. : "));
    Serial.print(major); Serial.print(F(".")); Serial.println(minor);
    version = major; version <<= 8; version |= minor;
  }
#endif
  return version;
}

void send_request (String request) {
  String req = request;
  if (client.connected())
    {
      client.print(req);
      delay(5);
      client.println();
      delay(5);
    }
    else
    {
      Serial.print(F("failed to connect from loop"));
      return;
    }

  // read response
  while (client.connected()) {
    while (client.available()) {
      if(finder.find("\n\r")){
    int line = finder.getValue();
    Serial.print(line);
      if (line == 1) {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      }
      else {
        digitalWrite(pin, LOW);
        Serial.println("led off");
      }
    }
    }
  }
  client.close();
}

can somene tell me how to reduce this delay time?

Do you have some build statistics? How much memory is available?


text:
FTDI stdk 500k not responding
I programming atmega328P bootloaded with an FTDI.
Some tutorial mentions that you have to connect the DTR to the reset pin:
http://electronics-diy.com/FT232RL_USB_to_Serial_Adapter_for_PIC_AVR_ATMEGA_ARDUINO_MCUs.php
Is that so? Because some don't, they just say rx,tx is enough. I still can't program the chip with the error:
 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

avrdude: Version 5.11.1, compiled on Oct 18 2011 at 21:17:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : avrisp
         Overriding Baud Rate          : 9600
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

avrdude done.  Thank you.

I tried different baud rates, no matter what it's not responding. Linux recognizes the FTDI as:
Sat Feb 13 22:52:14 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:52:14 2016] ftdi_sio 1-2.1:1.0: device disconnected
[Sat Feb 13 22:52:19 2016] usb 1-2.1: new full-speed USB device number 73 using uhci_hcd
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device found, idVendor=0403, idProduct=6001
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Product: FT232R USB UART
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Manufacturer: FTDI
[Sat Feb 13 22:52:20 2016] usb 1-2.1: SerialNumber: A6004mhS
[Sat Feb 13 22:52:20 2016] ftdi_sio 1-2.1:1.0: FTDI USB Serial Device converter detected
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Detected FT232RL
[Sat Feb 13 22:52:20 2016] usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
[Sat Feb 13 22:56:25 2016] usb 1-2.1: USB disconnect, device number 73
[Sat Feb 13 22:56:25 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:56:25 2016] ftdi_sio 1-2.1:1.0: device disconnected

Well my questions now are:
1, When I use the Arduino IDE to program a barebone 328P with this FTDI what should be the BOARD and what should be the PROGRAMMER?
Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII
Although I tried almost all... I think something else is wrong.
2, Should I be able to get any result with doing the previous:
 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

command WITHOUT connecting the barebone chip? I think not, since this doesn't act like a fully fledged MCU just like a serial converter.
Thanks

You may get away with quicky resetting the AVR after you started avrdude. The bootloader kicks in at that moment and listens for an incoming flash image. Use arduino for the programmer type. You may have to fiddle with baudrate, not sure what the default baudrate is.

I have used the following commands in the past to program an Arduino without using the IDE: mcu=atmega1280,
freq=16000000L,
baud=57600,
port=/dev/ttyUSB002, avrdude -p$mcu -carduino -P$port -b$baud -D -Uflash:w:./project.hex:i

Poor man's make file for Proof of Concept purposes only.

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?
See: How to make an Arduino-compatible minimal board
From that page, this is how I hooked up my FTDI cable:

And a close-up:

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.

You need to connect DTR to the reset pin because the Arduino IDE (really avrdude) needs to be able to reset the processor in order to return control to the bootloader, which will then receive the new program. When an Arduino board is running your sketch, the serial port is available for use by the sketch; it can't be used to upload a new program.
To answer your first question, you should set the board to whatever your board actually is. You don't have to worry about the programmer. It's only used if you use the "upload with programmer" function. The normal "upload" function uses the serial port to send the sketch to the board via the bootloader. That's what you want. Note that while you don't have to set the programmer, you do have to set the port.
You can use avrdude to program the Arduino through the serial port via the bootloader. That's exactly what the IDE does. You have to specify the port just as you do in the IDE. To determine the other settings, look up your board in the Arduino IDE's boards.txt file. Most of what boards.txt does is tell the IDE how to invoke avrdude.
I suspect that one reason why avrdude isn't working for you is that you've set the baud rate to 9600.  According to boards.txt the upload speed for the Nano with the ATmega328P is 57600.


text:
Change device Function Summary for Teensy-LC
I found this thread here which describes procedure to change the produce-name of Teensy
However when we open device properties we see 'Teensy USB Serial (COM xx) in the Device function summary.
Please find the image below to understand what I am referring to.

So is there any way to change this details as well?

I think that string is inside the USB code in the Teensy. Conceivably you could locate the appropriate library and change it.

Could this string be inside the Teensy bootloader and presented to the USB device layer (Windows) when waiting for upload? In that case I don't think it is possible to change as the Teensy bootloader is not open-source.

Could you link or give the URL of the "thread" you found? Thank you.


text:
Combining code for multiple sensors in one program
I need to operate 2 different sensors (gas and temp) simultaneously.
I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.
Here are the sketches:
Thermistor code:
void setup() {
  //This function gets called when the Arduino starts
  Serial.begin(9600);
  //This code sets up the Serial port at 9600 baud rate
}

void loop() {
  //This function loops while the arduino is powered
  int val; //Create an integer variable
  val=analogRead(0);
  //Read the analog port 0 and store the value in val
  Serial.println(val);
  //Print the value to the serial port
  delay(1000);
  //Wait one second before we do it again
}

This is the gas detector code:
/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int sensorPin = A0;
// select the input pin for the potentiometer
int DOPin = 2;
// select the pin for the LED
int sensorValue = 0;
// variable to store the value coming from the sensor
int ledPin =13;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(DOPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.print("Analog Output = ");
  Serial.println(sensorValue);
  // turn the ledPin on if triggered
  if (digitalRead(DOPin) ==HIGH) {
    digitalWrite(ledPin, LOW);
    Serial.println("Digital Output = OFF");
  } else {
    digitalWrite(ledPin, HIGH);
    Serial.println("Digital Output = ON");
  }
  delay(1000);
}

I want the arduino code for display this
"AutomatedCar Parking With Empty Slot Detection"

You just need to assign the sensors different pins.
/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int gasSensorPin= A0; // GAS sensor pin
int DOpin= 2; // select the pin for the LED
int gasSensorValue= 0; // variable to store the value coming from the sensor
int ledPin = 13;

int tempSensorPin = A1;  //Temperature sensor pin
int tempSensorValue;

void setup() {
 // declare the ledPin as an OUTPUT:
 pinMode(DOPin, INPUT);
 pinMode(ledPin, OUTPUT);
 Serial.begin(9600);
 }

void loop() {
 // read the value from the sensor:
 gasSensorValue= analogRead(gasSensorPin);
 Serial.print("Analog Output = ");
 Serial.println(gasSensorValue);
 // turn the ledPin on if triggered
 //
 if (digitalRead(DOpin) == HIGH){
 digitalWrite(ledPin, LOW);
 Serial.println("Digital Output = OFF");
 }
   else {
     digitalWrite(ledPin, HIGH);
     Serial.println("Digital Output = ON");
  }

Serial.print("Temperture: ");
tempSensorValue = analogRead(tempSensorPin));
Serial.println(tempSensorPin);  //Print the value of pin A4

delay(1000);
}

This is your combined sketch.

I know that, and I did that. My problem is how can I put both in one program, upload it to the device and run it together.

Upload the code from my answer and attach your temperature sensor to pin "A1"


text:
Difference between data type int and long on Arduino
I was learning to program for a void obstacle robot but when I looked at the code I saw two data types long and int.
Int are datatypes that holds  -2,147,483,648 to 2,147,483,647.
Long are also datatypes that holds -2,147,483,648 to 2,147,483,647.
Int and long are like same but I came up with the code where two types of datatype is used as seen below:
int trigPin = 2;
int echoPin = 4;
long duration, cm, inches;

But how can you know when to use which datatype? I searched a lot in the web but I didn't understand so can someone explain this to me please.

"Int are datatypes that holds -2,147,483,648 to 2,147,483,647" Where did you hear that?

On the Arduino (AVR models) an int is 16 bits, not 32 bits. Thus it goes from -32768 to +32767.
That is different from long which is 32 bits.

What are the widths of int and long on the 32-bit ARM Arduinos such as Due?

I think on the Due that an int is 32 bits, the same a long. See here for example.

According to the C language specification, int must be at least 16 bits or longer and long must be at least 32 bits or longer.
It is OK for a compiler to implement int as 32 bits or even 64 bits. It is OK for a compiler to implement long as 64 bits or longer. But it is not allowed for a compiler to implement long as 16 bits.
So when to use which type?
If the values you will be working with can be represented within 16 bits then it's OK to use int. If you need more than 16 bits use long. If you need more than 32 bits use long long.
Do not be caught up with compiler and/or CPU specifics. As mentioned by others, even within the same product range, Arduinos, there are 16 and 32 bit CPUs available. Instead, only trust what the standard guarantees.
The full specification of types in C are:

char must be at least 8 bits
int must be at least 16 bits
long must be at least 32 bits
long long must be at least 64 bits

Note: It is perfectly legal for compilers to implement char, int, long and long long as 64 bits. This is in fact not uncommon among DSPs.

Also: Read your compiler documentation

And: sizeof(char) <= sizeof(int) <= sizeof(long) <= sizeof(long long) according to standard. So, if int is 64 bits, then long must also be at least 64 bits.

int in AVR GCC is 16 bits, not 32.

It's the same reasoning as in C: the size of the int type is expected to be the natural word size that your system handles most efficiently. It must also be at least 16 bits wide, no smaller than a short, and no larger than a long.
So an int may be 16-, 32-, or 64-bits, based on the whatever your system handles best, and so is most likely to be 16 bits wide on an 8- or 16-bit CPU, 32 on a 32-bit CPU etc.
I use int when I want the best performance, whilst taking care to guard when I need more range than offered by 16 bits. These days, you tend to know when you are writing application code for 16-bit systems, although that's not so true for "library" code where portability may be of greater concern.
In your example, assuming the author had chosen their types carefully, the int variables probably require a small range and could afford to be word-size, leading to potentially shorter or faster code (or both). The long ones presumably required more than 16-bit range (they are guaranteed to be at least 32 bits wide). On the processor you'd selected as a compilation target, it looks like int and long were both implemented as 32-bit; this would be different (or should be) if you selected a 16-bit target CPU.

I like to use types from stdint.h.
While they do have minor drawbacks, the benefit they provide is you know exactly the size your are handling, even when compiling on other architectures.
#include <stdint.h>

uint8_t  my_byte = 0xf0;
int16_t  trig_pin = 2;
int16_t  echo_pin = 4;
uint32_t duration, cm , blah;
uint64_t big_int;

// etc.

But obviously you don't want to be moving around a bunch of int32_t when your data only needs int16_t.

So not using machine word size does not impact performance on AVR?

@René - Generally not using word size can impact performance on most CPUs.  But traditionally AVR CPUs have 8bit registers & accumulators with some 16 bit instructions for pointer operations.  So when I program, I get the code running first, then optimise for speed if it's too slow.

@René - But if you really want to be pedantic about it, you could use word as your data type.  This is 16 bits on Arduino Uno, and 32 bits on Arduino Due & Zero.  But this comes back to the problem of really only knowing the minimum size of your data type.  Say you use word on some Due code, but then want to back-port to Uno?!  Using uint32_t instead would solve this problem before it starts, but yes it will be word-size sub-optimal on Uno.   What about future Arduino boards ... what word size will they have? 32? 64? 128!?

OK. So I would use the machine word size (int? WORD seems to be an obselete windows type definition) if the lower limit is sufficient, I do not care about memory size and need the speed, *_t if I care about size?

scrap that ... http://www.gnu.org/software/libc/manual/html_node/Integers.html says *fast*_t seems to be the way to go ...

@René - Yes.  Also when you pack structures, make sure you pack all the variables to word-sized boundaries.  So full-sized words at the top, any single chars or bools at the bottom.

if you are using Esp32 boards in Arduino IDE: