text:
Receiving serial data in groups instead of individually
I have two different Vernier science probes connected to a Vernier shield that connects to an Arduino Uno. I have the Uno connected to an ESP8266 via the Tx.
Here is my Uno code:
String sensor1 ="Conductivity Probe ";
float interceptSensor1 = 0.0;
float slopeSensor1 = 960;
String sensor2 ="pH Probe ";
float interceptSensor2 = 13.720;
float slopeSensor2 = -3.838;
int timeBetweenReadings = 2000; // in ms

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

void loop() {
  float analogSensor1 = analogRead(A0);
  float voltageSensor1 = analogSensor1 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor1Reading= interceptSensor1 + voltageSensor1 * slopeSensor1;
  //converts voltage to sensor reading
  String sensor1Output = sensor1 + sensor1Reading;
  Serial.println(sensor1Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
  float analogSensor2 = analogRead(A1);
  float voltageSensor2 = analogSensor2 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor2Reading= interceptSensor2 + voltageSensor2 * slopeSensor2; //converts voltage to sensor reading
  String sensor2Output = sensor2 + sensor2Reading;
  Serial.println(sensor2Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
}

On the serial monitor every two seconds I get one line of output and it alternates back and forth between the sensors:
Conductivity Probe 807.04

pH Probe 4.12

Conductivity Probe 802.35

pH Probe 4.13

Conductivity Probe 802.35

pH Probe 4.12

Since I've only got a simple serial line to work with but I need to send multiple, different types of data to the ESP8266, my strategy is to send one line (ex. Conductivity Probe 807.04) and use logic on the ESP8226 to parse the string, isolate the float number (807.04), and  use Conductivity Probe to determine how that number gets further used (in my case, to publish to an MQTT feed called ElectroConductivity).
The Tx of the Uno + sensors is wired to the Rx of the ESP8266, and here's the ESP8266 code:
  while (Serial.available() == 0) {
  }
  sensorReading = Serial.readString();
  Serial.println(sensorReading);

The data comes in large groups instead of line by line:
pH Probe 4.12
Conductivity Probe 807.04
pH Probe 4.12
Conductivity Probe 807.04

I'm new to serial comms and Arduino in general. I'm guessing that there's an issue with how serial is read by the ESP8266.
EDIT
When I use sensorReading = Serial.readStringUntil('\n'); instead my output looks like this:
Conductivity PrpH Probe 4.12

Conductivity Probe 816.42

pH Probe 4.12

Conductivity Probe 825.8Conductivity Probe 821.11

Conductivity Probe 821.11

pH Probe pH Probe 4.12

ConductivitypH Probe 4.12

What's your question?

The question is why is he getting the data at the other end of the serial link in blocks rather than line by line.

readString() will keep reading until it times out. Instead try readStringUntil('\n') to read until you get a new line character.

Thanks! That seemed to have done it. BTW, it's \n, not /n. Was getting conductivity cut off when using the former, haha. So readString() will just read as much as it can before timeout? I never explicitly set a timeout for readString(), so I'm assuming that if it's not explicitly set then there's a default of like 4 seconds or something?

Bah, it didn't work. Please see updated post.

@user3135509 oops. Fixed the \ Vs / typo. That new behavior is weird, it's almost as if something isn't keeping up and the serial receive buffer is overflowing between loops. Do you have a lot of other code in the loop or is it just reading and printing for now? At this point I'd be tempted to read the incoming serial data byte by byte rather than using the readString functions, that way you gain a lot of flexibility and can ignore any timeout related issues.

On the Uno side, everything you see in the OP is what's in the loop. On the receiving side of the ESP8266, there are other things in the loop, such as setting up MQTT subscriptions and publications. So, uh, having other code running in the loop() function, code that's unrelated to serial, would cause the serial buffer to overflow?

@user3135509 it depends on how long the other stuff takes and how fast the serial data is coming in. It looks like you have 2 seconds between lines so that should be plenty of time, as a sanity check maybe comment the other stuff out and see if it starts working or not.


text:
Arduino Mega 2560 interrupt pins and port mapping with rotary encoder
I am trying to use port manipulation in interrupts to read a rotary encoder. I found code for a Uno, so the port call for pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively. My code is not working. Do I have my ports wrong? I've tried reading up on this and I'm not fully understanding the Bxxxxxxxx part. I think that might be what's incorrect. Here is part of my code with one of the interrupts.
static int pinA = 2;
// Our first hardware interrupt pin is digital pin 2
static int pinB = 3;
// Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0;
// let us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0;
// let us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0;
//this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0;
//stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0;

void setup () {
  pinMode(pinA, INPUT);
  // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  pinMode(pinB, INPUT);
  attachInterrupt(0, PinA, RISING);
  // set an interrupt on PinA,
  //looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
  attachInterrupt(1, PinB, RISING);
  // set an interrupt on PinB,
  //looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
}

void PinA() {
  //CCW
  cli();
  //stop interrupts happening before we read pin values
  reading = PORTH & 0xC;
  // read all eight pin values then strip away all but pinA and pinB's values
  if (reading == B00001100 && aFlag) {
    //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos --; //decrement the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  } else if (reading == B00000100) bFlag = 1;
  //signal that we're expecting pinB to signal the transition to detent from free rotation
  sei(); //restart interrupts
}

Did you ever get this working? I too have been wanting to use a Arduino Mega to track the angular position of a Omron Encoder with 3 interrupts. One of the interrupts for he Index to reset to 0 every time it completes one revolution. I want to use it to track a rotating mast for for direction finding. There are pieces of code but nothing complete.
Is yours complete?
bkukuk@cox.net

Re “pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively”, it's true that Arduino digital pins 2 and 3 belong to different ports on Uno vs Mega2560 boards.
Mega2560's have six INTx pins, vs two such on Uno's.  On the Mega, INT0...INT3 are PD0...PD3, and INT4,INT5 are PE4,PE5.  On the Uno, INT0,INT1 are PD2,PD3.  Note, in an answer at Can external interrupts be OR'd together on the '328 (Uno)? I show a couple of routines that will display appropriate masks for pins on different Arduinos.  See the sections “Using other pins for PCIs” and “ISR-framework-generating Sketch”.

Here are a few problems with the code shown in the question:

aFlag is initialized to zero, and is never set nonzero in the code shown.  So the first if condition in PinA() is never met.
PinA() is an interrupt handler, connected to interrupts by your attachInterrupt() calls.  Because hardware disables interrupts before it enters an interrupt handler, there is no need for the interrupt handler to turn off interrupts.  That is, delete cli() in PinA().  Similarly, delete the sei() at the end of PinA() because hardware restores interrupt status when a RETI instruction executes.
The Arduino software environment defines constants like B00001100 with binary values that match the name.  That is, in the Arduino software environment, constant B00001100 has the value 0B00001100.  In my opinion, that's a stupid and unnecessary feature; I suggest that in your code you use standard C notation like 0B00001100 when you want to use binary constant values.
I regard writing encoderPos -- instead of encoderPos-- as a perversion and suggest deleting that unnecessary space.
As you haven't shown the PinB() interrupt handler, I don't know how you were going to handle the encoderPos++ case.  Judging from the code shown, you are using a method that won't correctly handle bounce and intermittent errors.  I suggest using pin-change interrupts and a state-machine method, as illustrated in answers to:
• Reading from a KY-040 rotary encoder with Digispark
• How to read RPS for fast rotation with status change method in Arduino?
• Read RC receiver channels using Interrupt instead of PulseIn
• Can external interrupts be OR'd together on the '328 (Uno)?

On the mega, you'd read the pins with PINE.
So your code in PinA would change to:
reading = PINE & 0b00110000;

  if(reading == 0b00110000 && aFlag)

  {  encoderPos --;
    bFlag = 0;
    aFlag = 0;
  }
  else if (reading == 0b00010000) bFlag = 1;

I found a great discussion talking about the masking required here: https://forum.arduino.cc/index.php?topic=561741.0

source: Stack Exchange

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

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

sort: votes


text:
Difficulty connecting arduino ethernet with PC using a switch
Facing difficulty connecting arduino ethernet(w5100) with PC using a switch (Dlink). When both are connected directly(p2p) using ethernet cable, arduino device can be pinged. However, when connected via switch - ping doesn't work, and both devices can't communicate with each other; updated the MAC addr. several times, nothing worked. How can this be resolved?
The same setup works when connected via a router instead of switch. But we need it to work with switch only.
Static ip has been assigned to both PC and arduino uno ethernet shield.

Do all link lights come on?

Yes, three lights are on, one for power, two for the two Ethernet cables.

Have you verified that the switch works?

Yes, pinged two PCs successfully via that switch and cables.

Are you using the same cable for direct connection and thru switch connection? They are different ...

@Alterno, cables are the same.

I think the w5100 works at 10MBs, so is the switch you are using compatible with 10MB/s?

@CodeGorilla Yes, the switch supports that speed.

@user3126972 - Damn.... The only other thing I can think about is there used to be two types of cable, crossed and straight.  You would use a straight cable to go from a device to a switch and a crossed cable to do P2P.  With some modern devices it doesn't matter because they auto-cross.  Its a long shot, but it might be worth checking (Google to work out how to spot the difference).    Could it be related to duplex?  I haven't looked at the datasheet for the W5100.  Does it support full duplex?  Is it supporting full duplex (can you even tell)?

@CodeGorilla, both the cables in use are straight one. Using the same cables I was able to ping two laptops through that switch. Regarding FullDuplex mode - yes, w5100 supports that, google 'W5100_Datasheet_v1_1_6.pdf'

What type of D-link switch is it? Is the switch a managed switch?

Is there an IP conflict? ie. does another device on the network have the same IP address assigned that you have on the PC or Arduino? What does arp -a on the PC say about the Arduino IP address? If there's no IP conflicts, it could be your arp cache on either device isn't being updated. To reset the Arduino, just reboot it. To clear the arp cache on the PC, just do a search for "clear arp cache" along with your OS type (or reboot).

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


text:
Are there any electro-chemical sensors available to measure nutrient contents of soil?
I want to develop a soil fertility testing device and need an electro chemical sensor to do so.
I searched the online available sensors but didn't get any source. Does anyone knows anybody in development of such sensors ?

I think you would be better getting this question moved to SE EE.  They know more about general electronics.

You have pH and humidity sensors for Arduino, but "soil fertility" is an unprecise term.
If you do a web search, you will find results for a number of devices that claim to measure soil fertility. I am highly suspect of these devices. Even laboratory testing cannot tell you accurately how fertile your soils are because of the methods used. Most labs test for the presence of inorganic chemals, including nitrogen, potassium, phosphorous and an array of other nutrients plants need. What most of them do not or cannot measure is the amount of plant-available nutrients in the soil. It takes a host of soil organisms to make nutrients in the soil available to plants. If those organisms are not present or are low in numbers, it is difficult for plants to take up nutrients. Fertilizers only exacerbate the problem because they kill off soil organisms, especially mycorrhizal fungi, throwing the entire ecology of the soil out of kilter. There are a couple of laboritories out there that test for soil biology and some nutrients.
Soil is hard. There is a lot of things in soil (compactness, unwanted chemicals/elements, microbes) that can affect the fertility, even if you have the right nutrients in it.
For hydroponic (not your case), you have cheap handheld EC/TDS meters. The pH and EC of your reservoir is all you need to measure the fertility of your water solution.
Go hydro and stop worrying about your tomatoes.

May want to throw in that depending on environment, monitoring water temp is very important as well in a hydroponic system.

@stevieg. If your room temperature is right, then your water temperature is OK. The only part that needs automation in hydro is maintaining water level; you can lost 1 lt/day (or more). pH and EC are relatively stable, and adding more nutrient solution usually correct the pH going high and add new nuts to the reservoir (DWC).


text:
Timer Prescaler problem
I am working on a project which requires use of 16bit timer . I am using Arduino Uno (Atmega 328p) board and Timer_1 (16 bit timer ) in Overflow mode. i want to use 1024 prescaler settings.
According to the datasheet of the controller i have to set [b]CS10 and CS12[/b] bits to use 1024 prescaler but the problem is OverFlow interrupt routine is never fired when 1024 or 256 prescaler is selected .
The Following code works just fine with Prescaler set to 8 or 64.
#include <inttypes.h>

volatile uint8_t sCount = 0;

void setup()
{
      Timer_one_16_init(); // configure the timer

      pinMode(13,OUTPUT);

}

void loop()
{
    // do nothing
}

void Timer_one_16_init(){

    TCCR1A = 0;

    // set the pre-scaler to 1024 (slowest)

    TCCR1B |= (1<<CS12)|(1<<CS10);

    // set the bottom / starting value

    TCNT1 = 0x00;

    // set Overflow interrupt

    TIMSK1 |= (1<<TOIE1);

    // enable global interrupt
    sei();

}

ISR(TIMER1_OVF_vect){

    sCount++;

    if (sCount == 60)
    {
        digitalWrite(13,!digitalRead(13));
        sCount = 0;

    }

}

i have no idea why this is happening. i have done everything which is given in the datasheet .
Am i doing something wrong ?
Thanks in advance

You must write the clock-select bits to the correct value. The simplest
way to do it is to write the proper configuration into the TCCR1B
register:
TCCR1B = (1<<CS12)|(1<<CS10);

In your program, you used |= instead of =. This doesn't write the
bits appropriately: it only sets (writes to 1) the bits CS12 and
CS10 but doesn't clear CS11. Since the Arduino core library sets the
prescaler to 64 (CS11 and CS10 set), you end up with all the
clock-select bits sets, in which case the timer is clocked by an
external signal on the T1 pin. Not what you want.

Edit: Judging from the comments, it appears that at least dannyf did
not understand my answer, I am therefore adding a clarification. There
are two scenarios when you may want to tweak the control registers of a
peripheral:

The peripheral is normally controlled by the Arduino core library,
and you want to use it through that library. Typical case: you want
to use a timer to analogWrite(), or the ADC to analogRead(), but
you want to clock the peripheral at a frequency which is not the
core's default.
You want to use a peripheral directly rather than through the Arduino
core. Either you are going to “take it over” from the core, or it's a
peripheral the core doesn't use in the first place.

In the first case, you should only touch those bits of the control
registers that you must change. The other bits should be left alone, at
whatever values the core has set them to. This is the approach of
dannyf's answer.
In the second case, it is wiser to not rely on the core's default
setting, and instead write every single bit of the control registers
to the values appropriate for your application. This is the scenario of
the original question, and the solution proposed in my answer.
For the particular case of this question, the TCCR1B register would
be set to: ICNC1 = 0†, ICES1 = 0, reserved bit = 0, WGM13
= 0, WGM12 = 0, CS12 = 1, CS11 = 0 and CS10 = 1. Combining those bits
together gives the setting TCCR1B = 0x05;. However, for readability
reasons, I prefer to write that value (1<<CS12)|(1<<CS10), as in the
question and in my original answer. Some people may prefer to explicitly
write every bit, like
TCCR1B = (0<<ICNC1) | (0<<ICES1) | (0<<5)    | (0<<WGM13)
       | (0<<WGM12) | (1<<CS12)  | (0<<CS11) | (1<<CS10);

Whichever version you prefer is up to you. I personally don't find this
latter version any easier to read.
†: The values of ICNC1 and ICES1 are actually
irrelevant in this case.

Thanks  it solved my problem. i have just checked the default value of TCCR1B . it is 0x33 . But in the datasheet default value of TCCR1B = 0x00. i was expecting the value of CS11 bit to be 0.

" i have just checked the default value of TCCR1B . it is 0x33 ." that means the code is setting WGM13. With the proposed "beginner" approach, WGM13 is cleared. To the extent that your code uses anything that requires WGM13 being set, like PWM, it wouldn't work.

"But in the datasheet default value of TCCR1B = 0x00. i was expecting the value of CS11 bit to be 0." you should never rely on the default values. and your code should only change the registers / bits to the extent that you need. For example, if you want to change prescalers, change only those registers / bits that are related to the registers / bits that need to be changed. Otherwise, your code may have unexpected impact on other parts of your code.

It is because of that, the code proposed to you is very dangerous: it is a bomb that will explode in your face when the conditions are "unexpectedly" right.

@parasbhanot: “But in the datasheet default value of TCCR1B = 0x00”. This only applies after a reset. You can rely on this default if you do not use a bootloader nor the Arduino core. The Uno's bootloader does its best to leave every register at its reset state, but it could be unwise to rely on this. And if you use the main() from Arduino core (the “normal” Arduino practice, where you write setup() and loop() but not your own main()), then many registers will end up in the Arduino's default setting, which is not the same as the hardware-defined default.

// set the pre-scaler to 1024 (slowest)

TCCR1B |= (1<<CS12)|(1<<CS10);

that approach presumes for the CS11 bit. in this case, if CS11 is set, the clock source is routed to the CKI pin, and if you don't apply a clock to that pin, the timer will never overflow.
Two options:
1) do it via two steps: set CS12/CS10 and clear CS11; or
2) do it in one step:
TCCR1B = (TCCR1B &~0x07) | (ps & 0x07);

ps would be whatever prescaler setting you wish to use.
the proposed solution below,
TCCR1B = (1<<CS12)|(1<<CS10);

is a typical beginner mistake, and a very dangerous one, as it clears other TCCR1B bits without the programmer even realizing it.

“TCCR1B = (1<<CS12)|(1<<CS10); is a typical beginner mistake.” No, it's the right thing to do. If you are configuring a timer for your own usage, you should not rely on whatever settings the Arduino core left in the control registers. Instead, you should set every bit of the control register to the value appropriate for your application. You could do that bit by bit, if you enjoy useless complexity, but the simplest solution is just control_register = the_value_I_want;.


text:
Arduino Newbie: Solderless Breadboard Alternate
I am completely new to arduino. I have created a circuit using solderless breadboard. But obviously the connections are lose or not as good as a soldered solution. So I was wondering since I am new to circuits too, what is the easiest

i found that with thick custom-cut wiring (~20AWG solid) and a brand new breadboard the connections are actually pretty robust ("drop proof"). deadbug-style is easy as well, at least for small circuits

Breadboards are for development and testing. When you are OK with your circuit, then you solder it.
Your alternatives:
Point-to-Point
Just solder directly component to component. You can arrange your component for minimal space and minimal wiring length. Can be very elegant (depends on your abilities) and doesn't require any board.

Perforated board
For personal projects, you can use a perforated board to put all your components. Requires some planning in components placement and wiring (you can paint yourself in a corner). Easy to do.

Expansion Shield
It's a perforated board on a shield, so you just plug it over your Arduino Uno. Great if you need easy access to lots of Arduino pins. Cons: little space for components. There are versions with a mini-breadboard instead of a perforated board.

PCB
You can make your how PCB, but it's hard and too much work. Use it only for high volume production. It require lots of preparation and dangerous chemicals.

Useful links (YouTube)

Review of some prototype circuit building methods
Perfboard Prototyping
Breadboards & Perfboards

"Point-to-Point" soldering is more commonly known as "Dead Bugging".

Re: the PCB option, you leave out a choice: Prototyping shops like Fritzing, Seeedstudio, or MacroFab that will manufacture a custom PCB design (just the PCB itself, or even pick-and-place the whole assembly!) for very reasonable cost and no minimum order.  That saves you the pain and expense of trying to etch and troubleshoot your own hand-rolled PCB using noxious chemicals in your kitchen or backyard.

@Tristan. Making a PCB is an order of magnitud harder than using a perforated board. It required more software to master, more problem to solve (routing) and more things to consider (the component's physical dimensions). Using perforated board is easier: just drop the components on the board and play with them until you get a neat configuration. Then solder. End of the story.

@LookAlterno I don't deny that designing a PCB is harder than using a perfboard.  I am merely pointing out that there are inexpensive ways to actually obtain a PCB that do not involve the personal chemical exposure and prep that you are suggesting -- it's not as hard as you are making it out to be.  If you can craft a gerber file (which you can do with freely available software, or directly on some providers websites!) that creates the correct connectivity, there are shops that will handle the actual manufacturing for you at very low (as in only tens of dollars) cost.

@LookAlterno Since I ran out of space on the previous comment, what the PCB option doesn't give you is the freedom to tinker or rework a design -- that requires a new fabrication.  You would reserve the PCB step for when you have a design that is more or less finalized and ready to be put in a permanent form.

The next step up from breadboard is either matrix board or strip board.
Matrix board is a PCB with a grid (matrix) of holes in a 0.1" grid with copper annulars around them for soldering.

Strip board (also known as the brand name Veroboard) is like matrix board but the holes are linked together in long strips, a little like a breadboard. These strips run the length of the board and you have to break the strips (there is a special tool you can use, but most people just use a small drill bit) into the pattern you require for your circuit.

Yes, both of these require soldering - so now is the time to get to grips with how to solder. There's plenty of tutorials and videos online to help you get to grips with it (though don't grip the hot end...). Don't be afraid of making a mess of your first attempts, soldering takes practice to get it right - and having the right tools helps.
Get a semi-decent soldering iron - not a plumber's iron, but a proper electronic one. You can get basic ones quite cheap. I started out with one of these cheap Antex ones:

If you can afford it, though, go for a temperature controlled one instead. It makes soldering easier since you are less likely to lift pads from over-temperature.
And last you will want some decent solder. I use 0.7mm solder with a rosin flux core. Don't use solder that doesn't have a flux core, that is for plumbing.
Having a flux pen (electronic flux, not plumbing flux) will help get you out of some sticky situations with your soldering as well. The addition of flux makes the solder behave itself. Without extra flux it can me somewhat unruly. Also some desoldering braid and maybe a desoldering pump can be useful (I tend to use braid more than my pump these days).

To make it easy, you can buy so-called proto shields for Arduino like below.
The advantage is that you can stick it directly on your Arduino (Uno/Mega) and you can soldier the extra components on the proto space.

and the connection will be same as that on the breakboard? or will I have to make some changes? like i said I am new to all this. Sorry if my question sounds stupid

It's not a stupid questions ... when I started half year ago I had the same problems. Btw, I never used a proto board like this. But yes, they have the same connections. (I used normal shields, meaning shields which you can stick on top of an Arduino Uno or Mega with premade components, e.g. for SD cards). But with a proto shield you can add your own components.

I basically want to connect four sensors. And I am unable to figure out how to do it without the breakboard. I want to connect humidity sensor, relay board 5v, pir sensor, and solenoid valve. Do you think there is a shield available for something like this?

I know there are boards with preassembled sensors, but I doubt it's exactly the ones you need. Btw, you can normally stack multiple boards on top of each other, but I doubt you will find exactly the configuration you want. In that case, I would use a proto shield (if they can fit on one proto shield).

One alternative that I like is the "breadboard-like" copper boards from Busboard Prototype Systems.  Several of their models have layouts just like solderless breadboards, but are soldered, and so more durable and stable, while leveraging your breadboard design pin-for-pin:

I love these because like many folks, I prototype earliest versions on one or more breadboards and these have the same hole layout, even down to the parallel power and ground rails down the sides.  Very convenient and available in several sizes and other configurations.

Use wire wrap for quick and easy prototyping.

Welcome to Arduino Stack Exchange.  Please take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.  This is an intriguing idea.  Good presentation of the answer.

what is the easiest

for most people, breadboard is the easiest.
I sometimes do point to point (deadbug, mostly RF or small things), or onto pcb adapters (ghetto-style).

I have not had much luck with breadboards either. I see, on internet, that others seem to make even quite complex circuits. I can only assume it means I need to take more care to insert the components better and perhaps spend a bit more on a better quality product? I see the replies all give alternatives but no suggestions as to why Saad has problems and how to improve I would be interested to know too! At the moment, I also solder components to breadboards but it is a pain if I have to de-solder. I also use one of those childrens kits for experimenting with electronics together with a solderless bread board. It has transistors and capacitors etc and so I can connect it to IC or other particular components fitted to the [![enter image description here][1]][1]solderless breadboard. The photo is just to give an idea. I have also tried soldering small female sockets to breadboards and plug the various components into those for testing.
I have been experimenting more and reading some articles on internet. In fact, I found it better to make small jumper wires, rather than use tje ready made ones. The ready made ones tend to move and the contact is not so secure. It is nit so easy to make the small jumpers though and needs patience! I also made a small switch power supply board.. I found on "instructables" https://www.instructables.com/id/Ultimate-DIY-Breadboard-Power-Supply/#CB1TV2QJ70QKF7I
It plugs into the bread board and I can select a required voltage
[1]: https://i.stack.imgur.com/sXOmY.jpg

Make a PCB with a plotter

You can create a PCB using copper foil and a cutting plotter. The complexity of the circuits will be limited to the resolution and precision that you cutter can plot at but it's a great for prototypes or full projects.
If you already have a machine, the materials are cheap and circuits can be designed using any vector based editing software. Fritzing supports the export of vector files.

[LudwigLabs] is creating PCBs using copper foil and a cutting plotter
(vinyl cutter). In this approach, it’s an additive process where
instead of removing copper from a copper-clad board, the traces are
cut out of copper foil and transferred to a solid backing surface
(cardboard, fiberglass, etc.).

Hackaday: Making PCBs with a cutting plotter
Cricut copper PCB


text:
Determine whether a variable is of an arithmetic type
Is there a way to determine whether a variable is of an arithmetic type or not?

arithmetic: integer, floating point numbers, boolean values
not arithmetic: pointers, references; e.g. strings, and probably all other implementation- and user-defined types. However if someone for some reason defines typedef int myInt myInt should be considered arithmetic as well (because it is!)

In a normal C++ program I could use std::is_arithmetic<T>::value, where T is the type I need to check, but this doesn't seem to work in the Arduino environment. (Am I wrong? If it works, could someone please tell me how to use it?)
I imagine I could make a list of allowed types, e.g. as described in this answer to a similar question (I'm referring to the second option, the Alternative). But given that I don't need to exactly know the type of T I was wondering whether there is a more elegant and flexible solution...

Why do you need that? In a normal sketch you already know yours types.

What are you actually trying to do?

There are some ports of the std library for Arduinos, but I'm not sure if they have this in.  You could just look at the code and work out how its done and port it yourself.

I simplified the function I'm working on: template
bool myFunc (int a, T b) {
if(a*b > 100) return true;
}     --- EDIT: sorry, I forgot that code won't format in comments... I hope it's simple enough to be readable.

@noearchimede In comments, put the code in backticks. Read this for more info: https://arduino.stackexchange.com/editing-help#comment-formatting

@Majenko Actually I'm writing a set of functions (in a library) that operate on arithmetic values, and it doesn't make sense to call them with non-arithmetic types (it's like writing pow("two", "four"). However given that I'm using the library in many different projects, and also other people will use it, I would like to be able to catch such stupid errors (either at compile time or at runtime, that makes no difference (those functions all print text, so they could print "not a valid number")). If I can't do that I'll write a long list of overloaded functions instead of using templates.

Ok, that makes sense.  For Arduino code overloading is probably the simplest method. It's used throughout the core for things like print() etc. And you would only need to overload for the types you actually want to handle - then other types that don't "add up" you would just get a compilation error.

I don't think Arduino IDE supports boolean arethmatic

Thanks, I didn't think about that... but if there is an arduino-compatible way to determine whether a variable is of an arithmetic type it should automatically not include bool, right?

Is there a way to determine whether a variable is of an arithmetic type or not?

no. end of the day, those are just bit pieces and it only makes sense to the computer with the right context. Another way to put it, the same bit pieces can and will mean different things under different situations.

I know that reading 4 bits representing a float as a long will give a valid but meaningless value. But the computer must somehow know how to interpret those bits, right? Either at compiletime or at runtime the type of each variable/set of bits must be known, and the property arithmetic/not arithmetic must also be known somehow: don't I get an error message if I try to do myClass + aString? (btw., may this be a solution to my problem? Try do do some arithmetics on the variables passed by the caller and output an error if it isn't possible to do so? Could that work, and if yes what could be...

...an elegant implementation? (I mean, an error like "unable to do myclass+astring" wouldn't be very clear to someone who doesn't know the implementation of the function he is calling)


text:
MAX7219 with Arduino UNO - LED control doesn't work
I'm very new to Arduino and this is my first project, so I may misunderstand something simple.
As a hardware I'm using 4 MAX7219 connected to Arduino UNO and a single diod for tests.
As a software I have Waoyda's LedControl 1.06 for MAX72XX.
It seems, I'm completely missing something, because with the code below, the diod is never lit, regardless on matrix position it is connected to.
#include "LedControl.h"

LedControl lc=LedControl(12,11,10,4);

void setup() {
  int devices=lc.getDeviceCount();
  for(int address=0;address<devices;address++) {
    lc.shutdown(address,false);
    lc.setIntensity(address,8)
    lc.clearDisplay(address);
  }
}

void loop() {
  int devices=lc.getDeviceCount();

  for(int row=0;row<8;row++) {
    for(int col=0;col<8;col++) {
      for(int address=0;address<devices;address++) {
        lc.setLed(address,row,col,true);
      }
    }
  }
}

Some high res photos: 1, 2, 3
UPD: scheme added.

OK, I'll ask the stupid question first.  No offence intended but have you plugged the LED in the right way around?  Secondly can you by pass the chip and provide power to the row and columns and see the LED light?  Are you connecting this to a separate power supply (I doubt the Arduino will run it) and if you are using a separate PSU have you connected the grounds?

@CodeGorilla If I use one of the default examples, "07.Display > RowColumnScanning", then the diod is being lit on every position. So, it seems, everything is fine with the diod, board and power.

Could you show us your wiring?

Add some debugging to the code. The way to do it is using the serial port and print out result like "int devices=lc.getDeviceCount();" so you can verify that it find the MAX chip(s). A god tutorial on serial: http://www.oxgadgets.com/2011/07/arduino-serial-communication.html

@tuskiomi added scheme

@MatsK lc.getDeviceCount(); shows 4.

OMG, the only problem was a typo in LedController initialisation! I used LedControl lc=LedControl(12,11,10,4); instead for LedControl lc=LedControl(11,12,10,4);. It seems the library has no error detection if passed data pin isn't really a data pin. Now everything works fine.

please give credit to those that supported you to find a solution.


text:
FreeRTOS : Create Tasks but don't start Scheduler
I'm using FreeRTOs on Arduino for the first time. In my setup(), i would like to create my tasks but i have few more configuration to do after so i would like to create my tasks but don't start the scheduler immediately.
This is my code currently with xTaskCreate and vTaskScheduler, but my code start the task immediately when they are created :
   //Create Tasks
   s1 = xTaskCreate(TaskAcquisition, NULL, configMINIMAL_STACK_SIZE, NULL, 2, &Acquisition);
   s2 = xTaskCreate(TaskStockage,NULL,configMINIMAL_STACK_SIZE + 200, NULL, 1, &Stockage);

.... Some more config

   Serial.println(F("Config finished"));

  //Check errors
  if(fifoData==NULL || fifoSpace == NULL || s1 != pdPASS || s2 != pdPASS){
  Serial.println(F("Creation error"));
  while(1);
  }
  Serial.println(F("Fifo and Tasks created"));

  //starting
  vTaskStartScheduler();

  //if the scheduler start the code don't came here
  Serial.println(F("Ram issue"));
  while(1);

Thanks for your help !

I'm voting to close this question as off-topic because it is entirely about FreeRTOS, and not at all about the Arduino on which that is running.  You really need to seek help in a FreeRTOS forum.

You need to vTaskSuspend the tasks immediately after creating them.
Then when you need a task to run you vTaskResume it.


text:
Different behavior when Arduino Micro powered by laptop USB vs portable charger USB
I'm working on a project that uses an LM35 temperature sensor to control a few LEDs. Above 97 degrees, one LED should switch on. Below 95 degrees, it should switch off and the other should switch on. In between those temperatures, the LED state should remain unchanged.
When the Arduino Micro is plugged into my Macbook USB port, everything functions as I expect, however when I plug the same USB cable into a different USB power supply (like a portable cell phone charger), the LEDs tend to blink back and forth at the frequency at which I tell the Arduino to check which state the LEDs should be in.
The only thing I can think of that is different between the laptop USB and battery is the lack of serial data being read by the battery. Unclear, though how I can fix this issue. Any suggestions would be appreciated.

Can you show a schematic of your wiring of the sensor (complete circuit would be most helpful), as well as your code?


text:
Reading multiple NTC temperature sensors with Arduino
Hej..I am building a project with four NTC 10k ohm temperature sensor with Arduino. It is easy to measure only one NTC temperature sensor. There  is many examples for NTC measurement for example code written with Steinhart-Hart Equation or reading  ADC Thermistor with Lookup Table.
I found one example with Steinhart-Hart Formula.  I am not so good at coding  with Arduino but I Manage and build to write code for only one NTC sensor and read it with Nokia LCD 5110.  The question is how to do code for Multiple NTC sensors?
/* NTC temperature mesurment 13-08-2017
 *
 *  Using Nokia LCD 5110
 */

#include "LCD5110_Graph.h"
LCD5110 myGLCD(8, 9, 10, 12, 11);  // Setup Nokia 5110 Screen SCLK/CLK=5, DIN/MOSI/DATA=6, DC/CS=7, RST=8 Chip Select/CE/SCE=9,
extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];

int tempPin = 0;   // A0 analog input
int Vout, charTc ;
float R1 = 10000; //otpornost na sobnoj temperaturi 10K ili 10000 oma
float R2, Tk, Tc;
float Ac = 1.009249522e-03, Bc = 2.378405444e-04, Cc = 2.019202697e-07;
char charBuffer[10];

void setup(){
myGLCD.InitLCD(); //initialize LCD with default contrast of 70
myGLCD.setContrast(68);
myGLCD.setFont(SmallFont); // Set default font size. tinyFont 4x6, smallFont 6x8, mediumNumber 12x16, bigNumbers 14x24
myGLCD.clrScr();

myGLCD.print("Temp test",CENTER,0);
myGLCD.print("Check",CENTER,12);
myGLCD.print("Please Wait",CENTER,24);

myGLCD.update();
delay(5000);
myGLCD.clrScr();
}

void loop() {
  Vout = analogRead(tempPin);
  R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
  Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Klven
  Tc = Tk - 273.15; //temperature converted to celcious

charTc=dtostrf(Tc, 3, 2, charBuffer);

  myGLCD.clrScr();
  //myGLCD.print("Discharging",CENTER,0);
  //myGLCD.print("Temperature:",CENTER,0);
  myGLCD.print("Temp1:",0,0);
  //myGLCD.print( charTc,CENTER,20 );
  myGLCD.print( charTc,36,0 );
  myGLCD.print("Temp2:",0,10);
  myGLCD.print("Temp3:",0,20);
  myGLCD.print("Temp4:",0,30);
  myGLCD.update();
  delay(2000);
  myGLCD.clrScr();
}

The row int tempPin = 0; // A0 analog input specify which analog input that should be used as input for reading the NTC value. Then you can expand the code with the analog inputs that is needed.

Thanks for you reply. Yes i know that Arduino has 8 ADC input. But my desire is how to do interval time execution for many ADC input. Is it best way to write timer interrupt? for every analog input to Execute every 2 seconds if the reading is changed of adc?

The row int tempPin = 0; // A0 analog input specify which analog input that should be used as input for reading the NTC value.
Then you can expand the code with the analog inputs that is needed.

Arduino UNO has 6 Analog pins ..
Sequentially Read ADC every 2 seconds either by calling the Respective ADC functions inside a TIMER_INTERRRUPT_VECTOR() or if high Accuracy is not Required you can restrict your main loop() to be small and write all ADCs inside it.
Also make sure that you sample your ADC if writing inside loop to make sure that its accurate.

You don't need interrupts to sample every 2 seconds. Just do it directly in the loop().

Yes..both the ways it can be done ,writing in loop is simple but it's always better to make your loop () run at shortest time..if planning to modify the code in future .one more option is to create individual tasks and make all ADCs run independently but little complicated

As I understand, you have multiple analog sensors you want to read. So your code should look something like this:
// assuming sensors are on A0, A1, A2, Ax

sensorPins [] = {A0, A1, A2};
int sensorNum = 3;

for(int x = 0; x < sensorNum; x++){
  readSensor(x);
}

Something like that should work for you.

Put in multiple analog input pins and read them sequentially;
Put in multiple analog input pins and scan them in the adc interrupts.

the first approach is quite simple and the 2nd approach requires a thorough read of the datasheet.

This is pretty simple. Create an array of uint_8 variables that contains your pin numbers.
Then write a function that takes a pin number as an input, reads the ADC, does the math, and returns a value.
sensorPins [] = {A0, A1, A2, A3};

float readTemp(int tempPin) {
  int Vout = analogRead(tempPin);
  float R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
  float Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Kelven
  Tc = Tk - 273.15; //temperature converted to Celsius
  return Tc;
}

Then write a loop that loops through your array of pin numbers and calls the readTemp function.


text:
Arduino only sends HTTP 1.0 requests
I'm trying to connect to an http server that uses HTTP 1.1, my problem is that even thought the request is in HTTP 1.1 format and the server does actually use HTTP 1.1(I tried it in a browser) it only responds with HTTP 1.0. I'm using this modified example of the web client, I updated the Ethernet library yesterday and for my server I'm using Node 8.4.0, I'm testing with google first even though I know the server can respond with HTTP 1.1.
Ethernet shield model: Han Run HR911105A 16/02
Arduino: Mega 2560
 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
  client.print("GET / HTTP/1.1\r\n");
  client.print("Host: www.google.com\r\n");
  client.print("Content-Type: application/x-www-form-urlencoded\r\n");
  client.print("Cache-Control: no-cache\r\n");
  client.print("\r\n");
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
}

With this I get the following response:

Thank you in advance

How does a 302 benefit from being HTTP 1.1?

It's just a test :P I don't really care about the result in this one, I just need an http 1.1 response so I can then connect the arduino to a socket.io server
I've tried many times with the 2 other servers and the only type of response I get is 1.0---OP

Did you try using a URL that returns a 200?

Han Run HR911105A 16/02 -- I do love the way people keep quoting the model number of the RJ45 socket as the board model...

Ignacio: I did try, the response is the following:
The reason for the bad request is because the handshake in the socket.io library needs an http 1.1 response, for this it sends 2 get requests. The library is washo4evr's library for socket.io.
http://i.imgur.com/qW2WVRH.png

The device sending the request has no bearing on if it is HTTP 1.0 or 1.1. Only the content has an effect.
That and what is in the path - and I suspect that may be your problem: your are going through a squid proxy - and an old version at that. It is most likely that the proxy is changing the request to be a 1.0 request instead of a 1.1 request.

Thank you: Turns out the local network where I was connected had an IP in this format:
xxx.xxx.70.xxx
And my IP was: xxx.xxx.80.xxx
Therefore the proxy was making the response go from 1.1 to 1.0


text:
How to get the angle from vertical window blinds
How can i know the angle of the vertical window blind by placing a small sensor on one of the blind slat
i am trying to make a arduino/esp8266 controlled window blinds, the controlling can be easily achieved in horizontal blinds, but my apartment has a vertical blind which are not interconnected at the bottom
Tried so far:

open and close based on time which it takes to open and close, but it keeps drifting over time
Cannot use light sensor to sense the ambient light, does not give correct information (day and night)
Tried to put a potentiometer on top of one of the blind slat ( no enough room to place things there, potentiometers have more friction)

any suggestions for angle sensor ?

Is this the sort of bind where you open / close or by turning a stick, or by pulling a string? Could you just start it in a known position, and let it keep track of where it is by how far it has turned - use a stepper motor so that you have predictable control of the movement.

A hall-effect sensor, plus a small magnet attached (glue?) to the outside edge of one slat ought to be able to tell you the strength of the magnetic field, and thus the distance of the magnet from the sensor. From that, given that the rotation is with a fixed radius, you can deduce the angle while introducing zero additional friction.
Edit:
I had imagined something like:

However, looking again, this introduces difficulty in detecting the 90deg position, where the magnetic flux lines are exactly parallel to the hall-effect sensor plane.
If you experiment with this enough, you may be able to get repeatable values from the sensor to know the angle of the blind slats.
Edit 2:
The timing measure you noted in your question could also be a possibility. If you could use a microswitch or photo-interrupt sensor on the extreme ends of travel (0deg and 180deg), so that any time those extreme ends are detected, you can eliminate drift.

Ya this sounds to be a good idea, Actually I can have a small magnet fixed to the bottom end of one of the slat, and place the hall effect sensor below it fixed to the base( i have some room below the slats for my window) , do you have good suggestions for cheap hall effect sensors  with rotating magnetic field .. Thanks @ Jose

just to know, does the hall effect sensor give you absolute value even when it loses power

If the sensor loses power, it doesn't work. If you mean, does it have to start from a "known value" after the power returns, then the answer is yes, it gives an absolute value. It measures magnetic flux through the plane of the sensor, which is not dependent on any initial position when power is first applied.

i was thinking this way http://imgur.com/a/whos7

A hall-effect sensor isn't going to work that way. It detects/senses magnetic flux "through" it, so simply rotating the magnet without moving it in the X or Y position relative to the sensor will not be detectable.

a cheap "tilt switch" (with a roller ball) could discriminate the extreme vertical state polarity...

@josecanuc, and forgot to mention, the other issue is that, these slats move like a pendulum (they are not steady in their axis)  when tried to change the angle, for this i can use a small magnet at the top of the slat holder and place a hall effect sensor on the window frame to eliminate the oscillation

@dandavis .. HOW ??  could you elaborate it

@SaiGanesh Given these difficulties, I would suggest to look for another place to put the sensor. Surely there is a cable/rope/chain that is used to adjust the angle -- can you put a potentiometer on the axle that is turned by that cable?

@josecanuc , thanks for the idea, while i was working with some GY-271 Compass modules, i figured this would be the perfect solution for my window blinds. I had my compass module stick to one of the window slat (perpendicular) and pulled some ultra thin copper wires to my board .. works Perfect now

How to get the angle from vertical window blinds

vertical blinds have by definition a 90degree angle.
unless "angle" means something else to you.

I believe each strip can rotate around the vertical axis, though...

each strip has ~180 degrees rotation angle along its own vertical axis

In that case, tie a weighty item at end of a rope and wind it over the shaft of a potentiameter. you can measure that potentiamiter's resistance by charging up a capacitor with it, or via an adc.


text:
Can I set pin 13 to output 5v, then put arduino mini pro to sleep?
Can I set pin 13 to output 5v, then put arduino pro mini to sleep and it maintains 5v going through pin 13 while in sleep mode?
I know there are various "levels" of sleep - can a voltage be maintained on a pin for all/any of the sleep modes?

Sounds like you interpret "sleep mode" as something that disconnects the MCU pins? What does the manual say about this?

@MikaelPatel Actually the manual is quite vague. It's possible to infer that the pins remain connected from the bit that tells you that to save power IO pins should not be driving resistive loads when you enable sleep, but that's about all.

@Majenko Yes, the Pin section of Power Saving is a bit vague but the I/O Ports chapter and circuit diagram gives some more details. Not driving resistive loads is not forbidden but should be avoided in low-power applications. The General Digital I/O circuit does not show any disconnect on sleep mode (which I think was the question).

can a voltage be maintained on a pin for all/any of the sleep modes?

yes.

I will be able to test this tomorrow and update with an accepted answer

Given the absence of clarity on the driving state of pins during sleep, consider connecting Pin 13 to an SR Latch or the gate of a MOSFET.
An SR Latch will hold it's output high or low until a high is presented on the Set or Reset inputs, so connect Pin 13 to the Set input, with a pull-down resistor -- even if the MCU in sleep mode allows the voltage output to drain away to 0v, the SR Latch will maintain it's output.
A MOSFET gate has a non-trivial capacitance which can hold a charge if the gate's driver goes high-impedance, thus holding the gate open after the driver is disconnected.

Thank you for the tips. I've never heard of SR Latches and they seem quite complex - well more complex than the mosfet.


text:
Arduino Uno - relay with separate power
i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC.
how should i connect it to the Arduino and the external power supply?

That doesn't look like a relay board set up for separate power supply. Those that do will have an opto-isolator per relay.

jVCC (where avail) is used to drive the magnetic relay coils, VCC is used to drive the logic/LEDs.

This relay is designed to operate on 5V.
Most commonly this will come from the Uno's 5v pin.
If you want to externally power the relay itself then make sure to connect the +5 to the Vcc on the relay board and the - lead to the GND on the relay board.
Uno's GND must also be connected to the GND on the relay so the Digital outputs from the Uno will properly control the IN1 and IN2 inputs to the relay board.

The Uno has multiple GND connections so it makes the most sense to connect the - to one of them then another to the relay.

Note that the Uno's 9V Vcc external power comes in through the barrel connector on the Uno itself. The Uno will pass power through its internal regulator to provide 5v at the appropriate connection.

If you are switching external devices that run on 120V it would be on the screw-terminal side of the board only.

To prevent accidental activation of the relays, note that this particular board is ACTIVE-LOW which means that as you initialize the output pins you should first set them HIGH so setting the pinMode will not default to LOW which would trigger the relay.

In the setup() section, using pins D5 and D6 as an example:
digitalWrite(5,HIGH); pinMode(5,OUTPUT);
digitalWrite(6,HIGH); pinmode(6,OUTPUT);

The question is "but i want to use a separate power supply for the relay".

The Arduino and the external PSU should have the GND or - connected with each other.
Then connect the external PSU + or Vcc to the relay boards Vcc.

Regarding jVCC see https://arduino-info.wikispaces.com/RelayIsolation .
It is used when you have optocouplers isolating the power supplying the relay coil from the Arduino's power (VCC).

External psu to gnd and vcc, in1 and in2 to arduino pins which control each relay (on is LOW) and most importantly gnd also to arduino gnd.


text:
Debouncing, or problem with my code?
I'm using a simple microswitch on pin 2, to activate an external interrupt.
void pause()
{
  Serial.print("\n\nPause\n\n");
  delay(1000);
}

void setup()
{
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(0, pause, RISING);
  Serial.begin(9600);
  delay(1000);
}

void loop()
{
  Serial.print("\nGoing");
  delay(100);
}

When I tap the micro switch, some reason, my serial monitor output looks like this:

Just to clarify, there is no delay between any of
Is this just some serious debouncing, causing my Arduino to find lots of rising instances? or is there some kind of problem in my code?

Just to clarify, there is no delay between any of - any of what?

Be careful using delay functions in an ISR!!! Read the italics: https://www.arduino.cc/en/Reference/AttachInterrupt

I have a page about using switches but since I don't want to give a link-only answer I'll summarize here.

Detect switch changes
What is needed is to detect a transition. That is, either:

It was closed and is now open.

Or:

It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    if (switchState == LOW)
       {
       Serial.println ("Switch closed.");
       }  // end if switchState is LOW
    else
       {
       Serial.println ("Switch opened.");
       }  // end if switchState is HIGH
    }  // end of state change

  // other code here ...

  }  // end of loop

