text:
Unsure about how the code works for this Make-It Robotics kit
I have been using a Make-It Robotics kit, that I picked up from a RadioShack that was closing, to learn more about Arduino, C, etc.  After building the line-following robot and downloading the correct libraries, I can get the robot to function as intended.  It uses 2 optical sensors in front of 2 driving wheels that are controlled by independent DC motors.  The optical sensors determine if the left or right side of the front of the robot is over a white or black area on the test track. The necessary motor then turns on to keep the black line roughly between the 2 sensors as the robot moves along. The default test track that came with the kit was a large black circle on a white background.
I want to make some modifications to the code (and maybe the underlying library files) to try to make the robot able to handle other types of paths with more acute angles and sharper turns, etc.  But, I don't understand some aspects of the highest level .ino source code file.
I am a little unsure of pasting such a long code block below and also don't think an image of it will help.  The version data for the file I'm using is below.  The files can be found online @ LINK
// ******************************************************************************    **
// * File Name          : linefollow
// * Author             : RadioShack Corporation
// * Version            : V1.0
// * Date               : 2014/01/16
// * Description        : Optical sensors send feedback to PCB
// *                      to make the robot follow a black line on a white background.
// ********************************************************************************

In this .ino file, I don't understand the code from line 68 onwards: from the Read Left/Right Optical Status onward...
I don't understand some of the bitwise operations there and don't really see how the sensor readings (whether it is over a white or black area on the surface) correlates to which motor activates to keep the robot on the course...
From my limited understanding of Arduino, this robot kit, and the code, it seems like the software and hardware have to interact in this way:

Robot moves forward using both motors turning the wheels in the same direction.  It approaches the black test circle at a shallow angle (i.e. almost tangent to it) to allow one sensor to go over the black line before the other one does.
Optical readings of each sensor are taken periodically.
If both sensors detect white space, robot continues to move forward.
If the right sensor detects that it has gone from white to black and then to white, it means that the robot needs to turn to the left to stay on the path.
To turn left, the left motor is un-powered and the right motor is powered until the right sensor detects black again.
Now that the robot is on course, it will keep turning in the direction of the sensor that detects a white to black to white transition.

I am not seeing how my intuitive understanding of the robot's operation matches with that of the code...

The files can be found online. - Where online...?

@Majenko Please see added LINK in original post.  The original "OEM" link that came with the kit's manual gave Error 404, so another site had the files.

Indeed, the way the bitwise operations are written is confusing.
  if((sensor_in & 0xf00)==0)
    sensorValue1=sensor_in & 0xff;
  else if((sensor_in & 0xf00)>>8==1)
    sensorValue2=sensor_in & 0xff;
  if (sensorValue1 == 0x00)
    action1 =action1 & 0xfe;
  if (sensorValue1 == 0xFF)
    action1 = action1 | 0x01;
  if (sensorValue2 == 0x00)
    action1 = action1 | 0x02;
  if (sensorValue2 == 0xFF)
    action1 = action1 & 0xfd;

Basically you have two input values that can be in the same variable - differentiated by the 9th bit of the value.  Values between 0 and 255 relate to one sensor, between 256 and 511 to the other.  The bitwise operators split that into sensorValue1 and sensorValue2 accordingly.
Then those sensor values are compared to 0 or 255 and used to define the action to perform - that action being comprised of the lowest two bits of a byte variable, so you have three possible actions:
0 = both sensors off
1 = sensor 1 on, sensor 2 off
2 = sensor 1 off, sensor 2 on
3 = both sensors on

The comments in the program also tell you this information:
action1
         left        right
0x00    black        black
0x01    black        white
0x02    white        black
0x03    white        white

Now you have how to deal with the action value:
if(action1 != action2)
{
  if (action1 == 3 )
    line_following.go_forward(50);
  if (action1 == 1)
    line_following.line_following_turn_left(50);
  if (action1 == 2)
    line_following.line_following_turn_right(50);
  if (action1 == 0)
    line_following.go_forward(50);
}
action2=action1;

So if the action has changed, we can change what we are doing:

If action is 3, so if both sensors read as white, or if action is 0, so both sensors read black (in other words if both sensors read the same) then move forwards.
If action is 1 (so the left sensor reads black) then turn to the left.
If action is 2 (so the right sensor reads black) then turn to the right.

So basically if it doesn't know anything better, it drives forwards, otherwise it turns in the direction that it finds the black line, thus keeping it always on that line.  As it drifts off the line one sensor will sense white, so the robot will turn away from that whiteness and back on to the line.

Thanks for taking the time to answer my questions.  What tripped me up at first was all the values being in Hex and the bit-wise math.  I had to read up on bitwise math on the Arduino reference website.

In addition to the answer given on this site, I had to do some reading up on what bit-wise operations are and how they are useful.  I did most of that reading on the Arduino website reference section.
I also stumbled across an online tech blog that actually dissected the inner workings of this program!  The blog's author seemed glad to help Arduino beginners who got this kit, but had trouble understanding how exactly the robot moved in response to the sensor data.
JoesTechBlog
Someone even asked the blog's author about why anyone would code the logic in this manner.  I too was wondering the same as to why it wasn't done at a higher (thus easier to understand level).  Below is the author's response to that question.  Can anyone here comment on it in terms of its veracity?

Hello Richard, Yes I agree this logic is non-intuitive. I would have done the >logic on the mirco-controller, that lives on the driver board, and just had >the read_Optical() method return a 0, 1, 2, or 3. But there is one possible >reason for this logic. Performing bitwise operations in most cases takes up >less CPU cycles than complex number comparisons. Since Radio Shack is not >providing us the source code that runs on the driver board. Then we can only >guess. Also sometimes bare metal programmers think in these terms, which may >seem non-intuitive at times, but the more we start working at the bit level >the more it makes sense.
Thanks for the post.
Joe


text:
What is the Arduino Uno default sketch?
When I bought my Arduino Uno and connected it to my computer, I tried to make the simple blink circuit (before programming the Arduino) and suddenly the LED started blinking. Is the blink example the default Arduino sketch?
I am sure that I didn't uploaded anything to the board.

Some may have the "Blink" sketch pre-installed, but many don't. However, when there is no sketch installed the board sits in bootloader mode waiting for you to upload a sketch.  While it's in bootloader mode the LED pin pin D13 blinks.
If your LED is blinking about once a second then it's the Blink sketch.  If it's rapidly blinking three or four times per second or so then it's in the bootloader and you have no sketch loaded.

For me it was blinking 1 time at a second. By the way, what makes the bootloader blink the pin 13 if there is no sketch loaded, is it a normal sketch ?, and why that don't happen when I upload the "BareMinimum" example ?.

@AsadMarmash The bootloader is just software. It runs before the sketch runs if there is a sketch installed. If there isn't it just runs and runs and runs. It blinks the LED because it blinks the LED. That is what the programmer that wrote the bootloader decided to program it to do. It doesn't blink with BareMinimum because BareMinimum doesn't blink the LED, and it is a sketch, so the bootloader runs it.

See my answer about the bootloader. The bootloader only flashes the LED 3 times. If it keeps flashing then the supplier must have uploaded the Blink sketch as a default.

source: Stack Exchange

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

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

sort: votes


text:
are 3 connections necessary for a push button?
I'm referring to the 5th circuit (see below screenshot) of the sparkfun manual came with the arduino uno. Instead of connecting all three of the (+) (-) and the digital pin to each push button, can I just connect the (-) through the resistor and the digital pin?
Also a side question, in terms of physics, you need two ends to be connected in order to create pressure for the flow of electrons, but the digital wire for each push button that goes out to the arduino board doesn't have its own ground wiring that suppose to create the pressure as a couple. How to cope with that in terms of electron flow?

You need two connections to the switch, but the pullup resistor requires a voltage source, which is a third connection.  You can place the pullup either at the switch, or at the ditial pin, or somewhere in between.  You may be able to use internal software-configured pullups instead.   All currents have closed paths - but they may be sharing a path with a current headed elsewhere, for example, when you close a switch a small current discharges the pin capacitance, sharing the ground path with a larger one flowing through the pullup resistor.

So can i just connect the (-) with the resistor?

No, you cannot, as then you would not have any signal line.

i meant i kept the signal line, along with the resistor which connects the ground node

The resistor does not connect to ground.

i meant if it does, that's what i said in my question "connect the (-) through the resistor and the digital pin"

That is neither what you should do, nor what you have shown in your diagram.

The diagram is the sparkfun circuit that I am referring to, of course it doesn't show what i'm describing. I thought anyone who played with arduino would recognize that screenshot as something from the manual that came with it, I'll edit the question to make it clear.

You can use the internal pullup e.g.
pinMode(inPin, INPUT_PULLUP);

Then wire your switch between pin and Gnd.

In order for an input pin to be able to read a real value it must be connected to something - either a power source (Vcc) or to ground.  If it's not connected to either of those and left "flapping in the breeze" then it's said to be floating and the input value cannot be determined.
So you need a way of switching that input pin between being connected to Vcc or being connected to GND.  That is why there are three wires - the input pin and the two voltage levels that must be chosen between.
Now an input pin has a very high resistance (impedance) to ground. So when you connect it to Vcc a very tiny current will flow through it to ground, thus completing a circuit.  If you add another resistance between the pin and Vcc the incredibly small amount of current that flows will only cause the smallest of voltage drops across that new resistor (see Ohms Law).  So connecting the input pin to Vcc through a 10kΩ resistor (for example) will mean the voltage read at the input pin will be only fractionally below the +5V of Vcc.
Now when you introduce the pushbutton, which connects the input pin to ground when pressed, will also connect the resistor to ground. So you have the full 5V of Vcc across that resistor, and the input pin will be reading 0V.
Without the resistor in there - if you just connected the input pin to Vcc and then had the button connecting to ground - as soon as you press the button it would connect Vcc directly to ground, which is a really really bad thing to do. That's called a short circuit, and it's when batteries start to explode and wires melt.
So the input pin itself is basically a voltage detector that detects what the voltage at the input pin is.  It has two thresholds known as VIH and VIL - the input logic voltage for HIGH and LOW respectively.  On the Arduino those are 0.6Vcc and 0.3Vcc - or 60% of the supply voltage for high, and 30% for low. At 5V that's 3V and 1.5V respectively.  If the voltage seen at the input pin is above 3V then it's seen as being HIGH. If it's below 1.3V then it's seen as being LOW.

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


