text:
Wrong analog reading
I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.

I don't understand the description of your schematic. Please draw it instead.

Basically I am trying to read the battery voltage, using A3 on Arduino Nano, but it show higher value than it is supposed, which is really weird.

How are you powering the Arduino? How are you calculating the voltage?

I am powering it from USB wall socket; I measured it and it outputs 4.92V. Well I am calculation the voltage by multiplying analogRead * 0,00488281

Well, with those figures I calculate it at (870/1023*4.92) 4.184V. How much do you trust your multimeter?

Well, I was thinking about that (my DMM was showing low battery for a while), but my charger is set to charge the batteries to 4.1V, and this is not a fresh battery, so from that reason I thought there must be a mistake somewhere....

I assume both measurements where unloaded?

I don´t fully understand the question... I measured it with the relay closed, if it is what you are asking....

When that relay closes, are you shorting the battery to ground through 10.2 ohms?

@NickGammon That sounds like a bit of an incorrect question there - shorting implies no resistance - the 10.2Ω implies (for a 3.7V battery) a discharge current of (initially) 363mA.  The latter isn't a short, it's a way of draining the battery while remaining well within the allowed current rating.

I have found the answer. I am not an arduino-newbie, but I was thinking that probably I am making a stupid mistake somewhere. But the problem is in my arduino. I tried setting pin D13 (and then all other pins) to HIGH, and I only measured 4.60V! I measured my USB port and it outputs 5.00V exactly, so there must be a problem in the arduino. So the solution - the ADC takes 4.60V as 1023, and therefore if you calculate it you get that the real voltage is 3.90V, which is exactly the same as my DMM said. Thanks Majenko, you were pointing the right way :) By the way, I was using a cheap Arduino Nano from China, I bought it only for 2.2 USD from Ebay. When I used original Arduino, the code and circuit perfectly works. Do you think that this can limit the functionality of my board?


text:
GPRS shield - Hayes commands to identify a faulty SIM connection
I'm currently battling with a LinkSprite GPRS shield (it's based on the SIMCom SIM900 chip) and seem to have absolutely no luck trying to connect to the network.  I've got two SIMs, both of which should be active, but I cannot get the connection light on.
I've got a serial connection going and it's responding to various AT commands, but I can't connect:

AT+COPS=?

is working, and giving me a list of networks, so I think my antenna is good, but

AT+COPS=-whatever-

immediately gives me +CREG: 3.
I'm now wondering whether there's a fault with my board, and that it's not seeing the SIM cards.  A few commands that I thought would work aren't, for example:

AT+CPIN?

just returns ERROR
Similarly, when trying to read SMS data:

AT+CMGL="ALL"

returns ERROR.
Have I proved that the board isn't seeing the SIM, or is there something definitive I can try?
Thanks in advance!

Having exchanged the board for another one (that works!) I can now confirm that the calls above (e.g. AT+CMGL) should work if there is a working SIM connection.

Are the boards identical? Or are they of different versions/manufacturers?

They were identical.

source: Stack Exchange

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

sort: votes


text:
does INPUT_PULLUP uses power?
When using a digital pin as input, one has the option of using the internal arduino resistor, which is connected to VCC; that is setting the digital pin as INPUT_PULLUP, and then the pin reads HIGH. Does this uses electricity?.
I mean the resistor is connected directly to VCC and I presume electricity is constantly flowing through the system, no?.
as oppose to having the pin as just INPUT?

I presume electricity is constantly flowing through the system - only if there is a load. With no load there is nowhere for it to flow, except as leakage current, as Ignacio Vazquez-Abrams said.

You can measure the current when using INPUT_PULLUP. https://hackingmajenkoblog.wordpress.com/2016/08/12/measuring-arduino-internal-pull-up-resistors/  I measured mine on a 3.3v 328p 8mhz and I calculated it to be 0.108ma

Only the leakage current on the input itself is constantly consumed if there is no external connection. This is usually much less than the waste caused by having the input floating.

If a voltage between 0.8 V and 2 V is applied to the input for a prolonged period of time, this situation becomes critical and
  should not be ignored, especially with higher bit count and more dense packages [...]. For example, if an 18-bit
  transceiver has 36 I/O pins floating at the threshold, the current from VCC can be as high as 150 mA to 200 mA.

There is not really a load applied to the pin with the INPUT_PULLUP.  I am using only for a push button, for a counter.

The pullups have a value between 20k and 50kOhm. If the input is connected to ground (button pressed), between 0.1mA and 0.25mA is flowing through the resistor. So bare anything.

What happens if the switch is open? Does it use power?

@Basj basically; no current will go though the resistor when the switch is open. Though I found out there is a tiny amount (1 µA max) of leakage current

See Deviation of power consumption between datasheet and real world? - there we established that leaving the pins input consumed considerably more power than input_pullup. That was with the pins not connected to anything.

Is there a typo here or am I reading wrong?   You said leaving pins as INPUT is more than INPUT_PULLUP, but your experiments show 0.35 µA for INPUT and 1.25 µA for INPUT_PULLUP

@rfii Yes, I did say that, and indeed it contradicts what I wrote. However as a general principle you are not supposed to leave chip inputs "floating", and configuring for input, with nothing connected, does that. You would probably get variable results depending on what noise was present near the inputs. I should probably re-measure the examples I gave on the quoted page.

Thanks your website is very helpful in how it tests everything so orderly

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


text:
A knob that can be turned by hand, have the position read, and turned by software to another position?
I'd like to be able to change variables on the Arduino by adjusting a set of knobs.  When I get to a desirable setting I'd like to be able to save those settings on the Arduino... and then I'd like to be able to load those settings back, and have the knobs turn themselves back to the correct positions.  Specifically I'm thinking of using this with a synthesizer.
I understand how to do all of this, except, I don't know if there are knobs that allow this type of behavior.

I think one of my amplifiers had something like that. Google "motorized potentiometer". There seem to be a few on eBay, amongst other places.

You might also consider using KY-040 rotary-encoders, with no cal marks on the knobs.  When you reload settings, just change all the current-position counts to match the reloaded values.  I can add this as an answer with a little more detail if you like.

Thanks Nick.  Looks like theres one here: http://www.mouser.com/ProductDetail/ALPS/RK16812MG099/?qs=uOLQ569YubvkId4TDNOKXQ%3D%3D

If you attach a knob to the Analog Feedback Micro Servo, either directly or via gears, then you can use the pot output to measure the current position and use the normal servo control protocol to turn it under software control.

Not a knob, but depending on your application, would a motorized slider like this be applicable?
You would read it just as you would a potentiality, and you have a motor that you can use to drive it to a specific position when you make a change in your software.
As for knobs, I have seen very few if any motorized knobs. What I would recommend here would be a continuous rotation encoder so that the position of the knob actually doesn't matter.

Alternatively, just add an LED/LCD display on top of each knob (or have a larger LCD showing info for all the knobs) to show the value.
Then you can have the knobs implemented with an optical rotary encoder.
Each knob is unmarked and doesn't need to be reset.
This solution doesn't put any mechanical part under strain.

If you can't get a motorised potentiometer could you use a rotary encoder, a motor, a shaft and some cogs.  Press the shaft and rotate manually then release and it disengages the manual cog and moves back to the motor cog.


text:
A question about including libraries
I'm a beginner in creating my own libraries so the following might contain some stupid stuff.
Anyways, I'm using NRF24L01+ modules for wireless communication and I've been utilizing the magnificent RF24 library (https://github.com/TMRh20/RF24) to operate these modules using Arduino. I wanted to clean up my code and decided to write my own library that uses the R24 library. My own library would contain all the subroutines that handle TX and RX functions.
Problem is that the RF24 library is initialized using e.g.
/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);

To begin using the NRF24L01+ one would the use the RF24 library like for example:
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
Serial.begin(57600);
printf_begin();
radio.begin();

radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();

Well, now I would like to make a library that would allow me just to call setup to handle all of the above. My library would be called RadioComm so I would call in my main code:
RadioComm rComm();

setup() {
rComm.setup();
}

The problem is that how do I use the RF24 library and all its functions in my library? To initialize the RF24 library in my own library I would have to call somehow this
RF24 radio(7,8);