This code looks for changes, and only displays something when the switch changes.

By the way, you should be doing neither delay nor Serial.print inside an interrupt, as both of the rely upon interrupts being active, and interrupts are not active inside an ISR.

Debouncing
A simple technique is just to build in a short delay, for example 10 milliseconds (ms). For example:
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    delay (debounceTime);   // debounce
    if (switchState == LOW)
       {
       Serial.println ("Switch closed.");
       }  // end if switchState is LOW
    else
       {
       Serial.println ("Switch opened.");
       }  // end if switchState is HIGH
    }  // end of state change

  // other code here ...

  }  // end of loop

In the above code the delay is inside loop (where it is OK to use it) and causes a short pause to allow the switch to stop bouncing.

Debouncing without delay
The above code is fine in simple applications, and if you test it, you should find that the message "Switch closed." and "Switch opened." should only occur once per switch press. But, there's a problem. If you hang around the Arduino forums for a little while you will probably see people telling you "don't use delay". There are various reasons for this, not the least is which that using delay stops your code from doing anything else useful (like testing sensors, controlling motors, flashing LEDs, etc.).
The code below does not use delay, but rather checks for the time that has elapsed after you hit the switch, and sees if the "debounceTime" (in this case 10 ms) has elapsed. If not, it ignores the transition.
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds
unsigned long switchPressTime;  // when the switch last changed state

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    // debounce
    if (millis () - switchPressTime >= debounceTime)
       {
       switchPressTime = millis ();  // when we closed the switch
       oldSwitchState =  switchState;  // remember for next time
       if (switchState == LOW)
          {
          Serial.println ("Switch closed.");
          }  // end if switchState is LOW
       else
          {
          Serial.println ("Switch opened.");
          }  // end if switchState is HIGH

       }  // end if debounce time up

    }  // end of state change

  // other code here ...

  }  // end of loop