text:
How do I control 4 LEDs with 2 Digital Outputs?
In an effort to learn about transistors that seemed easy enough. But I can't get it to work in practice
Can I control 4 LEDs with just 2 digital outputs (High, Low). So I figured I would use the difference between PNP and NPN transistors to create logic gates.
[00,01,10,11]
But I can not seem to get this to work in practice for the life of me.
I read about Charliplexing, but that is n*(n-1), which isn't good enough. I've also read about shift registers, but I'm not sure I fully understand (I'm a noob), and it sounds like you need a minimum of 3 pins. Is what I am trying to do even possible? If not, then why?

Using two pins it is possible to drive 4 LEDs as long as you only want one of them on at a time.  One LED will always be on - it's not possible to have a setting where there is no output selected.
Basically you are "decoding" a binary value output:
00 = LED 1 on, other three off
01 = LED 2 on, other three off
10 = LED 3 on, other three off
11 = LED 4 on, other three off

To do that you need to use (or construct) a 2-to-4 decoder.
Using logic gates it can be constructed like this:

If you can translate that into transistors then you'll end up with quite a lot of transistors.  Most people would use a specific 2-to-4 decoder chip such as the 74HC139.
Shift registers usually require three pins, yes, though there are possible ways of working with two pins.  You require two pins to provide the data and clock signals, and a third pin to latch the shifted data out to the outputs. However it is possible to use the first leading edge of the clock signal or a specially formatted data signal with a capacitor to create a pulse just before sending new data which can latch the old data.  This requires careful consideration though regarding how fast you would be transmitting, etc, and is not really recommended.
A better solution if you are limited in pins and need to drive multiple LEDs is to use WS2812 "NeoPixel" LEDs which chain together and use a single wire protocol to send data to all the LEDs in the chain.  You can support many LEDs (even hundreds) on a single IO pin, and they are full 24-bit RGB to boot.


text:
UART Software Serial - Syncing two sensors to make a tx and rx beacon
Problem
I've been trying to a create a receiver and transmitter beacon for a following robot, but have not been able to sync my two SRF02s to one another.
Any advice?
Code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX

void SendCmd(unsigned char address,unsigned char cmd)
{
  mySerial.write(address);//set the address of SRF02(factory default is 0)
  mySerial.write(cmd);//send the command to SRF02
}
void setup(void)
{
  Serial.begin(9600);
  mySerial.begin(9600);
  Serial.println("SRF02 TEST!");
}
void loop(void)
{
  unsigned long t3;
  unsigned long t1=micros();//time tx command issued
  SendCmd(1, 0x5C);//send pulse with transmitter
  unsigned long t2=micros();//time rx command issued
  SendCmd(2, 0x5B);//listen for pulse returns results in microsconds

 while(mySerial.available() < 2)//if two bytes were received
  {}
    t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
    t3 |= mySerial.read();// receive low byte as lower 8 bits
    unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
    unsigned long Dist = (Tm/29); //converting microseconds to cm
    Serial.print(t3); // print the reading
    Serial.println("cm");
    //Serial.print(tm);
    //Serial.println("ms");

  delay(250); // wait to read the output

}

Output#

Your distances seem implausible, so you need to investigate.  Try printing out the components of the delay, both measured on the Arduino and on the sensor.  Also consider that sound will travel a fair fraction of a meter during the time it takes to send the second command, and see if the software serial output routines buffer or block until the data is actually sent.  Preferably, for precise timing you should use discrete strobe signals and hardware timers, not serial commands and software.,

How far apart are your 2 SRF02's?  Also, when debugging print the data in a raw form as well as (or instead of) processed -- ie, print out t1, t2, t3 as well as Dist

theyre roughly 15 cm apart

I don't think what you are trying to do is possible with those modules.
I think what you are trying to do is transmit a 40KHz pulse on one module and find out when it arrives at the other module. Unfortunately that is not going to be possible with serially attached modules - simply because it takes longer to transfer the serial data than it does for the ultrasound pulse to travel between the two modules.  That's why you're seeing such big values - you're actually measuring the amount of time it takes to transfer the serial data, not the sound.
For those modules to work they have to transmit a pulse themselves and then listen for that pulse and they return the difference between those two events. The timing for that is all done internally to the module and the results are returned through serial. Trying to perform the individual operations through serial is just not going to happen.
A better solution would be to modify an HC-SR04 module.  De-solder the transmitter from the board and re-connect it with some wires - that is then your remote module. You can do the same with the receiver module if you want it remote from the board if you like.  Then you interface the HC-SR04 direct to the Arduino and use it as you normally would.

Edit:
Ok, so it seems there is a method of using them (AKA "Fake" sensing - idiotic name if ever there was one) that could be made to work if it's done precisely right.
However, doing it precisely right, as you have seen, is not easy.  Timing is critical. Timing of when you send instructions, and how you determine exactly when an instruction has been sent.
You would be much better off using a real hardware UART than software serial. That would mean upgrading your board to one with more than one hardware UART since you are using the only one the Uno has for your serial monitor.
I would also recommend not using the Arduino's Serial object(s) for this since they impose their own buffering and asynchronous transfer of data which will really really mess with your timing.  Instead you should manually manipulate the registers directly - that way you can know exactly when the final bit of the serial commands have reached the ultrasound module.
You should also send the command to the receiver first before the transmitter.  Did you know that at 9600 baud it takes about 2ms to transfer two bytes?  In that time sound will have travelled about 68cm.  If you start the receiver first then start the transmitter the receiver will be running when the sound wave reaches it, as opposed to when the sound wave is somewhere in the next room.  Then of course you have to take into account the time between starting the two properly, and that all comes back down to knowing your timing exactly.

So what you're saying is that I would have to create a continuously pulsing transmitter at 40KHz and use the receivers in their standard mode? If that is the case am I covering the transmitting transducers on the receiver modules, but still sending a pulse to time the events between sending and receiving?

Actually this is not true.  I suspect it as well, but a quick lookup of the parts suggests that bistatic operation is a supported usage mode.  I join your concern about the latency of serial communication, but while suboptimal there are perhaps ways of working around it, for example starting the receiver first and determining a (with care potentially fairly constant) serial message delay to subtract.

@ChrisStratton I see what the "Fake" mode does now. That's really an incredibly stupid thing to call it...! So yes, it could be possible if you do it absolutely perfectly correctly and time everything precisely. Far from ideal though, especially on an Arduino that has so many variables - you'd be best off a) using a hardware UART, and b) not using the Arduino's Serial object with its asynchronous transmission.

Probably better to use I2C instead of Serial. However, note that error due to Serial latency should be less than 70 cm (the distance sound travels in the time taken to transmit 2 Serial bytes at 9600 bps), but the data shown varies rather more than that; and anyhow, variability due to that latency ought to be negligible, so it seems to me Serial latency isn't likely to be the problem, but something else.

But if i want to make a wirelss receiver and transmitter beacon, I am not able to used I2C correct?

theyre roughly 15 cm apart

15cm substantially less than the time it takes to send the second device its command at 9600 baud (2 bytes, probably 20 bits counting framing, around 72 cm)
As a result you are likely missing the pulse, and perhaps catching some timeout, or even a cached response string from a next-to previous command which measured the previous pulse, including the time between pulses.
To operate that close, you will need to either use dedicated trigger/detect wires, or start the receiver before you transmit and try to subtract the delay from the time you started the receiver until the time when you transmit.
Beware that usage of software serial, as well as buffering of serial in general may introduce variable latency in your timestamping of the serial communications.  Ideally for something like this you would use a non-buffered implementation - the timing of serial data itself is potentially precise to a fraction of the baud rate, though we don't know how it is implemented on the sensor end.

`void setup() {
//Choose 9600 baudrate
Serial.begin(9600);
}
int x; //Byte
int n; //Number of available bytes
void loop() {
//Address
Serial.write(2);
//calls address of srf02 - 0x02
Serial.write(0x51);
//Send Pulse from 0x00 - no ranging takes place
n = Serial.available();
if(n > 0){
for (int i = 0 ; i < n; i++){
unsigned long x = Serial.read();
Serial.print(x,DEC);
}
Serial.println();
}
delay(1000);
}`   This is another code with just serial.writes. do you think i'm better off implementing something like this?


text:
Arduino power sources
Is it safe to connect a USB input to an Arduino (Nano) at the same time as an external regulated 5V supply to its 5V pin is connected, assuming the supplies have common grounds ? Will (I hope) the external 5V be used so as to not draw too much current out of the USB supply ?

From the Arduino Nano at Arduino.CC:

The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

Or, take if from the schematic:

OK, I see a section labelled +5V auto selector, with a Schotky diode between +5V and the VUSB rail, I don't understand enough about electronics to see what this does though. I get that if I supply 7V, say, to Vin then the Nano will use that as the 'highest voltage source'. I could perhaps use a variable voltage source fed from the batteries and set it to, say, 5.2V and force the Nano to use that? The reason for all this is that the Nano will be connected to a Raspberry Pi via USB for communicating with the ros system, and the Pi is unable to supply much from its USB ports, it cant run, for example, a WiFi dongle, mouse and keyboard at the same time.