and use all the radio. commands. How do I tell my own library that everything starting with "radio." is related to RF24 library because right now I'm getting this:
RadioComm.cpp: In member function 'void RadioComm::setup()':
RadioComm.cpp:20:18: error: 'radio' was not declared in this scope
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

Below are my .h .cpp and .ino files
Lib_test.ino
#include <RadioComm.h>
#include <RF24.h>
#include <SPI.h>

RadioComm rComm;

void setup() {

rComm.setup();

}

void loop() {

}

RadioComm.h
#ifndef RadioComm_h
#define RadioComm_h

#include "Arduino.h"
#include <RF24.h>

struct dataStruct{
unsigned long id;
float value1;
float value2;
float value3;
float value4;
};

class RadioComm
{

public:

RadioComm();
void setup(void);

private:
int pin1;
int pin2;

};

#endif

RadioComm.cpp
#include "Arduino.h"
#include "RadioComm.h"
#include <RF24.h>
#include "printf.h"

RadioComm::RadioComm(void)
{}

void RadioComm::setup()
{
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10
Serial.begin(57600);
printf_begin();
radio.begin();
radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();
}

Any help is appreciated.
Thanks.

Firstly, to address your compilation error:
RadioComm rComm();

That is not a constructor, that is a function prototype. When you have no parameters to a constructor you must not include the brackets or it confuses the poor little compiler.
RadioComm rComm;

Now - to address your main question.  Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.
In the class definition, in the private section, add:
RF24 *radio;

Then change the constructor to have:
RadioComm(RF24 &r);

The constructor itself would then read:
RadioComm::RadioComm(RF24 &r) {
    radio = &r;
}

Now throughout your library, instead of working with radio.whatever you need to work with radio->whatever since you are now using a pointer to an object not the object itself.
Then in your sketch you need to adjust your constructor to be:
RF24 myRadio(7, 8);
RadioComm rComm(myRadio);

The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.
It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.


text:
Can't upload my sketch from arduino IDE
I am using arduino uno and window7 64bit.I can't upload my program to arduino uno.When I upload it the warning message is show me.The warning message is"WARNING:Category 'USB' in library keyboard and mouse is not valid. Setting to 'Uncategorized'.What can I do?

Related (very similar) to How can I do this sentence show me in arduino.

Arduino IDEs v.1.6.x have recently been causing such kind of trouble on windows and mac systems. These problems seem to be caused by Java issues. Arduino IDE comes with java suit for it to work, installing java separately will cause problems. I suggest you uninstall java completely(by that i mean even the residue files that are not removed after uninstalling. For removing java completely you can use third party java remover like JavaRa ( https://singularlabs.com/software/javara/ ).
After doing so you can install the IDE again (i suggest to use .zip download of the IDE).
If it does'nt help it check this out http://forum.arduino.cc/index.php?topic=341144.0
its possible that problem is caused by out dated executables after updating the IDE.
Hope it helps.

I seriously doubt it's Java. Please rethink your answer.

I had similar problem and cause was java


text:
MPU-9250 : How to convert pitch (+90/-90) to 360 degree?
I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw.
Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.
I'm using this code:
vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]),
        1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2])));

vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3])));

vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]),
        1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3])));

m_data[0] = scalar;

m_data[1] = x;

m_data[2] = y;

m_data[3] = z;

What should I do?

I assume you want to map the range -90...-1 to 270...359 and the range 0...90 to 0...90?
It's simple enough:
if (angle < 0)
    angle = 360 + angle;

Note that you are adding the negative value to 360, which is the same as subtracting the positive value.
Or do you want to map it so that -90 is 0 and +90 is 360?  In that case you need to offset and scale it:
angle = angle + 90; // Angle is now 0..180
angle = angle * 2; // angle is now 0...360

Or in one line:
angle = (angle + 90) * 2;

this answer is completely wrong. In the first case you are creating something that will range from 0 to 90 and then from 270 to 360. In the second case, adding 90 and multiplying by two will create a 0 to 360 range mapped to a 180 degree movement, meaning that every degree the accelerometer rotates in that axis will result in a 2 degrees output.

@SpaceDog You are saying that it is wrong, then proceeding to say that it is wrong because it does what it is designed to do. I don't understand how that can be wrong. In case 1 yes it is intended to range from 0-90 and 270 to 360. In case 2, yes, it is intended to range from 0-360 in 2-degree steps. Given the vagueness of the question the two interpretations of what is wanted are perfectly reasonable, and the two cases given (which you have confirmed in your "it is wrong") are correct solutions to them. If it is wrong at least say why it is wrong, not why it is right.

it is wrong because the poster probably needs the pitch to be from 0 to 360 degrees in 1 degree step. What I mean is this: suppose the rotating object rotates just along the pitch axis, I mean, the object does a 360 degrees pitch axis turn. Supposing the object is at 0 degrees when it started it will go 0 → 90 → 0 → -90 → 0. Look at this in a graph it will appear that the object rotated from 0 to 90 and back to 0 but in fact the object continued to rotate in the same direction. This is probably the reason why it would be nice to get a scale where you can represent the real movement.

@SpaceDog You are reading things into the question that aren't there, and ignoring things that are there. The pitch only goes from -90 to +90. How can it be doing a 360 turn if it only goes from -90 to +90? If it goes past 90 in either direction it's upside down and will plummet to earth. At that point the resolution of your data is the least of your worries.

what about a loop? Isn't a loop a 360 pitch revolution?

@SpaceDog Again you are making dangerous assumptions. Not all devices will be able to make a loop. At least not without incredibly clever flying. It takes an amazingly good pilot to do a loop in a helicopter for instance. The only person able to judge if this answer has made the correct assumptions is the person asking the question. The person asking the question has said the answer is correct, so the assumptions made in the answer must therefore be correct.  You are basically saying that you know better than the OP what the OP is asking, which is mighty presumptuous of you.

@SpaceDog Besides: THE OP STATES -90 TO +90!  If it was doing a loop they wouldn't state that. They would state -180 to +180!

The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.
Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.
To get pitch and roll with the horizon from a quaternion, I think you want something like:
float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0];
float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3];
float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1];

float pitch = atan2(y,z);
float roll  = atan2(x,z);

I got this by rotating the vector <0,0,1> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.
"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.


text:
Burned Arduino?
I have an arduino that I programmed a PWM signal on pin 5. When I power the arduino with 12v or USB5v, pin 5 has the PWM signal. Iam checking it with a oscilloscope. Oddly enough the arduino is not recognisable to a windows PC or MAC, the device never shows up on the usb. The LED on the device seem to give all the right signals. The Green ON LED is on. And the L LED is also on. The program is not using serial so the RX and TX are not on.
When I try another Arduino it works fine.
What could I have broke? I am guessing the ATmega328 is fine?

Try reflashing the ATMega16u2 that does the usb-to-serial. Try it using the DFU option. If that fails use another arduino to reflash using ISP (using the ISP header right near the chip in question. If that also fails most the atmega16u2 is probably broken the board is beyond economical repair

Tried that, with no luck. Yeah I am not trying to fix for $$ reason, just trying to understand what went wrong.

with no luck. Could you expand on that. Were you unable to update the firmware, or did it not have any effect.

I was not able to use DFU option because the UNO is not detected by the pc or mac. I tried the ISP option and burned the bootloader, but it still is not detected by the computers.

Did the ISP programmer successfully verify the flashed rom?

Just a guess, if anything else work fine, my (first) guess would be the serial to usb adapter. I damaged one a while ago on a breadboard but also dont know how. But it could also be almost everything else. The pwm sketch, in which language is it written and burned? Does the Atmega have a bootloader on it?

The sketch was really simple, just doing a analogWrite(5, 100);

And how have you load it onto the arduino?

Using the arduino IDE

have you seen any error message inside the status window? would be nice if you tell a bit more..

The only error I see is the it can't find the usbmodem because the computer is not seeing the uno

which port uses the command? have you verified it? you said you have more arduinos right? try to communivate to another one using RX/TX pins.

Not sure what you mean? My other UNO use usb. And yes it is pin 5 sending the signal

that wasnt my question, ive meant the port you connect the arduino to your computer. it should be like COM1 on windows or like /dev/ttyACM0 on linux

Yeah it never shows up on windows or mac.

It also doesn't show up under device manager? Would it be possible for you to boot a linux distro and try it there? Most distros allow outputting detected USB devices and USB related logs so those might help up.


text:
Help understanding code to build circuit for plant reader
I'm working a design project that measures the tiny changes of conductivity in a plant. (To visualize how a plant reacts to its environment) I'm working with Arduino to realize that. Two wires are hooked up to the plant to measure the changes and are connected to the Arduino. I haven't worked with Arduino before but a friend got me the code from his plant reader (he got help too and doesn't know how to build it anymore). I do understand most of it but I just don't manage to translate the code he gave me into a circuit on the Arduino bread board. I use processing to visualize the measurements afterwards.