More information on the Arduino site: http://arduino.cc/en/Tutorial/Debounce

It is essential for me to use an interrupt, because I need to be able to pause my entire program, at the push of a button, then resume it when the button is pushed again. I heard from other people that I cannot use any type of delay in the interrupt, is this true?

You don't really pause a program with delay, it is now just doing something else (waiting for a timer to reach a certain time). Timers depend on interrupts to update counters as the hardware timer will overflow (roll over) very rapidly.
I suggest a redesign. In your main loop, for example, you could detect the switch press, and then not do anything until it is pressed again. For example, where I had "other code here" in my example:
static bool switchWasPressed;

if (switchWasPressed)
  {
  // do nothing
  }
else
  {
  // do what you want to do continuously
  }

Now, in the code which detects switch presses you toggle switchWasPressed. So instead of:
Serial.println ("Switch closed.");

You put:
switchWasPressed = !switchWasPressed;  // toggle switch press state

It is essential for me to use an interrupt, because I need to be able to pause my entire program, at the push of a button, then resume it when the button is pushed again. I heard from other people that I cannot use any type of delay in the interrupt, is this true?

No, it isn't essential to use an interrupt. Interrupts are not for lengthy pauses. See my extended answer above.

Do you really need to use an interrupt to debounce a switch? If not, this library may work for you: https://playground.arduino.cc/uploads/Code/Debounce.zip. It is easy to use and assumes you are using a normally open switch with one connection to ground and the other connected to pin 4 on the Arduino.
    #include <Debounce.h>
    const byte SWITCH = 4;

    Debounce debouncer = Debounce(50, SWITCH);

    void setup(){
      Serial.begin(9600);
      pinMode(SWITCH, INPUT_PULLUP);
    }

    void loop(){
      if(debouncer.update()){
        if(debouncer.read() == 0){
          Serial.println("Button Pressed");
        }
        else if(debouncer.read() == 1){
          Serial.println("Button Released");
        }
      }
    }