text:
Suggestions for latest ESP8266 WiFi module
I am having problems with the ESP8266-01 I bought. It works at only 115200 baud rate and it gives many problems when programming with Arduino Uno. I got it flashed to 9600 baud rate, but still many times it becomes unreliable.
I have seen many videos online that has the ESP8266 that works at 9600 by default.
Could someone please tell me where I can buy the latest ESP8266 that runs at 9600 baud rate by default?

No, I'm afraid we can't, since we're not ESP8266 salesmen.
However, I would seriously recommend not using an Arduino to communicate with the ESP8266 but instead to program the ESP8266 directly so you don't have any communication worries.  If you want to add an Arduino into the mix at a later date for its enhanced IO capabilities, then feel free to do so - where you can then implement your own serial protocol at whatever baud rate you like (or other protocol even - SPI? I2C?).
All you need is:

The Arduino core for the ESP8266: https://github.com/esp8266/Arduino
Some form of USB serial adapter (eg FT232 breakout board).

The controller chip on the ESP8266 is considerably more powerful than the Arduino's chip, and the fact that many people insist on using the ESP8266 as a slave device to the lower powered Arduino always seems completely backward to me.
If you want an easier board to program that messing with breakout boards you can do a lot worse than investing in a NodeMCU board. Make sure you go for the version 1 not the version 0.9 since the version 1 has a slightly more enhanced chip on it with more IO facilities than the version 0.9.

Thank you @majenko. But I m not that much of an electrical guy. I want to do a project on home automation. I learned to control the relays using arduino. Now I want to control my arduino remotely so that I could control relays with arduino easily. That's why I am using esp8266 with arduino. But I am having lot of problems with baud rate and serialsoftware. Could you please give me a solution for this?

Or could you provide me a link where I could download the latest firmware of esp8266 and flash it to use at 9600 baud rate easily

I have. Ditch the Arduino and get a NodeMCU. With the Arduino core installed it's exactly like working with the Arduino. Same language. Just a lot easier to work with for WiFi.

My mom will burn me. I bought lot of electronic equipments online. Or could you give me link of the latest firmware bin file for esp8266. Please. @majenko

I don't know a link for that kind of thing. This is an Arduino site not an ESP8266 site. Maybe you should ask for that link on an ESP8266 site, or ask google for it.

Thank you for your comments. @majenko. I will try my best.

The ESP8266 has 3 SPI slave selects, but note that one of them is used for the off-board flash that contains the firmware, and not all modules make SPI available externally. UART is the way to go, since it is available on most if not all modules.

@IgnacioVazquez-Abrams I use my ICSC library on the ESP modules for serial communication. Works well and is very easy to use.

@Majenko I think often Arduino is used as master because it has lower power consumption in the lowest sleep modes: it can send ESP8266 into the power down most of the time, and therefore save battery. For example https://openhomeautomation.net/esp8266-battery/ If you have only ESP8266, can you wake it up from deepsleep from the uploaded firmware?

Here's the other bit of it that most people don't understand on their first try.
Everything that plugs into an arduino is not a slave device.
In this case both this module and the hc-05 and hc-06 are standalone and actually HAVE THEIR OWN SOFTWARE on them. These chips are fully functional without arduino and you can send commands to them directly or by using the arduino as a dummy chip.
So at the end of the day to get your project working you should interface with the device directly instead of passing it through arduino.
Your device most likely isn't busted so don't worry about constantly flashing between versions. You probably just need to configure it using AT+ commands.
Here is a pdf of AT+ commands
Download pdf
This is a quickstart guide that includes pictures and order of commands. Don't fry your boards.
Download pdf
After that's done serialCommand amd software serial are pretty easy to use. Look at the serialCommand examples to see how it's done.
SoftwareSerial example using serialCommand

The problem is that you need another device to send the AT commands, and they need to be sent each time the device is powered on. This is why reprogramming the device to work completely standalone is a better solution.

Why do they need to be sent every time? Shouldn't it be able to function on it's own from stock? the whole point behind AT commands is that you can initialize it so it can function as needed, and not need to set things such as the baud rate and the name every time it's reset.

If I'm wrong that's fine, I just don't understand why you would need to do that every time. I have worked on other AT devices like bluetooth and it seems to hold up just fine after initialization.

Those devices have a firmware which is programmed to store settings on the module itself. The AT firmware for the ESP8266 for the most part is not.

Looks like I'm going to toy with it this week. I'll get back to you


text:
Cameras modules for my project
I would like to implement a camera to my Arduino project.
So far I have worked with some sensors (e.g. distance), Wifi and Bluetooth modules, buzzer etc. You can find some very good examples on the web on how to use these things on your project, from the wiring to the sketch.
But when we talk about cameras, I feel like things start to be more difficult - I don't know if it's because camera users should know better what they are doing and therefore don't need a step by step guide, if simply there is a lack of information.
I see myself like this guy and this guy. We just can't find a tutorial!
I'm looking forward to buy a VGA OV7670 AL422 FIFO camera or a Serial TTL JPEG with NTSC video, but I don't want to spend my money on something I won't be able to use.
There is any better camera I could buy (by better I mean an easier camera to start working and with some information for the implementation)?
Thank you.

An arduino really isn't a very good platform for camera projects - limited goals involving still or slowly updated images are possible but tricky and it isn't even remotely cost effective.  If you want to do something with a camera, get a low end embedded linux platform and a cheap webcam, or find an outdated Android phone.

Is there a particular reason why you want to specifically use an Arduino to use a camera?
There are ressources out there: haven't proofread in depth, but this example using a MSP430 launchpad looks good.
Also a good excuse to give Energia & launchpads a try, if you only know Arduino.

Funnily enough there is another question about cameras and the Arduino.

I am currently experimenting with this module: http://www.uctronics.com/mega-pixel-camera-module-mt9d111-jpeg-out-p-227l.html
I2C connection and supplies are working fine with an Arduino Uno, but getting the image data with an Arduino might be not possible.
You can slow down the Pixel Clock of this module to 375kHz, bit I think the  GPIO read-out speed (at least with the standard digitalRead functions) and memory of the Arduino are not sufficient...