Who can help me building the circuit. I don't get what's happening at pin13. Thank you for helping me :)

Please copy and paste the code into your question (edit the question to do this). That makes it much easier to read and comment on it.

Pin13 is attached to the onboard LED.
So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.
But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).
It seems to imply that once the plant is stressed, it will stay stressed :-)
Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.
What cannot be figured out from the code, is how to instrument your plant.
If your friend has a working setup, you could try to replicate it.
At least post a few pictures.


text:
Arduino and 127/220 Volts: Relay and Isolation
I am new to Arduino, also, I am not fluent in english.
I wish to create a controller for several circuits. All of those circuits are "in parallel" with additional circuits.
My question is:

Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

Suppose the following:

The retangular boxes are "parallel switches" connected to the devices.
R = Power Supply Phase

S = Another Power Supply Phase

N = power Supply Neutral

Arduino, C2 and C3 are 127 Volts, (S+N)

C0 and C1 are 220 Volts (R+S)

Are the Shields safe from oscilations from the eletrical supply?
What / Where / How should I look on what to ground? Local regulations state that I cannot let R and/or S be grounded.

Which relay shield? Construction is very important for safety reasons.

Arduino: Mega 2560 R3. Relay (all of them are Sanyou SRD-S-105D) Circuits are UP to 2 Ampere each

Okay, but which relay shield? Safety is more than just the parts, as I already said.

So far, there is no "shield" for the relays, they are going to be "screwed" in a wood connector, and the Arduino will have welded wires to the Relay controller pins.

Those relays don't have any ability to be screwed into anything.

Out of curiosity, where has 127VAC?

@IgnacioVazquez-Abrams I am still searching for an actual relay shield, but have not found any shopts that sell them here so far. When I sayd screwed, I am at the moment, planning to either use the plastic cover to glue/weld/screw or use some non-conductant way to keep them in place.

@CharlieHanson Circuits C2 and C3 are 127Volts, Alternating current, provided by the S phase

Make sure you follow creepage recommendations regardless.

Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

A relay provides galvanic isolation in the circuit.  The mains power is electrically isolated from the rest of the circuit since the device that performs the actual switching (the contacts in the relay) have no physical connection to the rest of the circuit - they are merely acted upon by magnetism.
That doesn't mean that it's safe, however.  There are a number of things you still need to deal with:

The Arduino cannot directly drive a relay - it can't provide enough current. You must use a drive circuit.
Back-EMF from the relay coil as the magnetic field collapses can damage sensitive semiconductors - good snubber circuit design is important here.
Mains electricity is dangerous and must be treated with respect.  Proper circuit design is paramount to ensure that the mains is kept away from the rest of the circuit. Proper connectors must be used and exposed high voltage points must be rendered inaccessible, either by the project housing or by the addition of plastic insulating shielding.
Relays as they turn on and off cause sparks. Sparks cause EMI. EMI causes induced currents. Induced currents cause damage to electronics.  Minimizing the spark generation not only prolongs the life of your relay but the life of everything else around. Ensure your relays can switch fast enough for the currents you are dealing with, or consider using solid state relays (SSRs) that don't suffer from this issue.

When you wrotte: Arduino cannot directly drive a relay. I am having difficulty understanding this. Do you mean that Arduino cant provide the main power? (I expected that, the Relay has 5 pins, 2 for control, a common, and a Normal Open/Normal Closed), they are all understood, OR is this something else?

@Bonatti The Arduino IO pins have an absolute maximum current rating of 40mA and a normal operation maximum recommended limit of 25mA. This is not enough to energise a relay's coil properly.  Google "Arduino Relay" and you will see some simple drive circuits.


text:
Why I cannot connect directly Arduino UNO and Xbee S2?
I'm connecting Arduino UNO to Xbee S2 Zigbee module directly, and X-CTU cannot find Xbee module via arduino. i'm not using shield, it finds with non-arduino board connecter, but not by arduino UNO board.
i checked all parameters like baud rate, etc.., wirings, and it seems no problem at all, but it keeps msg like 'reset your radio module' and even i swtiched pin 5 and GND, it doesn't works.
what i have to do?

If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.
Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.

thanks for the answering, so is there no way to connect PC-Arduino UNO-Xbee s2 module when arduino MCU is programmable?
or does arduino can properly programmed and active when i programmed xbee s2 module and arduino separately?

You could use an Xbee shield like this https://www.sparkfun.com/products/12847 (there are other variants), which includes a switch so that you can easily switch from Arduino-programming mode to X-CTU mode. A common option is to just use the SoftwareSerial library (I think it's automatically included in the Arduino IDE) and just use 2 other pins for communicating with the xbee, so that pins 0 and 1 are free for programming on the Arduino via USB. But with this method I think you'd still have to swap the wires back to the Rx and Tx pins (0 and 1) on the Arduino if you want X-CTU to see the xbee.


text:
What is the relationship between the gain on the receiver and the delay time
I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify.
Part 2:
Hey Everyone,
I also had a question regarding what purpose each of the following delay serves in wireless communication.
// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);// line in question ---------------------
  b >>= 1;
}

and the delay used in the regular blink program.
The regular delay used in the blink programs was what set the 2 microsecond delays.
Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?

Related to Basic Serial Transmission Protocol and How to find the deferenced value of a transmit Port Register?. The bit of code you are quoting is from SoftwareSerial, and the delay is what makes the bits come out at the intended baud rate. The regular delay used in the blink programs was what set the 2 microsecond delays. - what do you mean by that?

So, you can open up the Arduino IDE, and type in delay(x) without have to physically import any new libraries other than the ones automatically inherited. That delay is what i am referring to.

How do I link other posts? Is it something I have to do elsewhere? Or do i just link them on the post and they will automatically show up as linked posts?

"Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?" ... So that you can communicate with hardware UARTs, which do require a start bit...

How do I link other posts? - if you mention another StackExchange post it is automatically added to the linked posts.

Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%.