Yes, it is bouncing of your button.
You are seeing it because delay() does not work, and cannot be used, in an interrupt.
Also delaying in an interrupt is completely opposite to the whole ethos of interrupt programming.

Thanks, but is there a way for me to put a delay in the interrupt, so the second I press the button it just pauses before any debouncing can occur?

No, but you can record the time the interrupt occurred (hint hint)

your code works as coded - whether it works as expected is unknown.
basically the isr is triggered on the first edge, and the execution loops around in the isr, and the execution returns one second later.
As a result,  your code missed most of the "bouncing", actually it missed all bounces other than the very first one.
not an effective debouncing strategy.
yes, delays or while loops can be used in an isr, so long as you know what you are doing.

Please take the time to use proper English on this site. Proper English includes starting sentences with capital letters. As a reasonably high-rep user, who posts a lot of useful answers, you are setting standards for others to follow. Please take the time to capitalize your sentences correctly. Thanks!


text:
Sim808: Is My GPS Module Broken?
Is my GPS module broken?
My GPS returns $GPGGA,000250.262,,,,,210,,2,700,,*4C as NMEA. Why there is no latitude longitude? the first value is the UTC time, but there are so many null values ,,,,, Is my GPS module broken?

Edited
My Sim808 model is SIM808 Module GPRS SMS Development Board IPX SMA with GSM GPS Antenna