Take a look at the Arducam mini (http://www.arducam.com/tag/arducam-mini/)
I just made a custom Arduino based PCB using this camera and it works great.

I am using this camera, it has an OV568 on board. Getting a photo takes a few seconds, on the UART, which is slow, but could probably sped up if I change the baud rate. But for now I don't need to fiddle with that. Also the image is a JPEG, and what can you do with that in an Arduino? In my little project, it doesn't matter, the Arduino passes the data along to a computer, which handles it. No problemo.
But as a proof of concept, I used the JPEGDecoder library to display the photo on my Arduino Mega, with a small 2.2" TFT screen. If takes between 50 to 60 seconds to decode the JPEG and display it on the screen. And that JPEG was in an array, not even on an SD card. Gasp.
So depending on what you're looking into, you might want to rethink the whole idea. You'd be better off with a Raspberry Pi or a Beagle. Arduino won't cut it. There may be some 32-bit MCUs, like the Chipkit series, that could provide a performance boost.


text:
Atmega328P burn bootloader with FTDI
I need your help.
I am using Arduino ProMini in my project.
In project board there is Atmega328P which doesn't have Arduino bootloader, and Atmega328P RXD, TXD pins are connected to FTDI Basic(sparkfun)'s TXD and RXD pins.
I searched on internet how to burn bootloader for arduino. Most of them use other Arduino's built in SPI or other method. Problem is Atmega328P is already assembled to PCB board and I cannot make any soldering or change. Atmega328 and FTDI basic are connected and assembled to upload sketch (if there is bootloader of Arduino inside of Atmega328P, no problem to upload sketch).
Is there any solution or suggestions to burn bootloader using FTDI?
Thank You.

You cannot upload the bootloader through the ATmega's UART pins, but the necessary pins (SPI & reset) are quite likely broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task.  Otherwise you may just have to desolder the chip.   A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices will require far less work on your part.

@ChrisStratton You should turn that into an answer

Every one of the dozens of Arduino Pro Mini I've ever tried to program came with the Arduino bootloader. Are you saying your Arduino Pro Mini somehow doesn't have a bootloader? Or are you saying that you know your FTDI adapter is working because you can upload your sketch to an Arduino Pro Mini, but you get an error message (quote it exactly please) when you upload the exact same sketch with the same FTDI adapter to this other ATmega328P ?

@ David Cary There is new Atmega328P MCU (even fuses are not set) on PCB. AFAIK, I need to burn Arduino bootloader, and it becomes Arduino. To burn bootloader, it seems I need SPI. But Atmega328's SPI pins are not connected to anything on PCB. It seems we need to hardware design again and add SPI feature on PCB. Thank You

You cannot upload the bootloader through the ATmega's UART pins.
Perhaps the the necessary pins (SPI & reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.
Otherwise you may just have to desolder the chip.
A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part.

After several attempts and searching on Internet, I gave up and decided to design hardware again. It is impossible desolder the Atmega from PCB. PCB is so small and my soldering skill is not enought :((  THANK YOU FOR YOUR ANSWER

Planning for ISP access is of course a good idea.  If you are working with through-hole parts you may want to use a socket on the next prototype, but you could rescue the board by cutting the IC pins and using a new chip (you can, incidentally, buy them with the bootloader already loaded).  If you are working with SMT a hot air desoldering tool will pay for itself the first time you rescue a custom board that might have been damaged by cruder removal attempts.  But it's not clear that you needed to remove the chip anyway, unless you had peripherals driving the needed pins in conflicting ways.


text:
Why LED light delay is 5 second in arduino?
My code :
int pin = 8;
int pout = 12;
int result=0;
void setup() {
  pinMode(pin, INPUT);
  pinMode(pout, OUTPUT);
}

void loop() {

  result = digitalRead(pin);

  if(result == 1)
  {
    digitalWrite(pout, HIGH);
    delay(1000);
  }
  if(result == 0)
  {
    digitalWrite(pout, LOW);
  }

}

I have set delay 1 sec but whenever i put high voltage on pin 8 The LED glow for 5 second. why?
How to set delay to none ? means whenever the pin 8 is HIGH the LED will glow else off.

The problem (likely) isn't in your code. You need to include a pull-down resistor in your electronics, so that when you remove the "high voltage" the residual charge stored in the pin due to its capacitance can be drained. Alternatively you can use the internal pull-up resistors, but then you'd need to invert the logic of the pin (high becomes low and vice versa) and instead of connecting "high voltage" you'd need to connect ground to activate the LED.

1. changed result=1 digitalWrite(pout, LOW)and result=0 digitalWrite(pout, HIGH) still have the same issue LED glow for 3,4 second 2. also use this if(result=1) digitalWrite(pout, HIGH); delay(100);digitalWrite(pout, LOW); still no luck LED goes on and off for 3,4 sec. 3. I have put 6k ohms resistor  between LED still No luck. :(

You need to put the resistor between pin 8 and ground, not on the LED.

ohh, awesome :) works now thanks. added 2.2k ohms worked and 680 Ohms is also working. Could you please let me know how to choose resistors?

The precise value doesn't matter. A relatively high value like 10k is customary. The higher the resistor, the less current is wasted when the switch is on, but the slower the residual charge will drain.


text:
How can I power an Arduino in a 3-phase environment?
I am working on a project which uses an Arduino board. Currently I am testing my device using 2-phase power and it works fine.  I want to use that device in agriculture fields where 3-phase power is available instead. How can I do this?

Typically low wattage accessory equipment in 3-phase systems is supplied by just two of the three wire phases, but you will need a power supply rated for the unusual voltage which results.

You do not want to connect your arduino to mains voltage, do you? So your question is probably about the powers supply you are using. As there is no arduino branded PSU you will have to give us more information about  that PSU and your local mains voltages. Otherwise it will be deleted.

The very short answer is that the Arduino board itself is designed to be powered by low-voltage DC (but you almost certainly already know this). So what you're really asking, I think, is "can you use the mains power supply that converts mains AC to DC on a three-phase supply?"
The answer to that is a guarded yes. You will need to confirm that you are connecting to a single phase (basically what you were doing in testing) and that the voltage is appropriate for your power adapter.
The abridged version of the gory details follows…
Three-phase supplies are almost always used for motor or other power applications – for a low power device like an Arduino (or even lighting or small appliances) you don't typically need three-phase. What is usually done is to take the power supply for those devices either from phase-to-neutral or phase-to-phase – depending on the configuration of the three-phase supply.
Wikipedia has an article on three-phase power that explains the common connection schemes (Y or star where the three phases are wired to a common point, and delta where they are wired in a triangle). What is significant is that you will typically get a high and a low voltage depending on how you connect to a three-phase system. For example in the US a common Y three-phase service will give you 120 V phase-to-neutral and 208 V phase-to-phase.
A true 3-phase (as in needs to connect to all three phases) low-voltage power supply will probably be quite expensive. But you also don't need one. Unless you are building an "industrial" device all you need is a "normal" low-voltage power supply that is designed for the voltage that you'll be connecting it to.
All you need to do is to confirm the voltage that you'll be using and check that your power supply is rated for it. Many low voltage supplies are designed to be "universal" and you'll see a rating like 100-240 V, 50-60 Hz. That's likely to work on most three-phase supplies as long as the connection isn't phase-to-phase in a part of the world where the high voltage is in the 400 V range.

There are a lot of 3-phase PSU. But in fact not many provide a voltage suitable for an arduino. Example: [http://www.pulspower.com/index.php?reqNav=product&objectId=21], which is a device using explicitely two phases of a three phase system, not from a two phase system. The manufacturer also has real 3-phase PSUs, but only with Vout beginning with 24V.

I'll correct what I wrote. Supplies like that exist, but if you're just doing something small with an Arduino are way bigger (and probably way more expensive) than what is required. The one you linked to is capable of providing 8 A at 12 V DC and is designed for mounting in a control enclosure. I'd expect you're paying a premium for that too. So it really depends on what you need – if you're looking for industrial grade gear, then that is a good example of what is available, but if you're just looking to provide power for an Arduino in a 3-phase environment, you can get by with less.

3-phase transformers are not cheap in general and low-voltage 3-phase transformers are very niche since taking such a small amount of power from 1 or 2 phases won't affect PF very much.

The one I linked is in the wild for about 100 € without VAT. Which is a pretty good price considering the specs. But that won't help our friend with tapping the powerline running over the rice field. (This could explain, why he has no neutral). :P

€100 is not a bad price, but still way more that you would have to spend to power an Arduino in a three phase environment. It really depends on what the goal is… But for prototyping I'd be tempted to spend less – at least to start with.


text:
How can I program RFduinos and how can I connect them with Bluetooth?
My RFduino dev kit just arrived, and for my project I have to connect a few RFduinos via Bluetooth and light up certain LEDs attached to the RFduinos. If anyone could point me in the right direction as to where I can program them/how I can connect them, it would be GREATLY appreciated.

I am starting on a similar project (without the Dev Kit).  Hooking the Bluetooth module to the RFduino is pretty straight forward, PWR to PWR, GND to GND, remember to cross the transmission wires: TX to RX & RX to TX.
In your void setup(), you need to start the connection:
Serial.begin(9600); // check your documentation to see the baud rate

In your void loop(), read or write to/from the bluetooth connection with serial write/read. Serial.read() or Serial.write()
Remember that Bluetooth is a communication protocol, not a controller.  You don't mention WHAT you are connecting your RFduinos to using Bluetooth. You still need a controller capable of sending a signal to light up the LEDs using Bluetooth.

Thank you that is very helpful. I plan to use my iPhone as a controller, but I also want to make my own App. I don't want to use the pre-existing RFduino LED controller app. (the one on the app store)

Sweet!  I'm doing the same thing with Android!  However, life has put this project on hold for a while.  Please keep me posted on your progress.


text:
Why does my Arduino keep waking up?
This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search.
I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial here. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds).
In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish sleep until interrupt wakes, perform interrupted action, then go back to sleep. What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?
Thanks for the help!
#include <avr/sleep.h>
#include <avr/power.h>

ISR(TIMER1_OVF_vect)
{
 //do nothing
}

void enterSleep(void)
{
  set_sleep_mode(SLEEP_MODE_IDLE);

  sleep_enable();

  /* Disable all of the unused peripherals. This will reduce power
   * consumption further and, more importantly, some of these
   * peripherals may generate interrupts that will wake our Arduino from
   * sleep!
   */
  power_adc_disable();
  power_spi_disable();
  power_timer0_disable();
  power_timer2_disable();
  power_twi_disable();

  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the timer timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  /* Re-enable the peripherals. */
  power_all_enable();
}

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

  /*** Configure the timer.***/

  /* Normal timer operation.*/
  TCCR1A = 0x00;

  /* Clear the timer counter register.
   * You can pre-load this register with a value in order to
   * reduce the timeout period, say if you wanted to wake up
   * ever 4.0 seconds exactly.
   */
  TCNT1=0x0000;

  /* Configure the prescaler for 1:1024, giving us a
   * timeout of 4.09 seconds.
   */
  TCCR1B = 0x05;

  /* Enable the timer overlow interrupt. */
  TIMSK1=0x01;
  while(!Serial);
}

void loop()
{
    enterSleep();
    Serial.println("Waking");
    //delayMicroseconds(10000);
}

Yes.  Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.
You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.
If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent.  If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done.  A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.

You can use Serial.flush() to block until all the data has been sent from the buffer (and the last byte has been sent from the UART internal buffer register).

Great! Thank you! Both very helpful answers.


text:
Arduino IDE Visual Studio and compile problems blank project .ino hack
I'm new to Arduino and have little programming experience apart from my computer science degree.  I used C++ for some projects in my degree but am barely proficient.
My first project is relatively complex process control for an Arduino beginner and I've quickly become frustrated with the Arduino IDE which seems to be a common problem.  I've installed Visual Studio with the Visual Micro plugin (Win7) but I'm getting compile problems.  I have successfully built a data logging sensor array both in Arduino IDE and Visual Studio in Win7, but as I'm trying to add complexity I'm experiencing difficulties.
I found this recommendation on Gammon Forum for use with the Arduino IDE to achieve a standard C++ build environment but it's not working in the visual studio environment.
Files contained in "EmptySketch" project folder:
"EmptySketch.ino"
//beginning EmptySketch.ino
//end EmptySketch.ino

"TestSketch.cpp"
//beginning TestSketch.cpp

#include <Arduino.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  // put your main code here, to run repeatedly:
}
//end TestSketch.cpp

When I create a project in Arduino IDE this compiles, uploads and runs with the expected output, but when I open EmptySketch.ino in VS it builds, uploads but gives no output.
Can anyone help me with this approach or should I simply upload my real project using a conventional .ino which won't compile and ask for help with that?

Firstly, please format your code correctly. Edit the question, highlight all code and press CTRL + K. Secondly, if you upload a blank sketch, what do you actually expect to happen?

Maybe, instead of a complex first project, slowly work through the examples in the Arduino Cookbook, or some other such literature, in order to familiarise yourself with the code and coding environment. The Arduino IDE is an extremely simplified environment, but even so, it  still takes some getting used to. However, I'm sure after a few examples you will be up and running...


text:
Programming addressable LED
I have TM1812 addressable LED strip (1meter long 96 LED). I am looking a way to program it and i found this http://www.deskontrol.net/blog/arduino-based-artnet-node-for-led-pixels/
and its mentioned in article that it doens't work with current version of Arduino IDE.
Is there some other lib/api available to program it or another method?
UPDATE
As mentioned by @dlu FastLED support wide variety of LEDs. I contacted developers of FastLED on google + and they have updated there documentation for support of TM1812 its similar to TM1809

There is a very nice library called FastLED, it is also on GitHub as FastLED/FastLED. It is quite flexible and supports a huge range of addressable LEDs. I'm currently using it with 1.6.6.
The code that you linked to was developed with an older version of the Arduino IDE, so you might want to see if you can find an older version and try building with that.

I checked there reference sheet. its not mentioned anywhere they support TM1812. https://github.com/FastLED/FastLED/wiki/Chipset-reference

Ack, I'm sorry I was writing from memory and TM1812 is close to the WS2812 that the NeoPixel uses. I'll fix it…

Can i use WS812 library to program TM1812 or any other libs?

I need to go look at them. Do you have a data sheet you could link to? Looking at the GitHub page (https://github.com/FastLED/FastLED/wiki/Overview) I see that they are planning to support the TM1812, but don't have support yet. It might be worth contacting the authors and asking about the status of TM1812 support. Also since they support similar chips (by number) it would be worth comparing the data sheets to see how hard it would be support the newer chips.

How can i program them without using any library.

All TM chip Family is supported by Fastled Libs if you use a TM1811 just put TM1809.
It should work, I have tried and it succeeded.


text:
Prevent Switch case from not being complete
I got this program. It controls a refrigeration room using a ds1280 temperature probe.
The thing is, sometimes the probe reach 7.00°C then the refrigerattion cycle start (refrigeration cycle is on a switch case statment) and then the probe read 6.75. So the refrigeration don't complete its start and leaves part of the system in wrong mode.
How can I add some guard to ... once the switch case statment don't being interrupted by anything unless complete the on in this case or the off in other case.
Here are the most resembling parts of the code.
void turnOnCompressor(){

/*
This subrutine is intended to stop the refrigeration cycle
in the most ordered way, and keeping the refrigerant on
the high side of the system.
*/

// boolean refrigerattion = false; // var to handle ref status only once
// byte compOn = 0;
// byte pascomOn = 0; //to chek if the variable has updated.
// unsigned long  comOnTime  = 0;
// unsigend long  comOnDelay = 1500;
// unsigend long  comOnCT    = 0;     //the current time of the compressor.

//------for debug only
//Serial.print("comOnCT  =             "); Serial.println(comOnCT);
//Serial.print("comOnCT - millis()  =  "); Serial.println(millis() - comOnTime );

// Serial.println("INICIANDO REFRIGERACION");

if(refrigerationBegin == true )
{

if(refrigerattion == true && millis()- comOnTime  >= comOnDelay ){
   compOn ++;
   comOnTime = millis();
 /*
 //--------for debug only
 Serial.println("---------------------");
 Serial.print("Var compOn "); Serial.println(compOn);
 Serial.print("comoON  "); Serial.println(compOn);
 Serial.print("pascomON"); Serial.println(pascomOn);
 Serial.println("---------------------");
*/
}

if(compOn > pascomOn ){

  switch(compOn){

  case(1):
  lcd.setCursor(0,0);  lcd.print(F("      CICLO DE      "));
  lcd.setCursor(0,1);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  break;

  case(2):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 1       "));
  digitalWrite(dif1, LOW);
  break;

  case(3):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 2       "));
  digitalWrite(dif2, LOW);
  break;

  case(4):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      SOLENOIDE     "));
  digitalWrite(solenoid, LOW);
  break;

  case(5):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      COMPRESOR     "));
  digitalWrite(compressor, LOW);
  break;

  case(6):
  lcd.setCursor(0,1);  lcd.print(F("                    "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  refrigerattion = false;
  refOff = true     ;       // to cycle only once the set of the instructions per cycle.
  compOn = 0;
  cycleFansvar = false;        //bool to chek the refrigerattion has stop
  //--------------------------------
  //refrigerattion = true; add this variable at the end of the off routine to cycle the
  //operation otherwise will just start once
}
}
}

refrigerationBegin = false;
}

void turnOnCompressor(){

/*
This subrutine is intended to stop the refrigeration cycle
in the most ordered way, and keeping the refrigerant on
the high side of the system.
*/

// boolean refrigerattion = false; // var to handle ref status only once
// byte compOn = 0;
// byte pascomOn = 0; //to chek if the variable has updated.
// unsigned long  comOnTime  = 0;
// unsigend long  comOnDelay = 1500;
// unsigend long  comOnCT    = 0;     //the current time of the compressor.

//------for debug only
//Serial.print("comOnCT  =             "); Serial.println(comOnCT);
//Serial.print("comOnCT - millis()  =  "); Serial.println(millis() - comOnTime );

// Serial.println("INICIANDO REFRIGERACION");

if(refrigerationBegin == true )
{

if(refrigerattion == true && millis()- comOnTime  >= comOnDelay ){
   compOn ++;
   comOnTime = millis();
 /*
 //--------for debug only
 Serial.println("---------------------");
 Serial.print("Var compOn "); Serial.println(compOn);
 Serial.print("comoON  "); Serial.println(compOn);
 Serial.print("pascomON"); Serial.println(pascomOn);
 Serial.println("---------------------");
*/
}

if(compOn > pascomOn ){

  switch(compOn){

  case(1):
  lcd.setCursor(0,0);  lcd.print(F("      CICLO DE      "));
  lcd.setCursor(0,1);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  break;

  case(2):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 1       "));
  digitalWrite(dif1, LOW);
  break;

  case(3):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 2       "));
  digitalWrite(dif2, LOW);
  break;

  case(4):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      SOLENOIDE     "));
  digitalWrite(solenoid, LOW);
  break;

  case(5):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      COMPRESOR     "));
  digitalWrite(compressor, LOW);
  break;

  case(6):
  lcd.setCursor(0,1);  lcd.print(F("                    "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  refrigerattion = false;
  refOff = true     ;       // to cycle only once the set of the instructions per cycle.
  compOn = 0;
  cycleFansvar = false;        //bool to chek the refrigerattion has stop
  //--------------------------------
  //refrigerattion = true; add this variable at the end of the off routine to cycle the
  //operation otherwise will just start once
}
}
}

refrigerationBegin = false;
}

Sorry for the horrible indentation... this thing paste like thath

Nope, you can use block controls to paste code correctly. I've cleaned up a bit the formatting, you can finish it up and add proper indentation.

I suggest you write (indented!) a simple representation of what you would like to do (the algorithm) in plain English.

Try to avoid complex test cases inside "if" tests, especially if they can have side effects and if you do use complex conditions, check that the operator precedence meets your expectations. But I would advise to avoid complex tests altogether.

Sorry the first time un here... Yes... Is a sistem drive by temperature.... The one secon to add switch statement... For say..  Tunr one fan then wait a second. . turn another fan... Wait a second. Turn compressor on.

The idea us simple... Yet challenguing to me ... If the temperature is 7 or higuer start refrigeración... If its 3 or lower .. Stop refrigerattion...if.. The temperature is un between. Start ventilation Machine..

Problems arises when... The  state Machine dont complete its tasks... So the variables arent initiated and for say.... Refrigerattion wont start again... - sad sad very sad case

Please edit your main post and put there the description. Btw why do you place all those dots? It makes reading harder.

The posted code is driven only by the refrigerationBegin, refrigerattion comOnTime  comOnDelay, variables, and the millis().  There is nothing temperature sensitive in this code.   If you don't want a prematurely terminated start or stop cycle, you might need to insert a "compOn  ==0" or "compOn ==6" test into the hidden code to prevent that from happening.

Sorry... The programa has a thermostar función thath stop and star refrigerattion according the temp. I dont post it because the whole code is too big.

Are you trying to control by temperature or by time?
(I'm finding the code hard to follow. There seem to be 2 copies of it, and the comments in turnOnCompressor() seem to contradict the function name. I also don't see any code that mentions temperature.)
If this is temperature controlled, you need a dead-band - a temperature range bounded by a high- and a low setpoint. If you have a single setpoint, the system will jitter as air-circulation and electrical noise make the temperature appear to alternate above and below setpoint. The turn-on setpoint needs to be higher than the turn-off setpoint. You'll need to experiment to find out how far apart they need to be for the system to be stable.


text:
Reset Arduino Uno R3 from Serial when it freezes (stops looping)?
I have an Uno that loops processing serial commands and reading from a DHT11 sensor. For whatever reason, the device often stops responding. I put an LED on a pin and gave it a blink to see whether the loop is running, and sure enough the loop() stops running (the LED stays ON or OFF, depending on when it froze). I enabled the watchdog at 2 seconds, but it does not reset the device [it still stays frozen, even though wdt_reset() is called at basically the same time as the blinking LED is toggled].
I then tried various combinations of BaudRate=1200 (or 9600), Open(), Close(), DtrEnable=true [on both the Uno and the Mega], yet none of the combinations would make the device reset. The device will reset, however, if I re-upload the sketch using the Arduino IDE. I would like to emulate this resetting functionality from my own program's code. Reading on the official site, it sounds like the Baud=1200 reset feature is available only on certain models (not the Uno or Mega).
My code is by no means simple as I am no beginner when it comes to programming. This is the first time, however, that I have had a finicky unit that freezes all the time (say between 10 minutes and 2 hours into running). I merely want to reset the unit from the PC using code, like the Arduino IDE does. On the other hand, if the watchdog worked correctly, that would be fine as well. At the same time, I am not that experienced with electronic circuits, so making a circuit that would "press" the "reset" pin when the LED stops blinking is not something I am quite ready to do. Plus, I do not want to add a bunch more components if the job can be done through code.
On a side note, the Serial connection appears to be fully functional the whole time. The LED on the unit that indicates receiving from the PC continues to function whenever I send data to the device. I can connect and reconnect without any apparent issues. Plus, the Arduino IDE has no problem uploading new sketches and resetting the device. Naturally, no data is received from the device after it freezes (until it gets reset, of course).
Update 1: I made a simple sketch (see below) that would run for about 20 seconds and then let the WDT watchdog timeout do its thing. Result:
(a) Running the code on an Arduino-brand Mega 2560, the device simply resets every 20 seconds and keeps blinking;
(b) Running the code on a generic (made in China) Uno R3, at timeout the L light turns on and the device becomes completely unresponsive (not even the reset button or the Arduino IDE can save it); It must be unplugged to reset it.
(c) Running the code on an Arduino-brand Uno R3 works as expected, just like on the Mega 2560.
#include <avr/wdt.h>
void setup() {
  wdt_reset();
  wdt_enable(WDTO_2S);
  wdt_reset();
  pinMode(A5, OUTPUT);
  delay(1);
  Serial.begin(125000);
}
unsigned int LoopCount = 0;
bool TestLED = false;
void loop() {
  if(LoopCount % 300 == 0){
    TestLED = !TestLED;
    digitalWrite(A5, TestLED ? HIGH:LOW);
    if(LoopCount < 20000)
      wdt_reset();
  }
  delayMicroseconds(1000);
  LoopCount++;
}

Nevertheless, I still would like if someone could provide a solution in terms of resetting a frozen generic Uno from Serial in .NET code -- not the WDT frozen, but the normal frozen (of unknown origin). I may be the one coding, but I'm unfortunately not the one deciding which units are put into production.
Update 2: I switched the EasyDriver to its own power source, where the only things in common with the stepper and the Arduino were the ground and the two signal wires. The generic Uno board ended up being even more problematic, going into a new freeze mode (after just a minute or two, pretty reliably) where the L light would blink very quickly. I'm not sure whether it had anything to do with toggling of the DtrEnable property, but I decided to stop messing with the generic board for the time being. The name-brand Uno appeared to freeze occasionally or malfunction as well with the original wiring, but the Watchdog did its thing and reset it straight away every time. Also, I tried toggling the RtsEnable property with the generic board, but it didn't seem to make a difference. The board would become unresponsive and unrevivable, even from the Arduino IDE.
Some more background: The reliability problem only really started to surface when I hooked up the DHT11 temperature sensor, even though the freezing would tend to happen only when the stepper motor was running. I have the DHT11 hooked up exactly as advocated by Adafruit, and it tends to read correctly most of the time.
Update 3: I was thinking maybe the SainSmart Mega2560 would be different from the no-name generic I was using. After getting one and hooking it up, I have found it to have the exact same problem. The SainSmart CPU crashes between 5 and 15 minutes into running. The serial chip (or module) keeps going as you can still see the serial lights change when you send to it. However, the on-board reset button does nothing, and the Arduino IDE cannot upload to the device or reset it. Only a power cycle can save it.

Uno resets whenever a serial connection is established (which is how the IDE is able to reset it to re-upload your sketch). Disconnect/reconnecting your serial terminal should cause the same reset. It's very strange that the WDT doesn't reset it, though.

Agree with @JRobert - I've never seen a case where the WDT didn't reset the chip except when the chip was permanently fryed. Are you sure you are correctly enabling the WDT and not setting it to interrupt only mode? Posting code would help.
The Arduino IDE resets the board by toggling the DTR line on the serial connection. This in turn pulls the RESET pin on the chip low long enough to reset the chip. But if the chip if can reset via the RESET pin, then it almost certainly should also reset on a WDT timeout.

I probably ought to have mentioned that by serial, I meant USB / virtual serial port. Maybe I was mistaking, but I thought the same software commands that work via a conventional serial connection would also work through USB.

@bigjosh -- the chip still works. I've had it freeze several times. It doesn't freeze when it's just sitting there blinking. It's when I run a stepper motor for a while (like 20 minutes). There's a possibility that it's electrical in nature, which may mean that the CPU is crashing, but nevertheless the Arduino IDE can reset the device when it freezes like this. When you say "toggling the DTR", what do you mean from a coding perspective? I'm currently working with the SerialPort class in .NET. I'll see if I can reset the device under a non-crash condition using the WDT.

Try the .NET SerialPort.DtrEnable Property to toggle the DTR.

Stepper motors crash lots of Arduinos! They make lots of inductive noise and pull lots of power. Try connecting the motors and the motor drivers to a completely different power supply that the arduino. Also try filtering any communications lines between the Arduino and the motor drivers. But even though the crashing is caused by motor induced glitches, the WDT should still bring it back to life. Post your WDT enabling code and we will take a look.

Yeah, the SerialPort.DtrEnable property is exactly what I was playing with. I tried setting it before and after opening the port. I tried having a one second delay and having none between turning the property On and then Off (true and then false). I didn't try anything crazy though, like toggling it back and forth a bunch of times. Maybe it's the generic Uno acting up, or maybe there's something tricky about doing it from .NET. As for steppers, I'm using an EasyDriver, but indeed the motor is running on the same power as the Arduino. I've posted an update on my main question.

You really need to understand and fix the root cause, be it software or electrical issues.  It is possible you need to drive RTS rather than DTR to reset this particular board (the IDE may drive both).  It is also possible that an electrical fault or merely noise is causing the USB chip to be re-enumerated and re-opening the serial port is a key part of getting it talking again.

@Chris -- I used to think like that, but then I came to see that it's a very good idea to have systems be fault-tolerant. Trying to prevent every type of problem is often too costly (both in time and equipment) for basic (non-critical) applications. I would actually rather make a system successfully fault-tolerant first and then focus on getting the glitches out. From what I've heard, Google also chose this approach with their search system's network (cheap parts, high fault-tolerance). I agree that finding the problems is well and good, but I think that fault-tolerance should come first.

@Michael - recovery mechanisms are great, as long as you disable them when testing in order to find out if you have a problem.  This system has known flaws likely due to basic design oversights, and those really need to be fixed, not hidden.

You can reset the Uno over the serial link by toggling the DTR line. How you do that depends on what platform and language you are using. There is a capacitor between the line and the reset pin, so the toggle must last a minimum ammount of time. 0.5 seconds works.
This is ok for just a quick fix hack, but probably better in the long run to (1) figure out why the code is crashing, and/or (2) figure out why WDT is not working.

I just tried it, and indeed, simply doing [(1) SerialPort.DtrEnable = true; (2) Sleep(1000); (3) SerialPort.DtrEnable = false;] is enough to make it restart an official Arduino Uno R3 via .NET code. I guess the problem is that this particular generic version doesn't respond the same as the name-brand edition. Presumably this is a feature that sometimes doesn't get tested. At the same time, I haven't had the official one freeze yet in this setup, so I cannot say whether it would reset the same after freezing.

Since we don't know the nature of the freeze-up, and the clone-board behaves differently than an Arduino-brand board but we don't know how or why, there's not much more we can offer beyond suggesting you recommend a higher quality board to your management. You surely have reason enough to do so.
The last remaining thing I can think of, and it's kludgey work-around (shame on me) is:
You know the board will come back after a power-cycle. Kludge up a 555 timer circuit that powers-down the board for a second or two, and trigger it from the DTR line. This is really a broken fix for a broken board!
If my management or a client was intent on shipping a product built with these, I'd have to speak up about potential damage to the company's reputation - and possible liability, if a failure could have real consequences someone - and if necessary, write my objections to the next three levels above me. This board should not be shipped in a product.

Agreed. I did actually pass on the suggestion that the board probably isn't appropriate for this application. Thanks for the extra input.


text:
Can I use 5V 1A Adapter to power Arduino UNO?
I have two Adapters, one is rated as Output 12V 500mA (used to power an old modem) and another one is rated as 5V 1A (old mobile phone charger).
My question is can use any of these to power my Arduino UNO with a barrel connector?
What does it mean when any adapter is rated as Output DC 5V 1A, Does it mean maximum we can draw 1A of current through it? What will happen if I draw more current than that.

You can't draw more than 1A, thats adapter specification maximum.

You can use a clean 5v supply through the USB connector, but not through the barrel jack.  The 12v supply would probably work (if it is DC) through the barrel jack but the regulator may get hot - something around 8v is better there.

An Arduino will not consume 1A of current, far from it, it will use less than 0.1 A of current even with a couple of LEDs lighting up. So don't worry about the current rating of the adapters, it is OK. The Arduino will only take as much current as it needs.

I'm guessing your other adapter is 500mA, not 500A.

The answers are here.

As I mentioned 5V adapter is actually a LG mobile charger - Do I assume that it can supply clean 5V? How do I know it is clean 5V or not? I measured it gives 5.0V  @ChrisStratton

If we look at technical specifications, it is recommended to supply voltage from 7-12V so use your adapter 12V/500mA (never go above 20V). 5V/1A adapter is not enough when connecting via DC barrel jack according to technical specifications.

And that is valid if you use the DC jack on your Arduino board. You can make the Arduino work on the 5V/1A adapter but then you need to connect it directly to a +5V connection or a USB input (these are also 5 V).

Since the arduino only draws a few mA, the unloaded voltage on the power supply might be considerably higher. It depends on the quality of the supply. It is probably a good idea to measure the unloaded output voltage before connecting it directly to the board.

What does it mean by measuring unloaded output voltage? Does it mean measuring voltage without connecting it through any device? If so, I've measured - it is perfectly 5.0V

@palash it means that power supplies or regulators are rated to give out let's say 5V, but it is only guaranteed when you draw at least a certain amount of current. If there is no draw, the (unloaded) voltage may be higher.


text:
ATtiny85 SPI with Timer 0
Trying to shift out from ATtiny85 to a shift register using the USI in SPI mode. I have Timer 0 running as slowly as possible (checked it was running by temporarily changing it to toggle a pin with an LED attached.) I have LEDs hooked up to USCK and DO so by rights I should be able to see them blinking as it sends.
What else do I need to do in order to get it shifting out in sync with Timer 0? All the examples I've looked at so far strobe the USI clock manually.
#include <avr/io.h>

int main(void){
    DDRB = (1 << DDB2) | (1 << DDB1); // USCK & DO Output
    DDRB &= ~(1 << DDB0); // DI Input
    PORTB |= (1 << DDB0); // Pullup Resistor for DI

    TCCR0A = (1 << WGM01); // Timer 0 in CTC Mode
    OCR0A = 0xFF; // Timer 0 Compare A
    TCCR0B = (1 << CS02) | (1 << CS00); // Prescaler / 1024

    USICR = (1 << USIWM0); // USI 3 Wire Mode
    USICR |= (1 << USICS0); // Timer 0 for USI 4-bit Clock Source

    USIDR = 0x7F; // Why you no go? :c

    USISR |= 0x08; // Set Counter to 8
    USISR = (1 << USIOIF); // Clear Counter Overflow

    while(1);
    return 0;
}

I think it should be: USISR = _BV(USIOIF);

This is a good question, but not related to Arduino. I think you could re-ask it on Electric Engineering stack exchange.

"This flag is set (one) when the 4-bit counter overflows (i.e., at the transition from 15 to 0). If the USIOIE bit in USICR and the Global Interrupt Enable Flag are set an interrupt will also be generated when the flag is set. The flag will only be cleared if a one is written to the USIOIF bit. Clearing this bit will release the counter overflow hold of SCL in two-wire mode."
So it's set when it overflows and you clear it by setting it? What the f- Atmel. :I

Yepp, you have to think as the hardware guys do :)

Still doesn't work. :c I've resorted to strobing it manually for now.

Did you forget to load the counter and clear flags in USISR?

It still isn't doing anything (updated code snippet.)


text:
Measuring acceleration in g's
I am using adxl335 accelerometer with Arduino uno r3 to measure acceleration due to gravity along x axis. I am using 50 ms delay and printing to serial.
I have two questions, which are;

Can I measure fractional values, like .8 in acceleration due to gravity?
when I shake the accelerometer up down along x axis, I don't see any variations in 'g'?

I am using analog pins and 3.3V power supply from Arduino to power the sensor.

If you read the datasheet you can quickly find that the output of the device is 300mV per g.  That means:

Read the analog value
Convert it to millivolts
Divide it by 300

The result is the g value.  If you do it using floating point then yes, you get fractions of a g resolution.
For instance:
float mv = analogRead(0) / 1023.0 * 5000.0;
float g = mv / 300.0;

If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step.  Divide that by 300 and you get a resolution of 0.01628g
As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down.  It's all in the datasheet - it makes for good reading, I suggest you take a look.

Thank you very much, it worked, I looked at the data sheet but it turned out to be that I was directly dividing the analogRead by 300. As for the variation in g it turns out that I wasn't shaking too hard and the code was wrong. Thanks again


text:
How can I use arduino board for AC mains?
I want to use LDR to control a light bulb (12W) which runs on AC supply using Arduino.
Is it possible to do this?
If yes, how?

Yes, with a relay. Ask google, it knows how.

Try the PowerSwitch Tail II.
This is suitable if you are living in the USA (120VAC power).
You will find 240VAC versions as a kit on that web page as well.

The quick and dirty answer is that you need something that will safely handle the mains voltage that you can control with the Arduino (which is running at 5 (or 3.3) volts). There are two issues you need to consider:

Safety – keeping the mains voltage separate from the Arduino and the other low voltage components so that nobody gets hurt.
Capability of components – avoiding damage to the Arduino and related components due to the mains voltage.

A common way of achieving the second goal is with either a relay or a solid-state component like a triac.
The first goal is often accomplished by using an optocoupler – a device that isolates the low-voltage circuitry from the higher mains voltage by means of an LED and a photo transistor in a common housing.
The circuitry around the relay and optocoupler aren't all that complicated but it isn't trivial either. You might look on e-bay – a search for "arduino relay" will find you lots of modules that will do the job for you.

You can use a relay shield like these:
Relay Boards - eBay
Be sure to check the amp draw of the relays. Sometimes you need a transistor, but I don't think you should for these shields. Just be careful working with mains voltage.

If you want to switch it on/off, there is a simple solution using a relay and an optocupler (safer option) or transistor. Here is a schematic:

but if you want to control intensity of light, then you have to use triac control, which you have explained here: AC Phase Control.


text:
Suggest some ways to communicate (Rx and Tx) between Arduino and LabVIEW through Internet

Suggest Hardwares to use and also suggest some place to learn about
IoT, video tutorials, websites, blogs, books etc.
Currently I am using Xbees to communicate between LabVIEW and Arduino Mega.
Most of the websites that I checked are using ESP8266 but I am not
sure how to use them to receive and transmit simultaneously.

What type of protocols do you want to run? What is the required bandwidth (message per second, avg message size)? Response time? This could be control algorithm inner time, etc. These types of questions (requirements) need to be answered first before approaching an architecture, design and implementation. You are skipping directly to the implementation.

I am sending 54 bytes and receiving 18 bytes of data. I want response time to be as minimum as possible, which I think would depend on the internet speed. I am not sure about other things. How would you tackle this problem ? I am asking you to answer your own question :P sorry. I am a newbie.

Would it work if the round trip of messages is approx. 10-20 ms with a worst case delay of 250 ms? How would the application (LabView/Bot) react? I am assuming that you wish use a WiFi Router. The "Internet Speed" or bit-rate has very little to do with the actual bandwidth as using using WiFi/TCP/IP may require retransmission, etc. If you have requirements of lower than 1 ms it all becomes much more difficult (expensive :).


text:
Arduino UNO inconsistent I2C register reading from ArduCam
I have an Arducam hooked up to an Arduino UNO.  The code I am running looks like this:
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"

const int CS = 10;

ArduCAM myCAM(OV5642, CS);

void setup() {
  uint8_t vid, pid;

  Wire.begin();
  Serial.begin(115200);
  pinMode(CS, OUTPUT);

  SPI.begin();

  //Check if the camera module type is OV5642
  myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
  myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);

  if ((vid != 0x56) || (pid != 0x42))
    Serial.println("Can't find OV5642 module!");
  else
    Serial.println("OV5642 detected.");

...

and the rdSensorReg16_8 function from the library:
//I2C Write 8bit address, 16bit data
byte ArduCAM::wrSensorReg8_16(int regID, int regDat)
{
    Wire.beginTransmission(sensor_addr >> 1);
    Wire.write(regID & 0x00FF);

    Wire.write(regDat >> 8);            // sends data byte, MSB first
    Wire.write(regDat & 0x00FF);

    if(Wire.endTransmission())
    {
        return 0;
    }

    delay(1);
    return(1);
}

The problem I am experiencing is that sometimes I will receive the "Can't find OV5642 module!" message, and other times everything is fine and I receive "OV5642 detected" (I have the OV5642 module hooked up, so it should always be returning detected).
I have tried using different cables to connect the camera to my UNO.  I have tried swapping out my USB cable.  I have tried using a 12v wall adapter to power the UNO. None of these options permanently solved my problem - I still receive both messages interchangeably.
One thing that seems like it is adding consistency is when I change which USB port on my computer the cable is plugged into.  Every time I switch the USB port I am using, it seems like for the first run I'll receive the successful "OV5642 detected" message, but after reseting the Arduino or re-uploading my sketch, I go back to the "Can't find OV5642 module!" message.
Can anyone help me troubleshoot why I am getting inconsistent readings?  Thank you.

Same problem here. It seems like if you reset the camera (plug it out and in again) it works again. I don't know why, I also tried it with a Raspberry Pi, and I didn't have this problem (however I had other problems!).

I would start by adding a short delay before SPI.begin() and verifying that the power drawn does not exceed 500 mA.
The product description describes the power on sequence. OV5642

Thanks for the suggestion Mikael.  I added a delay and verified the power, but I am still experiencing the same issues.

Ok. Let us assume a hardware issue. Pull-up resistors on I2C wires? Might be integrated on the board. How are you connecting the device? Did you measure the power drawn? How much was it? Did the voltage drop?

Have you tried decoupling the power pins on the module? Just attach a 100uF or larger capacitor to the GND and power pins on the module.


text:
Best 2a stepper motor driver for Arduino Uno
What is the simplest (from a user/install standpoint) 2a stepper motor driver for an Arduino Uno?
I would like something simple and easy to stack like the Adafruit Motor/Stepper/Servo Shield for Arduino v2 Kit  but unfortunately it only handles 1.2a. I can do basic soldering but I would like to keep things simple and physically stacked or connected if possible. I don't want to use jumpers or a breadboard.
I am trying to run this stepper to simply open and close a door every few hours:
14:1 Planetary Gearbox High Torque Nema 17 Stepper
Using this battery from Amazon:
ExpertPower EXP1250 12V 5Ah
If I'm missing anything please let me know. Your feedback is appreciated.

While you can do it, this doesn't sound like an application for a stepper motor, but rather some sort of ordinary motor with a mechanical reduction and a limit switch.  If you want to go with this anyway, MOSFET bridges like the TB6612FNG on that Adafruit shield can theoretically be paralleled, but it may also be that setting a reduced current level below the motors rating would be fine for your needs.


text:
Multiple rgb control plus calculation help
Hi me and a friend is making a computer shelf with leds in the woodwork, were using a special glue for the plexiglass in the shelf which means we're using individual rgb leds, four leds for each window (3 windows) and what I need help with is, amount of voltage, ampere, code and how to connect all this up. I've used 123d.io to sketch something up but I'm struggling with getting proper strength in the leds.

(code https://puu.sh/lI6PC/e214028b07.txt)
Aswell as some of them change colors as the picture here shows:

I'm very new at these things so I really appreciate all help and advice (and from an earlier post, reason for not using strips is purely based on the method of build, the shelf will not sit correct if the strips were in use)

What do you mean by proper strength in the leds. The second image seems to indicate you are running the leds at only 1mA. 20mA is generally the current to run an led at, to get maximum brightness.

Also using 12v as a supply is way more that what's needed, resulting in more losses.

How do I calculate to get which voltage is needed, I thought it was just mostly multiplying 3V per led then sum it up and done deal, but as I've seen it's completely wrong so how big is the needed powersupply?

That what you need to do if you connect them in series, but you are connecting them in parallel. So you need a voltage higher that the forward voltage of the blue led, which is about 3.2V. You need about 720mA when you turn on every led (at 20mA).

It's not advised to connect leds in parallel, with only one common resistor. Slight difference in forward voltage of the leds will create big current differences. This will make some leds appear brighter that neighboring leds. It can also damage the brighter led since too much current can flow through them. So you need to add a resistor to each led, and common the other side of these resistors to the transistor.
Second bigger error is that there isn't any resistor between the arduino pin and the base of the transistor. Without it there is nothing limiting the current going into the base, which could fry the arduino pin.

Thank you, I'll add that :) is the ones I'm using decent (270ohm)

270 will work, but isn't ideal. I'd use something like 2k. Lower values will be less efficient, and make the transistor run hotter. You could put a few 270 resistors in series to create a higher value resistance.

There's a lot to unpack here, this is actually several questions.
First of all, the way your circuit is designed currently, your data pins are connected via the transistors to ground. This means if you set a pin high, or use analogWrite(), the Arduino will pump as much current as it can get, directly into the ground. This can damage the Arduino. Put a resistor between the pin, and the transistor.
The first point is that you are using several LEDs. If you want to control them separately, you will need 3 pins per colour. AnalogWrite() only works on PWM pins - if you look at your Uno, you can see that some of the pins are marked with a ~ (pin 3,45,6,9,10,11) - these are the only ones you can (easily) use. Since there are 6 of them, you could only run 2 LEDs this way. You could either run the project on multiple arduinos (1 Arduino per 2 "windows"), or you can get a chip to do the heavy lifting for you. I am working on a similar project, and am using a TLC5940 - there is a thorough tutorial at http://playground.arduino.cc/Learning/TLC5940 - they also save you from having all the resistors and transistors, and each TLC5940 will run up to 16 LED-pins (3 per LED, so you can run up to 5 "windows"). They are also designed to daisy chain, so if you need more, you can just add another chip; no extra Arduino pins to worry about. 3 of them can run all 12 of your LEDs independently.
The next item to be aware of is that there is a limit to how much power (in Amps, or milliAmps) you can draw from a given power source. Each part will use a certain number of millAmps. The spec sheet for your parts should tell you how many. LEDs are generally around 20mA (per colour), but this varies - check the datasheet. An Arduino uses about 50mA. This means that if all 12 of your LEDs are bright white, you will be drawing 50mA+(20mA * 12 * 3) = 770mA.
How does this affect you? Well, if your project draws less than the power source can provide, you're golden! You can't provide "too much current" to a component - it will draw what it needs. When you draw more than the supply can supply, you get one of two results. If it runs on the mains, it will overheat, and eventually either burn out, or catch fire (there are exceptions to this, but you'd better be sure of your facts before risking it!). How long this takes, depends on how much current you are drawing, and how much margin there is on the power supply. In the case of a battery, the battery will drop in voltage, and will also heat up (but is much less likely to catch fire). I suspect this is happening here. If you have a multimeter, you can hook up your circuit to batteries, and then measure the voltage between + and - on the batteries.
P.S - +1 to @Gerben - you need one resistor per LED leg (except common). If you use the TLC5940, you would need 3 TLC5940s; as I said before, you can daisy-chain them. This does, however, mean that you can control each LED individually.


text:
Interfacing Arduino with matplotlib animation
I've also asked this question over on stack exchange so I'll link the actual question here.
The short story is I have a plot that updates in real time from data collected on an Arduino. The plot updates on a 50ms + overhead interval and I can either choose on the Arduino side to either delay the loop 50ms + compensation or use flush(). I'm running into some problems with the delay option where my program begins to lag (Python side). I'm wondering if flush will work as I expect and hold the output until my python program reads from the serial port. So then the Python program is completely controlling the flow of data every time it polls for an update.
Edit: Here's a snippet of the code.
void loop() {
  // put your main code here, to run repeatedly:
  val1 = analogRead(0);
  val2 = analogRead(1);
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  //Serial.flush();
  delay(50);
}

Please post a snippet of the Arduino side of the code. It should not send data faster than every 50 ms.

I edited my post to add the snippet

Thanks! You can test this: Reduce the update speed and verify the lag. When you get no lag. Increase the number of samples written. Typically python does not read the serial port directly. It goes through the operating system. There is also buffering going on in the python serial module and on top of that there is the garbage collector. You can help the python side by using a lower update rate but still keep the sample rate on the Arduino side.

What serial speed are you using - is 50ms enough time to transmit all the data?  If you're using slow serial, maybe just transferring the data is taking too long.

Uh... answered over there, copied below.

Please do not cross post questions as it leads to duplication or effort.  I have flagged the question on SE SO for deletion.

On the Arduino side, flush simply waits until the last byte has been fully transmitted.  It says nothing about how quickly it is being read by the PC.
The general problem you are having is called "flow control".  It has been solved with many different techniques, like "handshaking".  For example, the PC could send a character when it has received the last byte of a data set (a line, as returned by readline):
line = self.ser.readline()
self.ser.write("!"); // Tell Arduino line was received
line = line.split()

While the PC proceeds to parse the line, the Arduino will eventually receive the handshake character:
void loop()
{
  // Send a line
  Serial.println( ... );

  // Wait for handshake character
  bool gotHandshake;
  do {
    while (!Serial.available())
      ; // wait for chars
    char c = Serial.read();
    gotHandshake = (c == '!');
  } while (!gotHandshake);
}

Then the Arduino can proceed to send the next data set (i.e., a line).  The OS on the PC will buffer characters from the Arduino until the python program receives them with readline and sends another handshake character.  No delay required.


text:
Read gyro output values with other programming languages
I have a large quantity of gyro values and I read them through the Arduino serial monitor. I'd like to know how I can use these values in other programming languages (such as C/C++/Java) after the values are read. Are there particular  libraries for the Arduino that could help me in this way?

See http://arduino.stackexchange.com/questions/1850/how-can-i-reset-the-program-on-an-arduino-uno-while-the-device-isnt-recognised?rq=1. Seems to be much that same issue.

If your Arduino sketch is printing the data as ASCII numeric strings (human-readable), then any language with support for reading and writing to a serial device can interact with your Arduino on the port it is connected to, and collect the gyro data as it is being sent.

Yes, of course you can.
In C/C++ there are different libraries depending on your operating system - that is if you even really need a library to help you at all (in Linux you certainly don't - you just use standard system calls - open, read, etc).
In Java there are a few different ones.  RXTX is a common (though not very good) one.  Personally I ise JSSC(Java Simple Serial Connector) since it contains the JNI files for all the main platforms - you don't have to get the right separate library packages for your specific OS like you do with RXTX.
Then of course there's things like PySerial for Python, Device::SerialPort for Perl, and whatever nonsense Microsoft have created for C# and their .NET stuff.
So in general: pick a language you are comfortable with, then ask Google how to use the serial port in it.


text:
One LED being constant and another blinking
I have just started my first project. I got through with 2 periodically blinking LEDs. Now I want one LED (blue) to be lit constantly and the other (red) to be blinking as before. Can anyone help me with this?
This is my code for blinking LEDs.
int red_led = 4;
int blue_led = 3;

void setup() {

  pinMode(red_led, OUTPUT);

  pinMode(blue_led, OUTPUT);

}

void loop() {

  digitalWrite(blue_led, LOW);

  digitalWrite(red_led, HIGH);

  delay(1000);

  digitalWrite(blue_led, HIGH);

  digitalWrite(red_led, LOW);

  delay(1000);

 }

So you do not want one of your LEDs to turn off?  The answer will depend on how your LEDs are wired.

Why are you even setting the blue LED low then?

What had you tried before posting the question? Did you at all understand the code you posted above?

The wonderful thing about the Arduino is that it hides a lot of the programming "noise" and lets you concentrate on the code that is actually doing the work. Part of the joy of programming is starting to "own" the code and being able to make it do what you want.
The answer here isn't too hard, and I'm sure that many could answer your question – but I think you might enjoy the experience more (and you would earn more respect) if you make a stab at it yourself first. Or if you already have, tell us what you've tried and what happened when you tried it. That will help us help you to see not only the steps necessary, but the concepts that will enable you to branch off on your own.
Do you know what is causing the LEDs to blink in your current code?

The LEDs get forward-biased with positive supply at anode and ground at cathode: that makes them getting lit. In the code, the infinite loop forces the consecutive LEDs to glow for 1000ms and then going to "off" state for 1000ms.

So, if you move the blue_led control out of the infinite loop() and into setup() you get what you want.

Remember that the setup() function runs once, and then the loop() function runs forever.  So to keep the blue LED light, simply turn it on, but never off.  The code for the red LED remains unchanged.
const int red_led  = 4;
const int blue_led = 3;

void setup()
{
    pinMode(red_led, OUTPUT);
    pinMode(blue_led, OUTPUT);

    digitalWrite(blue_led, HIGH);  // LED On
}

void loop()
{
    digitalWrite(red_led, HIGH);  // LED On
    delay(1000);
    digitalWrite(red_led, LOW);   // LED Off
    delay(1000);
}