Microsecond resolution delays on an Arduino are tenuous at best.  They aren't that accurate.  Simply because you're hitting the limit of the speed of the CPU.
At 16MHz you have a clock period of 1/16000000 seconds.  That's 63ns.  That's the granularity of the delays you can achieve - and that can only be achieved by inserting a precise number of NOP assembly instructions.
So for the best 1µs delay possible you would need (0.000001 / 0.000000063) 15.87 NOP instructions.  Of course, you can't have that many, so you have to round it either up or down.  Normal integer truncation would result in 15.  So that would actually be a delay of 945ns, which is an error of 5.5%.
2µs would be (0.000002 / 0.000000063) 31.74 NOP instructions, which would round to 31, so 1.953µs, or an error of 2.35%.  As you can see increasing the length generally reduces the error.
HOWEVER
The delay function on the Arduino for microsecond accuracy (delayMicroseconds()) is maybe not as accurate as it could be.  Simply because it's impossible to just have an exact number of NOP instructions for a delay since you can't know how long the delay should be until the function is called with a parameter detailing how long the delay should be.  So it has to perform a number of calculations and make a number of assumptions.  It tries to come close, but it was written for one specific version of the compiler and compilers change. Things may have been changed in how the function gets called, and how long parts of it take (what registers are pushed and popped may change with different compiler versions, for instance).  So it's not a perfectly reliable delay.
For more detail you can look at the source code of it (it's in wiring.c) and you can see how for small delays it's very hard to get it right. For instance, this couple of lines highlights the problem nicely:
    // for a one-microsecond delay, simply return.  the overhead
    // of the function call yields a delay of approximately 1 1/8 us.
    if (--us == 0)
        return;

Note the use of the word approximately there...
Also you need to note that the delay functions are just that - a delay at that specific moment in time from the start of the call to its finish.  It doesn't take into account anything else that's going on in your code, so a delay of 1µs in a loop of code that does other things will end up in a loop that takes X + 1µs where X is the amount of time that the rest of the code takes to execute.
And that's where the tunedDelay() function comes in.  It has been specially written to be used in that specific circumstance to provide a delay that takes into account the time the rest of the loop takes to run.  That is, the loop's time plus the tunedDelay time equate to the final period you want for the whole loop.  For asynchronous serial communications the timing accuracy is important.  Since there is no separate (or even embedded) clock to get the timing from both ends have to agree what speed the communication happens at (the baud rate), and any deviation from that can cause communication errors.  So the timing has to be as close as possible. A normal delayMicroseconds() function call just wouldn't cut the mustard - they needed it more precise than that.  Manually tuned to have specific delay values that are as precise as possible, and that was done for specific baud rates on specific speed chips.  Each supported frequency has a table such as this:
static const DELAY_TABLE PROGMEM table[] =
{
  //  baud    rxcenter   rxintra    rxstop    tx
  { 115200,   1,         17,        17,       12,    },
  { 57600,    10,        37,        37,       33,    },
  { 38400,    25,        57,        57,       54,    },
  { 31250,    31,        70,        70,       68,    },
  { 28800,    34,        77,        77,       74,    },
  { 19200,    54,        117,       117,      114,   },
  { 14400,    74,        156,       156,      153,   },
  { 9600,     114,       236,       236,      233,   },
  { 4800,     233,       474,       474,      471,   },
  { 2400,     471,       950,       950,      947,   },
  { 1200,     947,       1902,      1902,     1899,  },
  { 600,      1902,      3804,      3804,     3800,  },
  { 300,      3804,      7617,      7617,     7614,  },
};

That's the value to send to the tunedDelay() function in the four different situations where its used for each of the baud rates at that specific clock frequency (16MHz in that example).
tunedDelay() itself is written in assembly code and is a very tight loop for the number of iterations specified in the parameter.  The shortest possible piece of code with the minimum of overhead to get the maximum accuracy and finest granularity (least number of clock cycles for one iteration) out of it.

Thank you so much sir. That was an amazing answer. Thank you so much!

Can you please explain what are the purposes of rxcenter, rxintra, rxstop, and tx?

They are how long to wait before looking at the state of the line for a specific bit (rx...) or how long to wait between sending each bit (tx)

So does rxcenter wait that many nanoseconds after receiving the startbit, the rxintra waits that many ns between each subsequent payload bit, and the rxstop waiting that long for the stop bit(even though there is no stop bit)? Am I understanding that right? ^^

It's not nanoseconds - its loop counts, but that is pretty irrelevant, it's just a period of time.  rxcenter starts the reading at the center of a bit - give it time to arrive, but not too long - just the first bit after the leading edge of the start bit.  rxintra is how long to wait between each successive bit, and rxstop is how long to wait to sample the stop bit.  tx is like rxintra but for transmitting.

yes, so that "how long to wait" part is in nanoseconds i presume?

I said no, it is not nanoseconds, it is loop counts. You could calculate how long it is by counting the instructions in the loop and working out how many clock cycles in total the loop takes, multiplying it by that number.

I am looking at the read and recv methods in the software serial library and I don't see any checks for start bits, so what's the point of writing one in the write method?

The start bit is absolutely essential in serial comms. In the graphic below, the start bit is marked "B" - which distinguishes it from "idle" data which is "A". Once received, the receiver then waits 1.5 bit times and starts clocking in the remaining bits. (Starting at "C" in the diagram, and then moving on for a total of 8 bits).

Without a start bit, how would the receiver know when the byte started? Imagine you wanted to send 0xFF (all 1 bits). Without a start bit that would be indistinguishable from the idle state.
In the graphic, "D" is the stop bit. Why have a stop bit? We need one (which is a "1" bit), so that we can detect the transition from the stop bit in the previous byte (a "1") and the start bit in the next byte (a "0").
In the graphic, "E" is the start bit for the next byte.

I don't see any checks for start bits ...

SoftwareSerial has a pin-change interrupt set up to detect that the receiving pin has changed state (to a zero usually). That is your start bit. You don't see it in the loop, because it has already arrived, otherwise you wouldn't be in the receive loop in the first place.

Hey @NickGammon, i have a question. So let's say the receiver is high, and it reads a 0 not because of the write function but because of interference/noise, and so it says, ok time to read 1 byte. How come it doesn't take the next 8 bits, and covert it into a integer? However, when the write sends a 0, it quickly converts the next 8 bits into a integer. How does this get resolved? Or am I completely missing the ball park here?

Also, i believe this is the line you're referring to regarding reading the start bit: if (_inverse_logic ? rx_pin_read() : !rx_pin_read()) and uint8_t SoftwareSerial::rx_pin_read() {   return *_receivePortRegister & _receiveBitMask; } So because the pin is on high, rx_pin_read will always return 1 in that register right? In which case, !rx_pin_read will evaluate to false won't it? never going into that if statement. Or am I totally off?

That is because it is a pin-change interrupt, which responds to a change in state. That line tests whether we are changing to the right state (normally from 1 to 0). The reason we are there in the first place is because of the interrupt.


text:
Connect 2 LSM9DS0 to Flora
So I'd like to connect two of these sensors to an Adafruit Flora (https://www.adafruit.com/products/2020). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?
Edit
I decided to use this multiplexer to use LSM9DS0's with the Flora.
https://www.adafruit.com/products/2717

Adafruit's rectangular 9DOF device, unlike their round 9DOF, brings several more signals out to pads.  When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:

The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system.  (See my answer to  question 13830 for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.
If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on one of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground.  This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.
It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.
¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner.  See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet.  That figure shows the underside of the chip.

Could I use this, or something similar, for multiple sensors? http://dsscircuits.com/sale/product/dssc0107

@Chris, I wasn't aware of that item; it should work.  From the data sheet, first you send (via I2C) a control word to the  PCA9544A, to select which attached device the I2C bus is passed through to.  After setup the  attached device can run full speed, but if you need to alternate between devices very much, the selection overhead will add up.


text:
Can I use GSM and GPS modules at the same time?
In my project I want to retrieve the Latitude and longitude and then transmit to a cell phone through GSM module. But the GSM as well as GPS modules uses the same pins i.e. Tx and Rx, so is it possible to use both modules at the same time?
Link to products
GSM - http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-SIM-Board-Quadband-PCB-Antenna-for-MCU-Arduino-/191611848583?hash=item2c9cf4c787
GPS-- http://www.ebay.co.uk/itm/New-1PC-Ublox-NEO6MV2-GPS-Module-Aircraft-Flight-Controller-For-Arduino-/400830328802?hash=item5d53596fe2
Thank you.

Yes.  Use SoftwareSerial for one of them.  That way you can use any pins you like for that module.
I'd recommend using the GPS module on the SoftwareSerial since it's (mainly) half duplex, and SoftwareSerial can't both transmit and receive at the same time like the hardware UART can.
Either that or switch to a different Arduino board that has more than one hardware UART.

Well, thanks for the answer, and please will you suggest any arduno board other than MEGA which has more hardware UART.

This table is useful: https://www.arduino.cc/en/Products/Compare Also you might want to consider other boards than Arduino - there are other makes using other kinds of chips that do so much more using the same (or similar) footprints.

If you are using two software serial then you can always use the listen() function to listen to specific object.
Suppose you have two software serial objects named GSM and GPS.
Now if you are reading or writing data to GSM then start with this, gsm.listen();
Now you can read/write data to GSM.
Next if you plan to read or write data to GPS then do this, gps.listen();


text:
Esp8266 server unreachable. Port doesn't open
I have followed all the instructions provided on  http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/
I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.
But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

First of all check that your ESP is connected to your WiFi network, to do this go to your router and check that your device got that IP address. Only when it shows up at your router you'll be sure that it is available on the network.

i did that already, my router homepage shows the same ip address on which i am trying to send the http request

Ok, then that means that your ESP is connecting to the WiFi network, but that doesn't mean that the web server is up and running. Arduino is showing up the Server Ready string but that doesn't mean that the actual ESP is actually running. Where the line if(esp8266.available()) // check if the esp is sending a message
{ create an ELSE statement just to check if the .available is returning false (meaning that the ESP is not there for Arduino.

absolutely, you are right, it is not actual sending anything, i just created a else statement making it print "no message send" and my serial buffer got filled up with the Same. Now, we now the problem, now the job is half done, what to do next.

That doesn't work

The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.
My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).
This link can provide some good information about this subject:
http://bbs.espressif.com/viewtopic.php?t=133

But, just now, i uploaded bare minimum and then opened the serial monitor and typed the commands one by one it worked out, the server was ready and it was also accepting my http request, but how can i compile all those commands in the sketch.

Ok, progress. What exactly did you do? how did you "uploaded" those commands? Using Arduino? Also, you didn't answer my question, how are you powering your ESP?

i have connected ESP to 3.3v on arduino and then i uploaded a empty sketch, then opened the serial monitor and typed in AT and got response OK likewise i typed in each AT command and the server was setup and it responded, but you know serial monitor has it's own limitations

Ok, I understand that you think it worked (in fact you saw it)  but the BIG difference here is power. If you send those commands one time it might not do a lot but as soon as you start sending other commands the ESP will start to consume more and more power (the library on the Arduino is not doing only the send of those commands but much more) and that's when the ESP just dies, it doesn't have enough power to stay up.

i have a malfunctioned arduino board but it can supple enough power, should i add that also keeping the present arduino as it is

Good, glad that you were able to solve your problem.

No that didn't solve my problem

I had the same problem and it worked when I disconnected my phone from 3g/4G.

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


text:
Error in Arduino Library file
I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.
Error

FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
  Command_Packet::GetPacketBytes()':
  C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:17:
  undefined reference tooperator new[](unsigned int)'
  FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
  FPS_GT511C3::GetResponse()':
  C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:735:
  undefined reference tooperator new[](unsigned int)' collect2.exe:
  error: ld returned 1 exit status

Library File (CPP)

byte* packetbytes= new byte[12];
byte* resp = new byte[12];

Not sure if having your files having an extension of .c.cpp would confuse things, it they're C++ it'd be more conventional if they were just .cpp.

No. That doesn't make any difference because it is just the file name with .cpp extension.

Do you have a typedef for byte somewhere in scope at that location? byte is not a fundamental type and is usually typedef'ed to char or unsigned char.

What version of the IDE are you using?

I am using Arduino IDE 1.6.5. But then, I tried it with different version of IDE like 1.0.5, 1.0.6. It still shows the same problem. @Majenko

Try 1) removing the library and writing in the main sketch byte *test = new byte[12];. If this works the library has problems. Then 2) Try looking in the library. Probably something is redefining new

@frarugi87 Okay. I removed the library from the sketch and wrote the test code. It showed the same error. So I guess there is nothing wrong with the library. What next?

Then you have two ways to proceed: start with a working example (just a plain file with empty setup and loop, for instance) and gradually add every feature you need, until you find the broken one, or start removing features from your own one until it works. This way you'll be able to find the code that issues the problem

But there is no much feature in it. It is just the simple example code which comes with the library and the fingerprint scanner. https://github.com/sparkfun/Fingerprint_Scanner-TTL  Please go through this link and maybe download this library and try it out. @frarugi87

As I told you, my usual debug workflow is adding one feature at a time, then compile and see if it works. You said that removing the library leaves the error, so try starting from scratch and then adding code slowly. At present I can't download it.. Probably this evening I'll be able to do that...

The core of the problem is that the code is being compiled as C and not C++.
The error says 'new[]' is undefined at the link stage.  This is because the linker is not pulling in the C++ standard libraries.  The built-in function new[] it doesn't exist in C.
The filename FPS_GT511C3.c.cpp is the elephant in the room.  You could consider renaming it (and others) to FPS_GT511C3.cpp.  Although the plain Arduino IDE does not really have a problem with building them.
Another option might be to modify the new[] (and delete[]) for C's malloc() and free().  However this is only appropriate for the allocation of simple types (byte, int, etc).  If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.


text:
Json gets corrupted after first HTTP request
I'm a web developer and I started building a small environment logger that will post to my website`s API. I'm really new to this kind of coding so bare with me.
Since yesterday, the whole Arduino started to acting funny. After the first or second request to the server(with already tested code), I started sending corrupted JSON data.
{
  ":12": "module3",
  "10-7 18:26": {
    "1": {
      "": 21.50,
      "26:12": 55.50,
      "measured_at": "2015-10-7 18:26:12"
    },
    "2": {
      "": 21.10,
      "26:12": 55.70,
      "measured_at": "2015-10-7 18:26:12"
    }
  }

Where it should be
{
  "modulename": "module3",
  "environments": {
    "1": {
      "temperature": 21.40,
      "humidity": 55.60,
      "measured_at": "2015-10-7 18:25:52"
    },
    "2": {
      "temperature": 21.20,
      "humidity": 55.80,
      "measured_at": "2015-10-7 18:25:52"
    }
  }
}

The second JSON is from the initial request to the server. The first one is the corrupted one. I tried stopping all kinds of parts from the code, without any luck, except when I enter the measured_at manually (without getting the data from the RTC.)
#include <DHT.h>

#include <elapsedMillis.h>

#include <DS3231.h>
#include <Wire.h>
//Json Library
#include <ArduinoJson.h>

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

#include <LiquidCrystal.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
EthernetClient client;

const String module_name = "module3";

DHT dht1;
DHT dht2;

DS3231 clock;
RTCDateTime dt;

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

elapsedMillis timer0;
const long interval = 10000; // READING INTERVAL

int connected_sensors = 0;
float t1 = 0;  // TEMPERATURE VAR
float h1 = 0; // HUMIDITY VAR
float t2 = 0;
float h2 = 0;

int nc = 0; //Network connection simulation INI

byte temp[8] = { //icon for thermometer

  B00100,
  B01010,
  B01010,
  B01110,
  B01110,
  B11111,
  B11111,
  B01110
};

byte humi[8] = { //icon for water droplet
  B00100,
  B00100,
  B01010,
  B01010,
  B10001,
  B10001,
  B10001,
  B01110,
};

byte sconnect[8] = { //icon for connection
  0b00000,
  0b11111,
  0b10001,
  0b10001,
  0b11111,
  0b00100,
  0b11111,
  0b00000
};

void setup() {
  Serial.begin(9600);
  clock.begin();
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.println("Terrarium Serial");
  // Print a message to the LCD.
  lcd.print("Weather v0.1");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("Sensor loading...");

  lcd.clear();
  lcd.print("Network check...");

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP"); //There is a problem with DHCP
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DHCP ERROR");
    lcd.setCursor(0, 1);
    lcd.print("Please Restart");
    for (;;)
      ;
  }
  nc = 1;

  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(Ethernet.localIP());
  lcd.setCursor(0, 1);
  lcd.println("Ready!");

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

  delay(4000);
  lcd.clear();

  lcd.createChar(1, temp);
  lcd.createChar(2, humi);
  lcd.createChar(3, sconnect);

  dht1.setup(15);
  dht2.setup(16);

  h1 = dht1.getHumidity();
  t1 = dht1.getTemperature();

  h2 = dht2.getHumidity();
  t2 = dht2.getTemperature();

  delay(2000);

  //Display the statics on the display
  lcd.setCursor(2, 0);
  lcd.print(module_name);
  lcd.setCursor(9, 1);
  lcd.write(2);
  lcd.setCursor(15, 1);
  lcd.print("%");
  lcd.setCursor(2, 1);
  lcd.write(1);
  lcd.setCursor(8, 1);
  lcd.print((char)223);

  timer0 = 0; // clear the timer at the end of startup

}
void CheckSensors() {

  if (timer0 >= interval) { // READ ONLY ONCE PER INTERVAL
    timer0 -= interval;

    dt = clock.getDateTime(); //get current time

    h1 = dht1.getHumidity();
    t1 = dht1.getTemperature();

    h2 = dht2.getHumidity();
    t2 = dht2.getTemperature();

    DataSend(); //send data
  }
}

//Print the changeable values on the display
void LcdPint() {
  lcd.setCursor(0, 0);
  if (nc == 1) {
    lcd.write(3);
  } else if (nc == 0) {
    lcd.print(" ");
  } else if (nc == 2) {
    lcd.print("E");
  }

  lcd.setCursor(10, 1);
  lcd.print(h1);

  lcd.setCursor(3, 1);
  lcd.print(t1);

}

//Construct the JSON response
JsonObject& prepareResponse(JsonBuffer& jsonBuffer, String measured_at) {

  JsonObject& root = jsonBuffer.createObject();
  root["modulename"] = module_name;

  JsonObject& environmentsObject = root.createNestedObject("environments");

    JsonObject& environmentsOne = environmentsObject.createNestedObject("1");
    environmentsOne["temperature"] = t1;
    environmentsOne["humidity"] = h1;
    environmentsOne["measured_at"] =  measured_at;

    JsonObject& environmentsTwo = environmentsObject.createNestedObject("2");
    environmentsTwo["temperature"] = t2;
    environmentsTwo["humidity"] = h2;
    environmentsTwo["measured_at"] =  measured_at;

  return root;
}

void writeResponse(EthernetClient& client, JsonObject& json) {

  char buffer[256];
  json.printTo(buffer, sizeof(buffer));

  if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /v1/sensors HTTP/1.1");
    client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/json");
    client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
    client.println("Connection: close");
    client.print("Content-Length: ");
    client.println(strlen(buffer));
    client.println();
    client.println(buffer);

    nc = 1;
  } else {
    nc = 2;
    Serial.println("connection failed");
  }

  while (client.connected())
  {
    if ( client.available() )
    {
      char c = client.read();
      Serial.print(c);
    }
  }
  Serial.println();
  client.stop();
  //End  post request

}
void DataSend() {

    //This is the part that I think crashes my entire code. I tried using the helper with the RTC library that I use
    //but that made things worse.

    String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& json = prepareResponse(jsonBuffer, measured_at);
    json.prettyPrintTo(Serial);

    writeResponse(client, json);

}