What makes me think why is this broken is because the day before, the module keep giving me location for every second. The lock was almost instant. I use the module at the same place like before. It is weird because the module is so unstable, yesterday was fine but the next day it takes forever to lock location.

More likely it just hasn't got a lock on any satellites. What antenna do you have and where is it all situated?

Many fields will empty until the unit can get a lock. $GPGSV messages will tell you how many satellites it currently sees, and how strong the transmissions are. The first lock can take several minutes, and it can be very difficult to get a lock indoors.


text:
Reading HC05 Output
I am using an Arduino Mega connected with a motion sensor and HC05 bluetooth chip to transmit distance data to a larger computer, process it, and send a data back. Currently, I am having trouble receiving/reading bluetooth output received from the program running on my PC which is successfully receiving data from the HC05 chip. I am using the Serial Software library to process serial input/output to the Arduino Mega. Having probed the output of the HC05 chip that serves as return stream of decision data to the Mega, I see that the magnitude of the waveform is around 3V. My guess is that for the Arduino and Software Serial library to process this input, it must be at 5 volts, just like the output, for which I had to build a voltage divider so that I could provided the specified 3.3 V to the HC05 input. Clearly if the output at TXD from the HC05 is 3.3V then the Mega will receive 3.3 volts at PIN4, the receiving pin.
Here is a basic diagram without the sensors or motors. Exact resistances are not provided but should not affect the issue.