void loop() {
  CheckSensors();
  LcdPint();
}

It even restarts the whole Arduino. I think this may be a conflict of some sort... I wonder why it shows up now, when I used it for 2 days straight a few weeks ago.

Chances are you're running out or memory.  All that String use certainly doesn't help - get rid of those and things can only improve.

This line, for instance: String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second; will be making swiss cheese of your heap.

I would suggest ditching the JSON library as well, and just building the output up a bit at a time using client.print() - you don't have to send it all in one string, just do it a bit (even a character sometimes) at a time.

Please tell me how you managed to format the code properly... I tried with that <-- language --> thing and i got nothing.
Also I tried removing  the measured_at and added another library, but that didnt help much either ...
http://www.rinkydinkelectronics.com/library.php?id=73
This one i added and still...
I`m a web dev, I write Javascript, this is really frustrating :D Could anyone show me a tutorial for proper ways to write for the Arduino .. I dont know.. I dont want to beg for someone to do it for me...

To format code you indent it by 4 characters (or highlight it and press the {} button above the editor).  To do it inline you place backticks around it (your code = your code)

Oh but the json helper is so nice :D Helps a ton with pretty code. The only string I have is the measured_at var. Can that take up so much RAM to stop the arduino?

Avoid String like the plague. Here's why: http://hacking.majenko.co.uk/the-evils-of-arduino-strings

I think that i`m getting over my league with this project of mine .... Eighter my code is really bad or the Uno is not suitable for my project (if I want to add more sensors).

The Uno can be a very capable board - you just have to remember that it is not a computer and has incredibly limited resources. Wait for my answer for some more pointers.

Oh great! What about splitting the code into function and files. I`m used to writing javascript and using Require.js and I cant stand code in one place :D Does that slow down the Arduino as Well ?

That makes no difference.

Great, good to know.

You have used 461 out of 2048 of your RAM bytes for string literals alone. At the very least, use the F() macro where you can, eg.
client.println(F("POST /v1/sensors HTTP/1.1"));
client.println(F("Host: api.terrariums.eu")); // SERVER ADDRESS HERE TOO
client.println(F("Content-Type: application/json"));
client.println(F("Authorization: Basic bW9kdWxlMzoxMzIxMzI="));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));

Ditto for Serial.print and lcd.print where you are printing strings.
After that, what Majenko suggested is a good idea. Using a custom library is well and good, but JSON is easy enough to output directly. Just make a small function to do it for you.

Problem now is the Content-length... How do I calculate it ?

Do you absolutely need it? If you do, instead of building up the entire content first, I suggest two passes.
First pass outputs to a dummy class which simply calculates the length, second pass actually outputs. Something like this:
// outputting class that just counts output
class DummyOutput : public Print
{
private:
  unsigned long length_;

public:
  void begin ()
    {
    length_ = 0;
    }
  virtual size_t write (byte c)
    {
    length_++;
    return 1;
    }
  unsigned long getLength () const { return length_; }

};  // end of DummyOutput

DummyOutput countOutput;  // instance of DummyOutput

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

  Print * outputter;  // where to write to

  for (int pass = 1; pass <= 2; pass++)
    {
    randomSeed (1);
    switch (pass)
     {
     case 1: outputter = &countOutput;
             countOutput.begin ();
             break;

     case 2: outputter = &Serial;
             break;
     } // end of switch

    // generate some output
    for (int i = 0; i < 25; i++)
      {
      outputter->print (random (5000));
      outputter->print ('\n');
      }

    switch (pass)
     {
     case 1: Serial.print (F("Content-length: "));
             Serial.println (countOutput.getLength ());
             break;

     case 2: break;
     } // end of switch

    }  // end of for loop
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output:
Starting
Content-length: 121
1807
249
73
3658
3930
1272
2544
878
2923
2709
4440
3165
4492
3042
2987
2503
2327
1729
3840
2612
4303
3169
2709
2157
4560

By generating the same output in two passes you can first just calculate the length (without outputting) and the second time you can output that length first, and then output the actual data.

I already did the json with print only, as ugly as it is it works. Problem now is the Content-length... How do I calculate it ?

See amended reply.

In all probability you are either running out of memory, or the libraries you are using (and the fact that you are abusing String objects) is fragmenting your heap to such an extent that your whole 2KB of RAM is being used and you are ending up with a stack-and-heap collision.
You have to remember that the Arduino Uno only has 2KB of RAM.  It's not a computer, and has no OS, and as such you have to unlearn much of what you know about programming and do things slightly differently.
The first problem you have is with your String abuse.  This line:
String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

will be doing horrible things to your heap.  The String class dynamically allocates memory on the heap to store the string content.  The operations you have there inadvertently create a rather alarming number of temporary Strings which are then thrown away at the end.  Every temporary String dynamically allocates RAM on the heap and can potentially lead to heap fragmentation.
For instance the numeric value dt.second is first converted to a String and memory allocated to store the content.  Every concatenation results in a new String with its dynamic allocation, etc.  Quite messy really.
Secondly, who knows what dynamic memory the ArduinoJSON library is using - quite a lot would be my guess - every tag, every value, etc, would need to be stored in memory somewhere, and unless they statically allocate a huge chunk of RAM (wasting most of your precious resource) they will be doing dynamic allocation - and that will make matters much worse.
So how would you get around it? It's actually quite simple - you need to think more about spoon-feeding a baby instead of preparing a 5 course banquet.
Instead of building up big objects with lots of data in them and sending them all out in one big chunk you need to just send little bits at a time.  There is absolutely no reason to use things like ArduinoJSON if all you are doing is sending data.
For instance to send the JSON data you could do something like this:
  if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /v1/sensors HTTP/1.1");
    client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/json");
    client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
    client.println("Connection: close");
    client.println();

    client.println("{");
    client.println("    \"modulename\": \"module3\",");
    client.println("    \"environments\": {");
    client.println("        \"1\": {");
    client.print("            \"temperature\":
    client.print(t1);
    client.println(",");
    client.print("            \"humidity\":
    client.print(h1);
    client.println(",");
    client.println("        },");

Etc.  You get the drift.
You notice I removed the Content-length header?  That's because you don't know how long the content will be now (one drawback), so to signal the end of the transmission you will have to close the connection (I don't recall if client has a way of only half closing - just the TX portion) to signal to the web server that you have finished.  However, if you know how long your numbers will be (say you format them to a specific number of characters) then your body size would always be the same and you can hard code a Content-length header.
Also - do you really need to send the time and date?  Surely the computer has a better idea of what the current time and date is than the Arduino - just use the computer's internal clock.

Really nice, thank you. I decided that it was a good idea to have the date as it will store when the measurements were taken. Ofc I can use the moment when the code enters my API but I thought this wouldnt be a problem at that time.

Use the same trick for sending the date and time then. Instead of pre-formatting it as a String, just send each individual entry with  a separate client.print().

Ok. Will keep you updated.

How should I close the connection when I cant send a Content-length header?

Client.stop does that.

I did it but I got no response from the server then.
BTW using F() I got the original code down to 50% memory usage and it works now. But I will try to follow your advice.

I always forget about F() - I rarely actually use the Arduino, instead using a board that uses the Princeton monolithic memory architecture not the Harvard split bus architecture, so F() does nothing for me.


text:
Can I use these cheap GSM module with arduino?
I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not.
Will you help me please?
Here are the link-
http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8
http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292

Both seem to have the pin header for a serial port. So chances are that they can take standard AT commands.
I've seen many modems using additional AT commands for special functions, but they all supported also the basic AT commands.

The SIM900A won't work in the UK, it's dual band.
The SIM800L is cheap as there is no power regulation on board. IIRC it requires 3.4V - 4.5V, min 2 amp supply. Check the data sheet to be sure.

You can actually use the sim900a and 900a mini in the uk but you will have to download firmware and flashing tools that you will find with a web search, not for the beginner though, an 800l is your best bet with a SMA Female JACK Connector to U.FL/IPX Converter Pigtail Cable F1445K so you can attach an sma antenna
cheers
Stuart


text:
Reading analog signal from digital pin #6
Is it possible to use digital pin 6 (PD6_PCINT22/AIN0) to read an analog voltage with analogRead()?
According to the ATMega datasheet, this should be possible.
If yes how is it done ? (pin configuration)

That is not possible. AIN0 is an input to the analog comparator, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.

Maybe. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega) and the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega).
As you can see in the image below the pin PD6 is not an analog input. To be an analog pin it should be write ADCx, like the PC0..5.

So, if you are not using and Arduino Uno you can't use PD6 as analog input but you can use PC0..5.
To read an analog value using analogRead() method you can do like this:
int analogPin = 3;
int val = 0;           // variable to store the value read

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

void loop()
{
  val = analogRead(analogPin);    // read the input pin

  Serial.println(val);             // debug value
}


text:
How is LED powered when PIN 2 is disconnected?
Using the Arduino tutorial "Button", I have noticed that if I totally disconnect Pin2 from the circuit, the LED comes on dimly.
I am trying to understand HOW this happens.  Is it simply due to being a floating ground?

The pinMode(buttonPin, INPUT); line tells the board to set the buttonPin in high impedance mode.
When you disconnect the wire the state of that pin becomes unknown; usually it oscillates.
Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".
The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as pinMode(buttonPin, INPUT_PULLUP); and invert the logic (i.e. buttonState = !digitalRead(buttonPin);). This way it will never oscillate again.

Sounds good!  Any idea why the tutorials all assume PULLDOWN and ask for resistors rather than coding for PULLUP?

That's because our mind thinks in a "positive" way. Button is pressed means, for the programmer's mind, a HIGH value. Since the atmega only has pullups, if you want to use it you have to connect the button towards ground, so the button pressed status is signaled by a LOW value. You just have to invert the logic, but... Personally I prefer to put buttons towards ground :P And, by the way, since you are learning I suggest you to experiment with debouncing ;)

Yep, de-bouncing was the next question and I've got that one mastered now.  I guess we all have the same questions getting started. :-)

Of course ;) That's why forums are a great way of learning if used properly. There is always someone who has already faced your problem ;)


text:
Using an Arduino Nano, how many LEDs can I safely power?
I am working on building a wordclock using one of the several design ideas that you can find all over the Internet. Something like a mix of this one: http://www.instructables.com/id/Sleek-word-clock/ and this one: http://www.instructables.com/id/Personalised-Word-Clock/ A lot of the guides suggested building your own Arduino to save money, but I found these Arduino Nano clones for $7/apiece: http://www.amazon.com/gp/product/B00SGMEH7G.
I've done a few simple projects before, but nothing with the same kind of power demand. How can I figure out the power requirements? My plan is to use approximately 64 3mm LEDs via shift register, or possibly the equivalent segments of an LED strip.
The Nano clone does not have a barrel connector for external power adaptor. Should I directly solder on the power cables from an external adaptor? Use a screw terminal or similar? Is the USB adaptor a good enough source of power for 64 LEDs? Or do I have to do something else to supply external power to that many LEDs?
Thanks for any advice! I am experienced in programming but not in electrical engineering so many of the concepts are something I don't have a good handle on yet.

If you use shiftregisters, and don't do any multiplexing, you probably don't want to run the leds at their maximum brightness. Running them at 5mA will probably be more that bright enough. That would, in worst case, mean 64*5=320mA. Which is not that much, though I'd suggest using a 5v adapter, as the tiny voltage regulator in the nano board probably won't handle that much current without getting extremely hot. You can easily find 5v usb chargers that handle upto 2A.

I'm trying to find some videos that explain it better. How should I tie in the 5v USB charger to the Nano?

Just use the mini-usb plug, or connect ground and 5v on the nano to the corresponding wires on the charger.

Are you ever going to power all 64 LEDs simultaneously?  I would imagine a word clock would have just a fraction of the LEDs switched on at any given time, which would greatly reduce the current demands.

If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.
If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply.  My immediate guess is "not enough".
64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs.  That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.
So you can reduce your current requirements by not having the LEDs as bright.  Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all.  At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.
So you can come up with a compromise between the brightness you desire and the current consumed by each LED.
Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED.  When all LEDs are on that would be (5 × 64) 320mA.  That's reasonable for a linear regulator, but still will generate more heat than is really advisable.
So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator.  You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.
Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip.  There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.

Thank you. I was planning to use 3 of these: SN74HC595N to control the LEDs.  Are you talking about something like the MAX7221/7219? I found a guide that mentioned that part but I didn't realize one of the benefits was not needing resistors. That sounds really useful, I will use it! Also: do you have any good references I can use to learn about how to safely connect the power?  EDIT: looking at this guide, http://playground.arduino.cc/Main/MAX72XXHardware, does this reduce power usage to safely supplied by the USB port? I would use a small AC adapter with USB micro port.

I often use the TLC59116 which is an I2C device - you can have up to 14 on one bus and each one supports 16 LEDs (so 224 LEDs max).  Connecting the power is easy - the best thing to do is just use the buck regulator for everything - connect it to the 5V/GND pins of the Nano and also the Vcc or 5V and GND pins of any external devices.

Oh, the TLC59116 is also a PWM device, so you can set the brightness of each individual LED - just like the PWM outputs on the Arduino.  I even have a library to control them: https://github.com/MajenkoLibraries/TLC59116


text:
Looking for a game application oriented display for Arduino Mega
I was using displays with serial communication (SPI), but sending bytes to draw a tile-based picture was way too slow so I'd like find one with a parallel port, enough fast bandwidth to receive fast pictures at a speed at least 10FPS (but I'd like 50FPS or 60FPS) from Arduino Mega (ATMEGA2560) and which has a library compatible with the Arduino's C++ compiler.
I think I've seen somewhere how to connect a display onto the XMEM pins of the Mega and send bytes like this:
*(0x12)=0x34 // Sends 0x1234

However, I couldn't find where to buy that specific one.
I was searching on eBay, but only found displays of unsupported drivers or drivers with broken links that I couldn't download, and displays that are ridiculously large like a shovel!
The resolution it needs to have is minimum 128x64, aspect ratio must be X:Y where X is greater than Y (unless it's possible to send bytes sideways while the screen is physically placed in a different orientation on the PCB).
It must be a touch display sensitive on anything (like Nintendo DSi when drawing Flipnotes).
It should be either:

Monochrome
Color display with MS Paint colors if it has equal to or less than 256 colors
Color display with 16-bit color input mode if it has a lot of colors

It should be no bigger than 2.5" because this is for a little handheld console.
If anyone knows where to buy it, please comment.
Thank you for your time.

I'd suggest, if you haven't done it already, to take a look at what is supported by uGFX.
If you find any HW meeting your needs, you can at least be sure that it is supported.

I was using displays with serial communication (SPI)  ...

Personally I regards serial and SPI as different things:

Serial
SPI

SPI is somewhat faster than serial.

... sending bytes to draw a tile-based picture was way too slow ...

How slow was it? What was your target speed?

The resolution it needs to have is minimum 128x64 ... It should be no bigger than 2.5"

Something like 2.2" 18-bit color TFT LCD display ?

fast bandwidth to receive fast pictures at a speed at least 10FPS ...

See Toorum's Quest II - Retro video game and console
That guy made a sideways scrolling game outputting to video with a display resolution of 104x80 with 256 colors. He also had sound generation and managed input from a NES controller.
See video of it in operation on YouTube.

When I send bytes by a for loop to paint an 8x8 tile from top to bottom, the picture appears in a quarter of a second which isn't near 10FPS. Plus, the console would need to have enough speed to not just blit the image, but have some of its own processing like feeding VLSI chip with MP3 music, RTOS processes, game engine,...
I've seen many people do the NTSC blitting, but I'm more interested in LCDs where I'm not timely challenged and can respond to interrupts in the middle of blitting the image.

Also, that TFT LCD display you linked uses SPI and I need one with parallel communication like those character displays.

When I send bytes by a for loop to paint an 8x8 tile from top to bottom, the picture appears in a quarter of a second - with what device? And what code? Something is wrong if it takes 250 ms to draw 64 pixels.

Not 64 pixels. WHOLE screen! I don't have the code right now and I think I've deleted it. The code writes from top to bottom like if it was blitting a tile-based screen layout, but just that one tile. And that's how much it takes. Also, I've even used manual port register manipulation rather than using the PutPixel function in order to speed up, but it looks like it's still too slow.

Wow, I'm surprised at that game and how much effort was put (they could have done without a custom board and still call it a great use of an Arduino). It ended up so professional, really shows love for the craft.


text:
Can I use this cheap GPS module with arduino
For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.
Here is the link--
http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8

After some research it seems you can use that gps module with an Arduino. Here's a link to the data sheet for it: http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf. Also it seems like you have to use the TinyGPSPlus library to get it to work. Here's a link to learn more about it: http://arduiniana.org/libraries/tinygpsplus/. You may have to use the protocols in this data sheet: https://www.sparkfun.com/datasheets/GPS/NMEA%20Reference%20Manual-Rev2.1-Dec07.pdf.
All of this information was taken from this thread: https://www.linkedin.com/grp/post/4573843-5806249757395406852.

Yes.  You can tell that from two entries in the specification:

TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

Output SiRF binary system OR nmea0183 V3.0(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.

authors: Евгений Новиков


text:
How to read an RFID reader?
I want to connect an RFID reader to an Arduino board. The RFID reader has several wires attached, and the manual mentions them as follows:

Red: VCC +12V
Black: GND
Green: D 0/RX/4R+
White: D 1/TX/4R−
Blue: LED/CS
Yellow: Beep

There is also another black wire attached, but the manual does not mention it.
This is an image of it:

I have the red wire connected to the 5V pin and the black wire to the GND pin on Arduino board. Then I have the white wire connected to the RX pin on the Arduino board.
I'm trying to Serial-read the RX port using this code:
void setup() {
    Serial.begin(9600);
}

void loop() {
    if (Serial.available() > 0) {
        int b = Serial.read();
        Serial.print(b);
        Serial.print(" ");
    }
}

When I try to read a keyfob, only this is printed – nineteen times 248:
248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248

To me it looks like there's something wrong with the connection somewhere.
How can I properly read this RFID reader? If above assumption is not correct, is there something I should know?

Which RFID reader? Please post a part number or photograph. Please post all your code.

@NickGammon It's a cheap-ass RFID reader from China. They usually don't put a manufacturer's name or model number on it. I also have posted all my code, but that doesn't make it more clear.

Do you not have a phone with a camera in it? Anyway, this might help: RFID reader - HZ-1050

Are you 100% sure the fobs' standard matches the reader? Check if the ISO standards are the same.

@FuaZe Yeah, if I plug the RFID reader into an Access controller, everything's working.

Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID_630_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?

That link looks much like his pic, and says "Output mode: Standard Wiegand26 Format For Access control "  so maybe http://arduino.stackexchange.com/questions/12927/parallel-connection-to-wiegand-26bit-rfid-readers would help.

Yeah, thats what i thought when i found the Aliexpress page, but his post says it supports 2 other modes according to his manual, so i'm not so sure. However, if there is a default mode, its probably the WG26 mode. From the link you provided, it looks like theres already a library (no surprise) that translates Wiegand https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino so its another option, i guess

From my personal experience, you should give some init time to the rfid reader to init.
Try to use a digital output to control the chip reset, and give it some milliseconds to init.
I had a similar behavior with a rfid reader and the reason was this I just told.
Good luck!


text:
Alternative to delay function
I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.
Here is the link to the example:
https://www.arduino.cc/en/Tutorial/AnalogWriteMega
Here is my code:
int currmillis = 0; //used in my function to find the current millis()
int prevmillis = 0; //used to hold previous value of currmillis
int boolval = 0;    //used to control whether to write the brightness value to the led or not
int time = 0;     //used in the delay function, difference between currmillis and prevmillis

int timeloop(int); //the function i wrote, it is at the bottom of the code

void setup() {
  Serial.begin(9600);
  for ( int i = 2; i <= 13; i++)
  {
        pinMode(i,OUTPUT);
  }
}//Setting the pins to output and allowing serial communication.

void loop (){

  for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
  {

    for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
    {

      boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

    }

    for ( int brightness = 255 ; brightness >= 0 ; brightness--)
    {
      boolval = timeloop(2);

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }
    }
          timeloop(100); // a delay of 100 ms using the function
  }
}

int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

Thank you

Your function is a pure delay. Why do you want to rewrite it? What different behaviour do you want?

// You don't need to return anything since it's just a delay
// also I changed the parameters to long ints because millis()
// returns a long int
void timeLoop (long int startMillis, long int interval){ // the delay function

    // this loops until 2 milliseconds has passed since the function began
    while(millis() - startMillis < interval){}
}

// Your call for a 2 millisecond delay would be
timeLoop(millis(), 2);

Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.

If you really want it to return something you could use this:
long int timeLoop (long int startMillis, long int interval){ // the delay function

    while(millis() - startMillis < interval){}
    return millis() - startMillis;
}

But it really isn't needed.

thank you - seems super hard to find functional functions on arduino sites

What's the point? Why rewrite delay()?
Anyway:
int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

In every iteration of that loop you are updating prevmillis. So you will never reach the wanted delay interval.
Apart from the fact that you may as well use the inbuilt delay rather than writing your own, and getting it wrong.

I am trying to make a workaround for the delay function

Why?
The XY Problem

The "Why" part interested me here, because I'm in the process of changing my delay(1000) to a millis() interval. Why? because I want a more accurate timer for sending data via serial. I need the processing time to be deducted from the one second delay, so the interval between loops is as close to 1 second as possible. That's fair and achievable, right?

"W": Because I think that is more sensible than sending and displaying data at an arbitrary rate, as my application involved scheduling to real-world time. "V": So that a user can schedule an event as part of the automation program! "U": Because...    ..."F-22": Because I wasn't breast fed!... ..."M-6.832810^11": Because the big bang singularity occurred! "L-6.832810^11": Unknown.

What? Did the cat get loose on the keyboard?

lol. Do you get it? It's my extension of "The XY Problem"!

Depending on what you want the alternative function to do, there are a megaton of timer libraries at the Arduino playground. One of them is likely to provide what you need.