I have provided the code below for Arduino-side operation.
/*
    This module uses the L293D chip to modulate and power
    two DC motors controlling the wheels of the FryeBot
*/

#include <SoftwareSerial\SoftwareSerial.h>

SoftwareSerial mySerial(4, 2); // RX, TX

/*L293D INPUT 7*/
const int YELLOW_GEAR_MOTOR_BACK = 8;

/*L293D INPUT 2*/
const int YELLOW_GEAR_MOTOR_FORWARD = 9;

/*L293D INPUT 10*/
const int RED_GEAR_MOTOR_BACK = 10;

/*L293D INPUT 15*/
const int RED_GEAR_MOTOR_FORWARD = 11;

/*
    Establish ratio os the rate of the faster slower gear
    to the faster gear to scale the duty cycle of the
    faster gear
*/
const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

/*Constant for full duty cycle for analogWrite*/
const int FULL_ANALOG_MOTOR_SPEED = 255;

const int pingPin = 7;

long duration, cm;

char buf[10];

char current;
String messageHolder;
String message;

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

    /* add setup code here */
    pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);

}

void loop() {

    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

    cm = microsecondsToCentimeters(duration);

    Serial.print(cm);
    Serial.print("cm");
    Serial.println();

    /* Load the distance value into a buffer */
    String sendValue = String(cm);
    sendValue.toCharArray(buf, sizeof(buf));

    /* Write the buffer with a space after for parsing*/
    mySerial.write(buf);
    mySerial.write(' ');

    /* Stop if too close to an object */
    //Serial.print("current: ");
    //Serial.print((int)current);
    Serial.println();

    if (message != "STOP_MOTORS") {

        analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
    }
    else {
        digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
    }

    current = mySerial.read();
    Serial.print((int)current);
    Serial.println();

    if (current == ' ') {
        message = messageHolder;
        messageHolder = "";
    }
    else {
        messageHolder += current;
    }

    delay(100);

}

long microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
    return microseconds / 29 / 2;
}

I am using the Serial Software library to process serial input/output to the Arduino Mega. ... Why on earth would you do that when you have three hardware UARTs...?!?!?!?!

I mean is the hardware implementation significantly better than the software one

Well.... yes? Massively better. You should only use SoftwareSerial when you absolutely must.

Ill give the UART a try and get back to you with the results. I'm assuming I should keep the voltage divider leading to the RX of the HC05?

Yes. It's still 5v logic.

So I implemented the UART approach with the same results, I can transmit data through the HC05 but the HC05 is either not receiving the data that is being sent via bluetooth from the PC or the Arduino is failing to read the data that the HC05 is successfully receiving. My guess is I need to step up the voltage from the 3.3 V output of the TX of the HC05 to 5 V for the UART RX to be able to read this. Perhaps I can use a basic bjt transistor network with 1 arduino output at high at the collector, the tx from HC05 at the base and the input to the UART RX at the emitter?

You may want a logic level translator, yes. 3.3v is at the bottom end of VIH.

The thing is I already have the transistor (bought them a year ago) and the source (any 5V arduino output pin). My only worry is that the output from the bjt transistor at the emitter might lag the input to the base (from the HC05) which is probably on the order of MHz. Would prefer not buying additional hardware is possible.

Why do you think MHz for 9600 baud...?

You're right. Didnt think of that. Still, even at 10kHz, the bjt wont lag?

Why would it? And what would it matter if it did? It would lag BOTH sides of the signal and the signal would be the same with a slight offset. Mind, what do you think it is that is used in high frequency oscillators and things? BJTs. They can go to many hundreds of MHz no problem.


text:
Using ESP8266-01 with Arduino uno R3
I am trying to learn how to use ESP-01(AI-Cloud, Black Version) with arduino
Initially, I created an adapter for it that has 4 inputs: RX, TX, Vcc(3.3v), GND I checked it and the wiring seems fine then I attached TX of arduino to TX of ESP and same with RX but with a voltage divider (1k ohm,2kohm),I uploaded arduino with a blank sketch and tried to run commands like AT and AT+CWMODE? but I got no response on the serial monitor.I tried to look for a proper tutorial to do this but, all tutorials show how to upload a sketch to ESP rather than arduino. Then I searched and found this piece of code:
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                            // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                            // and the RX line from the esp to the Arduino's pin 3
void setup()
{
 Serial.begin(9600);
 esp8266.begin(115200); // your esp's baud rate might be different

 sendData("AT+RST\r\n",2000,DEBUG); // reset module
 sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
 sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
 if(esp8266.available()) // check if the esp is sending a message
 {
   /*
   while(esp8266.available())
   {
     // The esp has data so display its output to the serial window
     char c = esp8266.read(); // read the next character.
     Serial.write(c);
   } */

   if(esp8266.find("+IPD,"))
   {
    delay(1000);

    int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                          // the ASCII decimal value and 0 (the first decimal number) starts at 48

    String webpage = "
Hello
&lth2>World!
<button>LED1</button>";

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

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

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

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

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

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

    sendData(closeCommand,3000,DEBUG);
   }
 }
}

String sendData(String command, const int timeout, boolean debug)
{
   String response = "";

   esp8266.print(command); // send the read character to the esp8266

   long int time = millis();

   while( (time+timeout) > millis())
   {
     while(esp8266.available())
     {

       // The esp has data so display its output to the serial window
       char c = esp8266.read(); // read the next character.
       response+=c;
     }
   }

   if(debug)
   {
     Serial.print(response);
   }

   return response;
}

I hooked pins according to the code and it worked serial monitor output some lines but with allot of garbage values, This also created a wifi hotspot 'AI-Thinker' which I connected to and opened Ip as shown on debugging. This made ESP try to send string 'webpage' but mostly was garbage.
so my question is, how to properly use esp with arduino to maybe just switch an led on or send data from sensors, super basics?
Is it better to use esp Library and upload sketches to esp and control arduino with it?
Can some one suggest the proper tutorial for this? because even after all this I am still confused that is RX of arduino connected to RX(which makes no sense but given in many of google images) or TX of ESP-01?

Start troubleshooting the serial connection, Arduino <-> ESP01. In the https://www.arduino.cc/en/Tutorial/SoftwareSerialExample you find a example that copy data from Serial (PC) to SoftSerial (ESP01). And Rx is supposed to go to Tx and vice versa. Arduino digital pin 0 (Rx) connects to ESP01 pin 2 (Tx) and Arduino digital pin 1 (Tx) connects to ESP01 pin 7 (Rx).

Possible duplicate of ESP8266 + Arduino Uno: Can't send AT Commands

"Is it better to use esp Library and upload sketches to esp and control arduino with it?"? YES!

@MatsK I was really confused and found that Tx-Rx used when there is need to send commands from arduino code & Tx-Tx used when there is need to send commands from arduino serial monitor this is when arduino isattached to pc via usb, Is this right ?

@dandavis thanks, so I should use my arduino and its IDE to upload sketches to ESP8266 , and then through ESP's Tx Rx pins control arduino and its sensor because I don't have any ftdi chip ,or 3.3v voltage regulator and hoping arduino is enough for this ?

Please remove the part "is it better...", that makes your question opinion based and worth closing. Also you should make only one question: this is not a forum.

To confirm that the serial communication is working, connect the ESP to the Arduino D10 and D11 that is used as SoftSerial pins.
+----+
| PC |
+--/-+
   |       +---------+
   \-------| Arduino |
     USB   +--.------+
              | SoftSerial
              |
           +--\----+
           | ESP01 |
           +-------+

And then upload this code to the Arduino. The code is from https://www.arduino.cc/en/Tutorial/SoftwareSerialExample
/*
 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of ESP01)
 * TX is digital pin 11 (connect to RX of ESP01)

 Created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.
 */

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ;
  }

  Serial.println("Goodnight moon!");

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  mySerial.println("Hello, world?");
}

void loop() {

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

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>

...

SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX);
WiFiEspClient WIFI_CLIENT;

...

void setup() {
  wifiSerial.begin(9600); // or 115200
  WiFi.init(&wifiSerial);
  if (WiFi.status() == WL_NO_SHIELD) {
    printLog("WiFi shield not present");
    // don't continue
    while (true);
  }
  printLog("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  printLog("Connected to AP");
}

...

The TX pin of the Arduino goes into the RX pin of the ESP and vice versa: that's the way serial communication works, apart for voltage level considerations.
Another factor you have to take into consideration is the two devices MUST operate at the same speed, once known as Baud Rate: I believe 115200 might be the ESP default speed, but that's programmable.
There are also other two additional parameters which play a role in serial communication, Parity and Data bits, but the default values are more than likely fine and you shouldn't worry about those.
So, in essence, verify your wiring and set the right speed considering some ESP modules run a firmware using non standard speed for serial comm.


text:
Connecting multiple boards to Arduino Uno r3
How can I connect the Arduino RFID RC 522 and SD card adapter to one Arduino Uno R3? As each library takes specific pins in Arduino for MOSI, MISO, CLK. So I have conflict in the pins, how can this be solved?

Short answer: yes, you can. No pin conflict, but you will need an extra SS pin for the second SPI device. [If you can, use the I2C version of your device.]
Unlike the I2C, the SPI bus uses separate lines for sending and receiving data, and it employs an additonal line (SS, SS1, SS2, ...) for selecting which slave device you are talking to. This adds additonal wires, but also eliminates needing different slave device addressses. So what this means is instead of specifying the address of the slave device, we simply address that slave device by turning on its SS pin. It's a lot more simple.
So, if you have two devices (RFID reader and SD Card Adapter), the conections looks like this:

The thing is, you need to use two Arduino pins for selecting the devices you want to talk to: one pin select the RFID reader; the other, the SD card.
Arduino has a fixed pin assignment for SPI comunications:

Because all devices share the MOSI, MISO, and SCLK lines, all commands sent from the master arrive at each slave device. The SS pin tells the slave whether it should ignore this data or respond to it. Importantly, this means that you must make sure to only have one SS pin LOW.
So you can see now how it's a minimum of four data lines that must be present in any SPI system. The MISO, MOSI, and SCLK signals are shared common with all slave devices. However, the SS chip cannot; it must be separate, because each slave device needs its own unique connection so that it alone can be addressed when the master device wants to communicate with it. So for each additional slave device that you add, you must have an additional line available on the master device for that slave device. So, using the above diagram as an example, if we have added a third slave device, we would have to add another SS3 data line to the master device and then connect to the SS pin of that third slave device.

Is the SS pin on a slave device also called as a "Chip Select" pin (CS)?


text:
DHT11 returning incorrect values
I am trying to use DHT11 sensor with Arduino. But unfortunately it is returning following values:
Temperature = 1.00
Humidity = 2.00
My code is as follows:
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

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

void loop()
{
    int chk = DHT.read11(DHT11_PIN);
    Serial.print("Temperature = ");
    Serial.println(DHT.temperature);
    Serial.print("Humidity = ");
    Serial.println(DHT.humidity);
    delay(1000);
}

Link to the library I am using is here
I have connected +ve to 3.3 V
I have connected -ve to Ground
I have connected out to digital pin # 7

Current temperature of the room otherwise is 34 degree celsius and 62% Humidity

You have to call the functions:
#include <DHT.h>
#define DHT11_PIN 7
DHT dht(DHT11_PIN, DHT11);

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

void loop() {

    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();

   if (isnan(humidity) || isnan(temperature)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Temperature = ");
    Serial.println(temperature);
    Serial.print("Humidity = ");
    Serial.println(humidity);

    delay(1000);
}

Edit

It seems that you are using a different library. Can you tell me which library are you using for this code?

I'm using the Adafruit DHT library, here https://github.com/adafruit/DHT-sensor-library. I've been using it for more than a year; no complains.

Serial.begin(9600);  was missing so I added that in your code and I still get the same output as before.
Temperature 1 and Humidity 2

@Saad. I tested the same sketch on my lab. It works, but sometimes the DHT act funny. Check connections, place a 4.7K resistor between Vcc and Data Line.

Ahmm I am not quite good with circuits. So not sure if I am supposed to put one at both places or just use one resistor. And secondly I only have 10k resistors at the moment :O would they work?

It's a pull-up resistor You can use a 10K, as shown in my edited answer.

I have added pictures in the original question showing how i used resistor. Still getting same temperature and humidity

Let us continue this discussion in chat.

This is not a DHT11, DHT11 is blue, DHT21 is black, and DHT 22 is white.
It must be a DHT22 hence the wrong values.
EDIT : on your pictures the white case says AM2302, it's definitely a DHT22 the code must be adapted accordingly.

I had the reverse problem: I used a DHT11 (blue one) instead of a dht22 (white one). The value I got were in the 500`C for the temperature and the 1500% for humidity. Replacing the DHT11 by the DHT22 solve it.


text:
Best way to store files on Arduino
I was wondering what is the best way to store files on Arduino, I've seen that is possible using the SD Card module but I only want like 2/3 file texts so having a whole SD Card for that sounds a bit overkill, is there any other way to store files like that?
Cheers!

How much data are we talking about? How is the sketch using the data? Read every startup, read on processing input, write on..., etc.

If you want files, then you need a filesystem. The only simple to use and reliable things on an Arduino that have a filesystem are SD cards or USB memory sticks through the USB Host Shield.
However, most of what people think they want to store in "text files" is actually data that can better be stored in other ways. Using text to store numeric values that only the Arduino will ever see is pointless - store it as numeric values.
The most convenient place to store such values (if you don't have lots of them) is in the internal EEPROM.
If you have more than a few values you can use an external EEPROM or serial Flash chip to store larger amounts of data.
Anything more than that, though, and SD card rapidly becomes the most cost effective method.

Thanks for the answer!
Is it a read only memory or can it be changed multiple times? For example I just want to store things like settings and variables like time, but I need it to be able to be edited after, like changing the time when ever needed.

@Matthew it is possible to read and write multiple times on the eeprom, but as far as I know there is a relatively low physical write cycles limit, i.e. you can change the value of a given bit only say 10.000 times. This is not a problem if you store settings, but you must avoid things like writing the eeprom in a frequently repeated loop. That said, it is quite simple to use it, I think there is even a dedicated library which comes with the Arduino IDE.

Microchip have invented what they call "EERAM" - an SRAM with EEPROM backup that saves its settings using energy stored in a capacitor when the power is lost. Infinite write cycles to the SRAM portion and EEPROM rated at 100,000 backups. Look for the 47C16.

There's nothing that says you can't have a filesystem on a serial flash chip - or for that matter, there is no requirement that you use a filesystem with an SD card or a USB stick.  If doing a lot of operations, the typical fact that one tends to be a fixed mapping of blocks and the other has a wear leveling algorithm does need to be considered, but at a simple level the same storage schemes can work.

@ChrisStratton Yes, I know. I have written block device drivers for flash chips, internal flash, SRAM chips, etc for chipKIT's implementation of sdfat. The biggest negative point to using an FS on a flash chip is that of wear levelling. You tend to get a disproportionate number of writes to a small number of blocks prematurely ageing the flash chip. An SD card is easy to swap when it dies, a flash chip isn't.

Best way to store files on Arduino

what's best (or not) depends on your criteria, which you didn't articulate.
The simplest (and dumbest) way is to use a sd card. generally a waste of space and pins for small files.
the 2nd best is to use flash or eeprom: limited space and potentially risky. this can be partially addressed via out-board storage devices.
the best is to not store files on arduino: transmit the content away and let more capable devices to handle that.

Yes, using an ordinary PC as an aid to Arduino is an overlooked option. We always have some old laptop that can be used for a lot of things: 1) As a clock (via NTP); 2) As a logger or database (no SD needed); 3) As User Interface (no keypad, no screen needed); 4) as an email interface (send/receive emails to the world). All you need is a WiFi connection.

The Arduino Uno uses the ATmega328P microcontroller. That microcontroller is able to write the EEPROM 100,000 times. As far as I know, that is 100,000 times per EEPROM location.
Suppose you want to run it for 10 years, then 10 years / 100k is about 1 hour. That means you can write to EEPROM every hour.
Storing settings is no problem. There is even a EEPROM.update function that only writes the data when the data has changed.
If you want to store the latest settings every second, then you need to look for something else.
Important note: When storing settings (in EEPROM or SD memory card) the Arduino could be powered off while it is busy writing. Those settings will not be valid. Therefor you might have to add a checksum, store a copy of the settings, and keep default settings in the code in case both the settings and its copy are not valid.


text:
Disabling Timer2
I am working on a Heart Rate Monitoring project, using this Sensor from sparkFun, plugged to Arduino pro mini and reading proper BPM, I have an LED connected to pin 13 of my Arduino that blinks when the pulse happen.
The code given on SparkFun page works on Timer2
I have two more LEDs connected to pin12 and pin11, which indicates battery percentage - because i am powering my Arduino using a 2 cell lithium ion battery with Voltage regulator.. I also have a voltage divider circuit at the voltage regulator with 1K resistors and connected to analog pin A0 for monitoring battery voltage.
I have assigned LED connected on pin 13 as LED1, on 12 as LED2 and 11 as LED3
LED1 for low charge
LED2 for half charge
LED3 for full charge
Here is the problem :
When i connect charger ,Arduino reads data from voltage divider and outputs levels to LEDS
Here - LED1 is conflicting between the pulse sensor (which is working on Timer2) and also for indicating the low level charging, and LED1 is flickering.
how to overcome with this issue.? disabling Timer2 helps.? if'Yes' then how to do that.?
Note : I don't want to sample Heart Rate Pulse when charger is connected!
Thank you very much.
Best
void charging() {
TCCR2A = 0;
usbState = digitalRead(usb_detect);
while (usbState == HIGH) {
usbState = digitalRead(usb_detect);
// read the input on analog pin 0:
int sensorValue = analogRead(A1);
// Convert the analog reading (which goes from 0 - 512) to a voltage (0
- 3.3V):
float voltage = sensorValue * (3.3 / 512.0);
// print out the value you read:
if (voltage >= 2.5 && voltage <= 3.3)
{

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }
    digitalWrite(gps_led, ledState);
    digitalWrite(blinkPin, LOW);
    digitalWrite(save_led, LOW);
  }
}

if (voltage >= 3.4 && voltage <= 3.7)
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(blinkPin, ledState);
    digitalWrite(gps_led, HIGH);
    digitalWrite(save_led, LOW);
  }
}

if (voltage >= 3.8 && voltage <= 4.1)
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(save_led, ledState);
    digitalWrite(blinkPin, HIGH);
    digitalWrite(gps_led, HIGH);
  }

}

Serial.println(voltage);

delay(1);        // delay in between reads for stability

}
}

What code are you running? The "Getting Advanced Code"? Or something different?

I suggest you just change what pins you use for your LEDs. One function per LED. Trying to use one LED for two functions is a bit daft really. What do you want the LED to be - low charge, or pulse? Make your mind up.

Yes, I am running "Getting Advance Code" from SparkFun page..
I cannot change or add more pins to my system, it's sealed in an enclosure..

Timer 2 is fundamental to that code. It is used to sample the heart rate sensor at a regular period. If you disable that timer you will never sample the sensor.
You cannot have two functions on one LED - it makes no sense. You should decide on one and only one function to use that LED for. If you want to use it for the battery status then remove the code from the timer interrupt that controls the LED. If you want to use it to display the hear beat then you will have to make do with just two LEDs for your battery status.
If the two operations are mutually exclusive then yes you can disable the timer. Just turn it off, then turn it on again when you want sampling to start again.
Off:
TCCR2B = 0;

On (assuming you are using this
code):
TCCR2B = 0x06;

I can reset my Arduino using Software Reset when i disconnect the charger.
Which means i can disable timer when i connect charger and re-enable it when the arduino reset..?
Will this work.?

By the way! i don't want to sample Heart Rate pulse when i connect to charger.

See my edit....

Rather than clearing TCCR2A (the CTC mode), I would clear either TCCR2B (to stop the timer) or TIMSK2 (which leaves the timer running but disable the interrupt).

I have added TCCR2A = 0; in my code at charging(); ,Please see my edited question

I am unable to upload the code.
I have created a new call back function call charging(); when ever i connect charger, complier comes in this function. in the first line i have added TCCR2A=0;
and it didn't worked..
By the way, how can i upload my .ino file here.?

You don't upload code, you paste it into your question paying attention to markdown formatting.

@EdgarBonet I am not familiar with AVR timers. Feel free to edit my answer to change it to your suggestion.

Hey, I have not seen @EdgarBonet comment earlier, I have used TCCR2B = 0; and it seems to be working, I have to do some test to conclude..
Thank you very much.

Pease edit this answer, TTCCR2B = 0; worked :)
Thanks a lot

in the linked repo in the product page you linked there is a explanation page how to use the device without using timers buried at the bottom of a file:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/blob/master/PulseSensorAmped_Arduino_1.5.0/Timer_Interrupt_Notes.ino#L217
In essence instead of using the timer interrupt you put the sampling code in the loop() body triggered by a software timer and make sure that there are no delay() or busy loops happening in it.

I have used delay(); function in void loop

it's not that hard to rewrite the loop to avoid delay() though.

you provide lots of information that has nothing to do with your question, and at the same time omitted critical information that can help other help you.

how to overcome with this issue.?

the simplest would be to move the pins so they have their dedicated pins.

disabling Timer2 helps.? if'Yes' then how to do that.?

if you want to reuse the pins -> multiple functions on the same pin, you may have to code as such. For example, you disconnect the led briefly, read the pulse sensor, and then restore the led. if you do that sufficiently quick, you wouldn't notice that the led had been disconnected.
the feasibility of such approaches will depend on the sensors connected to that pin and your ability to code.