text:
Splitting the power source between an arduino and a servo
I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?
Do I have to take some safety for the Aduino in concern or could I just split the wire?

Is your power supply 5V regulated?

It is a supply that is used to load a tablet, an AC/DC adapter. How do I know if it is regulated?

I think 500mA would be a more accurate rating. That is the rating of the fuse on the board. I don't know where you got the 100mA from?

Actually my question rather was: do your power supply output 5V or more than 5V? If it is 5V, it is likely to be regulated. A second question is where do you plug it to your Arduino (USB, power jack, Vin, 5V)?

If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.
If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).

"Do not go above 12V or you may destroy the voltage regulator on the board" I don't agree with this. First of all it depends on the board. Then, if we take the UNO as example, if you are you trying to get 800mA from the 5V rail nything above 7.5-8V will cause problems. If OTOH you are you trying to power only a 20mA LED even 20V is fine. Saying that the limit is 12V is correct in a limited amount of cases (max current ess than 200mA)

There is a page with information about the current limits of Arduino pins.  There's also a question on the Electrical Engineering SE site that addresses the current limits of the board overall.
From the accepted answer on that question:

The 5V output pin is good for ~400 mA on USB, ~900 mA when using an external power adapter

So that's more than the 100 mA you mentioned in your question.  (But go read the whole answer; there's more good info there.)
The easiest way to split the power is to use a separate, regulated power supply.
Except for simple tests (e.g., a single small unloaded servo), I use the digital i/o pins only for very low current signals:  buttons, status LEDs, sensors, serial communication, etc.
For example, to control an IR LED that can handle up to 50 mA, I'll supply power to the LED from the Arduino board's Vcc pin and control it with a transistor attached to a digital output pin.  Drawing 50 mA from the board's supply is well under the limit, and the digital output pin draws practically nothing.
For more than one servo, I use a peripheral PWM controller that takes power separately.  That peripheral is powered by a separate 5V 2A power adapter, which supplies the current to actually turn the motors.  I send commands to the controller using I2C from the Arduino, which is running from its own power supply.

Please note that "can source 200 mA (milliamps) from the Vcc pin" is NOT correct. That part comes from the datasheet of the microcontroller, and means that the maximum current that can flow inside the uC Vcc pin or outside the GND pin is 200mA. This means that the sum of all the currents sourced/sinked by the digital pins is 200mA (so 40mA for each pin, but max 200mA total). This is not for the Arduino +5V pin

@frarugi87:  Ah, I misunderstood.  Thanks for the clarification.  I'll try to incorporate that correction into this answer.


text:
lcd.print and 2D arrays
Click here to see my program running
I have created a 2D array (see my full code below), and each row contains one state of a battery here is  a schematic :
row [0] : "▯▢▢▷" // this row represents an empty AAA battery
row [1] : "▮▩▢▷"
row [2] : "▮▩▩▷"
row [3] : "▮▩▩ ▶"  // this row represents a Full AAA battery

Each "▩" character is a custom made character with this function:
lcd.createChar(0, customLcdfont_squareONE);

As you saw in my video it works at the end, but it's absolutely not the way I want it to work. The code that works is a mess!
I think the problem is that the Raw n°1 ([0]) starts with a 0, (try it out it's very strange). If we replace
char batteryFonts [10][5] = {
  { 0, 1, 1, 2 }, // you see { this "0", 1, 1, 2 }, is a problem I think
  { 3, 1, 1, 2 },
  {etc}, }
lcd.print( batteryFonts[0]);  // this sentence does not work

with
"char batteryFonts [10][5]={{ 4, 1, 1, 2 }, // 4 or what ever you want
  {etc},
  {etc}, }
 lcd.print( batteryFonts[0]);  // this sentence behind does work, but only with a row that does not start with a 0. Why?

It works!
Here is my full code. Just connect the pins 12, 13, 7, 4, 3, 2 to the LCD.
//This is a simple program that charges alkaline batteries
//Copyleft
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 13, 7, 4, 3, 2); // why pin 13 and not 12 ? because I love the led attached to it <3

// the empty battery - end
byte customLcdfont_A [8] = { // B stand for "Binary" and then the pixel ...
B01111,
B11000,
B10101,
B10100,
B10100,
B10100,
B11000,
B01111

// the empty battery body with fancy graphics enabled

};
byte customLcdfont_B [8] = { // B stand for "Binary" and then the pixel ...
B11111,
B00000,
B11001,
B00000,
B00000,
B00000,
B00000,
B11111
};

// the empty battery + end

byte customLcdfont_C [8] = { // B stand for "Binary" and then the pixel ...
B11100,
B00100,
B10111,
B00101,
B00111,
B00111,
B00100,
B11100
};

// the full battery - end

byte customLcdfont_D [8] = { // B stand for "Binary" and then the pixel ...
B1111,
B11111,
B10110,
B10111,
B10111,
B10111,
B11111,
B1111
};

// the FULL battery + end
byte customLcdfont_E [8] = { // B stand for "Binary" and then the pixel ...
B11100,
B11100,
B01111,
B11101,
B11111,
B11111,
B11100,
B11100
};

// the full battery  body

byte customLcdfont_F [8] = {
B11111,
B11111,
B00110,
B11111,
B11111,
B11111,
B11111,
B11111
};

// the 1/3 battery body

byte customLcdfont_G [8] = {
B11111,
B11000,
B00001,
B11000,
B11000,
B11000,
B11000,
B11111
};
// the 2/3 battery body

byte customLcdfont_H [8] = {
B11111,
B11110,
B00111,
B11110,
B11110,
B11110,
B11110,
B11111
};

/**************************************************************************/
void setup() {
  int i = 0 ;
  // initialize serial communications at 9600 bps:
  lcd.createChar(0, customLcdfont_A);
  lcd.createChar(1, customLcdfont_B);
  lcd.createChar(2, customLcdfont_C);
  lcd.createChar(3, customLcdfont_D);
  lcd.createChar(4, customLcdfont_E);
  lcd.createChar(5, customLcdfont_F);
  lcd.createChar(6, customLcdfont_G);
  lcd.createChar(7, customLcdfont_H);

  lcd.begin(16, 2);

// WATCH HERE IS THE PROBLEM !!!!

//the char table behind creates my different battery states as shown in the video ;)

 char batteryFonts [10][5]={

 { 0, 1, 1, 2 }, // this is an empty one  f%*# this does not work !!!
 { 3, 1, 1, 2 },
 { 3, 6, 1, 2 },
 { 3, 7, 1, 2 },// this is a 50 % full charged battery !

 { 3, 5, 1, 2 },
 { 3, 5, 6, 2 },
 { 3, 5, 7, 2 },
 { 3, 5, 5, 2 },
 { 3, 5, 5, 4 },// this is nice full one
 };

 // this sentence behind does not work !!! but only with the raw [0]

 lcd.print( batteryFonts[0]);    // I F***ing want this to display the first raw !!!!
 lcd.setCursor(0,1 );

  lcd.print(" not working ");
 lcd.setCursor(0,0 );

        delay(9300); // this make a short pause  for us so that we can see the result
lcd.setCursor(0,1 );

  lcd.print("    working      ");
 lcd.setCursor(0,0 );
      for (i=0; i=10 ; i+=1 ){
       delay(300);

  lcd.setCursor(6,0 );

  lcd.write(byte(0));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
    delay(700); //  batterry 0/8 empty aka discharged

  lcd.setCursor(6,0 );
  lcd.write(byte(3));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
    delay(1000); //batterry 1 /8

  lcd.setCursor(6,0 );
  lcd.write(byte(3));   lcd.write(byte(6)); lcd.write(byte(1)); lcd.write(byte(2));
   delay(1000);//batterry 2 /8

  lcd.setCursor(6,0 );
   lcd.write(byte(3));   lcd.write(byte(7)); lcd.write(byte(1)); lcd.write(byte(2)); //batery 3 /8

  delay(1000);

  lcd.setCursor(6,0 );
   lcd.write(byte(3));   lcd.write(byte(5)); lcd.write(byte(1)); lcd.write(byte(2));
  delay(1000); //batery 4 /8

  lcd.setCursor(6,0 );
        lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(6));   lcd.write(byte(2));
  delay(1000); //batery 5 /8

  lcd.setCursor(6,0 );
      lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(7));  lcd.write(byte(2));
        delay(1000); //batery 6 /8

  lcd.setCursor(6,0 );
      lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(5));  lcd.write(byte(2));
      delay(1000); //batery 7 /8

  lcd.setCursor(6,0 );
    lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(5));    lcd.write(byte(4)); //batery 8 /8

    delay(1000);

      }

    lcd.setCursor(15, 1);

    delay(115000);

}

/**************************************************************************/
void loop() {

//This is not interesting here
  lcd.print(" ~ The end of the code ... thank you for reading ;) ~ ");

}

You are correct; in C a NUL (0x00) is used to indicate the end of a char*. You will need to use LiquidCrystal::write() in order to send the character data byte by byte instead of depending on LiquidCrystal::print() to handle it.
Also, consider moving all of that static data into flash; you're going to need to handle it manually so you may as well do it right in the first place.

This confirms my doubs ! It's sloppy isn't it  ?
It's the same as in the C89 I studied, but slightly uncomfortable and I think the arduino  compiler should be updated to avoid this "issue"

It has nothing at all to do with the compiler. It is a fundamental tenet of C/C++, and LiquidCrystal::print() adheres to it.

Oh realy ? So I should study more !

I don't say thanks... as the comment box told me to avoid to say thanks (y) But I realy want to !

It's okay, your sentiment has reached me.

source: Stack Exchange

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

sort: votes


text:
How to prepare data structures and classes?
How can I port these structures to arduino ide, I also get error when I define pointers
// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';
  delete bar;
  delete[] baz;
  return 0;
}

In CPP shell it works
I try to put it like this
class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

I get an error
sketch_nov27a.ino:10:3: error: 'foo' does not name a type
sketch_nov27a.ino:11:3: error: 'bar' does not name a type
sketch_nov27a.ino:12:3: error: 'baz' does not name a type
Error compiling.

Should I lough or cry?

The problem is that the lines saying foo = ... etc. are assignment operations. C++ lets you declare and immediately initialise variables at global scope, but after that you can only assign to them inside a function. In your original program, all your declarations/assignments were inside main(), which is why it worked there.
For your Arduino program, you could change the assignments to initialisations instead (in global scope):
Rectangle obj (3, 4);
Rectangle * foo = &obj;
Rectangle * bar = new Rectangle (5, 6);
Rectangle * baz = new Rectangle[2] { {2,5}, {3,6} };

Alternatively, you could leave the declarations in global scope and move the assignments into setup():
Rectangle obj (3, 4);
Rectangle * foo, * bar, * baz;

void setup() {
    foo = &obj;
    bar = new Rectangle (5, 6);
    baz = new Rectangle[2] { {2,5}, {3,6} };
}

You put a bunch of code in a place where you can't have it. Move the assignments into a function body.

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


text:
Determine difference between 3.3V and 5V shields
How do you determine if an Arduino shield uses 3.3V or 5V on their pins?
Previously, I thought all Arduino shields used 5V, since that's what most  Arduinos use. However, I've been researching Arduino-compatible single-board computers like the PCDuino and Galileo, but these all seem to use 3.3V. More confusingly, they're vague about what types of Arduino shields they support. The PCDuino claims to only support 3.3V shields, but has an adapter shield to convert 5V. The Galileo has a jumper to support either 3.3V or 5V shields.
The main problem is how do you determine what voltage level Arduino shields use? I have a Seeedstudio motor shield and a Sain Smart sensor shield, and while they both take 5V power input, the docs don't mention anything about logic voltage level. How do I determine this?

Can you provide links to the doc's you're referring to? Maybe someone can look at those and see if the relevant info is there.

A 5v shield on a 3.3v arduino could fry the arduino. A 3.3v shield on a 5v Arduino could fry the chip(s) on the shield. Could, but not necessarily.

You read the schematics and datasheets. The former will tell you what power supplies are connected and how, and the latter will tell you what voltages are acceptable to the devices.


text:
Wiring 5V ultrasonic sensor to Arduino Due
Is it possible to use the 2760342 ultrasonic range sensor with an Arduino Due? The docs say it takes a 5V input, but doesn't specify the output, but I'm assuming it also outputs a 5V signal. Does this make it incompatible with the Due?
I've tested it with an Uno, it it works flawlessly. I've been researching using a Due and some other ARM based single-board computers, but they all seem to use 3.3V, while almost all Arduino shields and sensors use 5V. I'm hesitant to "upgrade" to these boards if I have to purchase an entire new set of shields and sensors. And I have no interest in hacking in some clunky custom voltage level shifter. Why isn't everything standardized on 5V?

Is this too clunky?
https://www.adafruit.com/products/735
Breadboard Friendly 8-bit Logic Level Shifter, $1.50.

Yes. I have no interest in buying an $80 SBC and then spending weeks debugging my own hacky level shifter circuit. That's like buying a new car for $30k and then having to make your own tires...

If your question is "Why isn't everything standardized on 5v?", see this good SO answer:
https://electronics.stackexchange.com/questions/135841/voltage-standards-like-3-3v-5v-etc
Bottom line is that the voltage drops as the electronics' technology advances (12v to 5v to 3.3v).
Concretely to your problem, I honestly do not think that a level shifter is somewhat "clunky" solution to your problem, as suggested by mikeY (and as rejected by you). This is the way things are done in the electronics world - when a hardware mismatch arises, there is a hardware adapter to rescue.


text:
Why does it say "Servo" does not name a type
#define pingTrig 6
#define pingEcho 7

#include

Servo myservo;

void setup()
{
pinMode(pingTrig, OUTPUT);
pinMode(pingEcho, INPUT);
myservo.attach(9);
}

void loop()
{
long duration, inches, cm;

digitalWrite(pingTrig, LOW);
digitalWrite(pingTrig, HIGH);
delayMicroseconds(10);
digitalWrite(pingTrig, LOW);

duration = pulseIn(pingEcho, HIGH);

cm = duration / 29 / 2;

if(cm < 10 ){
myservo.write(90);
delay(100);
}else{
myservo.write(0);
}
delay(2000);
}

Your include statement seems to be incomplete; add "Servo.h" to your include to make it look like this:
#include "Servo.h"

Without including "Servo.h", the compiler doesn't know what a servo is, and thus "Servo does not name a type".


text:
Example code and documentation on using Firmata communication in native Java
I have been trying for some time to get documentation on using Java and a Firmata client library for the communication between a PC and an Arduino. Please note I want to use Java only, i.e., not Processing.
Up to now I used the excellent Haskell library hArduino for Firmata communication with Arduino boards.
Now I am teaching a Java course at the university as a PhD student. Therefore I need to use Java. However, compared to Haskell there are no centralized libraries, packages, documentation as with Haskell.
So I used Google to find more information on using Firmata client libraries for Java. Unfortunately, the search results are polluted with irrelevant results about Processing and Javascript. Therefore I ask here.
According to the Firmata client library page, there are two Java client libraries. However, only 4ntoine seems to be up to date, while the Javarduino project seems abandoned.
So I guess the standard way is to use the "4ntoine" Java client library. Or are there other options?
(I am not interested in Processing or Javascript.)
Question: Where do I find up-to-date documentation and example code on using Firmata client libraries for Java?

Can someone create the firmata and java tags?

Maybe this can work for you.
Some months ago i used RXTXcomm library [1] to send Arduino data to a Program i made in java and store in in a file, it works fine with some issues:

I made the Java programm in linux but just works in java 6, so in the windows pc of the client i installed that version, i don't know if works with java7 or java8 in windows.
Java programm reads data from Arduino sketch with Serial.print() function, Arduino continously is using this function, i lose some data, so i had to put a short delay to java programm get all data send by Arduino.

[1] http://rxtx.qbang.org/wiki/index.php/Main_Page

Maybe JArduino can give you some useful information.
Check the native code in jardunio.core.

Link only answers are frowned upon because they don't add much value. Please expand your answer with information on why it is useful or make a comment instead.


text:
Cannot communicate with Serial Monitor - Arduino Yun
I connect Arduino Yun to my Computer with WiFi. I was able to get the IP address of my Arduino Yun. However, when I try to print something. It seems to not work at all. The following code is the one that I try:
void setup() {
 Serial.begin(9600);
}

void loop() {
 // print labels
 Serial.print("NO FORMAT");
 delay(100);
}

I did not get any kind of error. However, when I open the Serial Monitor, it shows nothing at all. I try to use the same code with Arduino Uno. It works fine.

double check the port, also check in Device Manager if there is the Yun in Ports. It might be the missing driver

When using the Yun over wifi, you cannot user Serial, you need to use Bridge Console object. Serial is bound to the usb cable.
Give a spin to ConsoleRead example.

Moreover, can you take a look at my other question with Arduino Yun?http://arduino.stackexchange.com/questions/5239/grove-temperature-with-arduino-yun


text:
Arduino Fio and BC127 communication
I am using an ArduinoFio and a BC127 (datasheet). I'm having troubles getting the serial connection working properly from the Arduino to the BC127 and viceversa. I wasn't able to communicate with the BC127 and I don't know if is because isn't correctly powered on or something else.
I've connected pin 0 of the BC127 to GND, pin 33 to 3V3 and pin 41,42 (RX, TX) to the TX, RX arduino's pins.
I've tested with the tester that all wires are connected, but the BC127 seems dead.
Any help is appreciated :|

There's a couple of things I would try.
First: Don't use the native Arduino TX/RX pins, they should be left alone to talk to the computer. Use SoftwareSerial instead in start a separate serial connection.
Second: Check that Arduino TX pin (that you declared in softwareSerial) is connected to the BC127 RX and vice versa. Unlike just about every other connection in electronics, serial connections need to have their pins reversed so that TX talks to RX. It's an easy mistake to make and one I've made when not paying attention to what I was doing.
Third: Flow control.
If the BC127 sends data when the Arduino isn't listening the data could be lost, to prevent this the BC127 won't send until the Arduino signals it is ready through flow control.
See the BC127 datasheet page 8, pins 40 and 43. Trying tying UART_CTS to 3V3 and UART_RTS to Ground. That should cause the BC127 to be in a constant 'send' state.
Lastly I'd hook up a couple of LEDs to pins 37 and 38. They should give you some sort of status indication that could be useful in debugging future problems.

use this method for dealing with voltage translation. Also we have IC's which does the level shifting. Works great with higher frequencies as well.

Use voltage level translator. 5v to 3.3V. Dont just connect directly 5v tx to a 3.3v tx...!!

Do you mean 5V tx to a 3.3V rx?

Yes I would use a N channel Mosfet to make 5v to 3.3V communication.

Your answer is likely to get more votes if you describe how to do this. Perhaps a schematic.

Sure I will post the schematic and how I deal with voltage translation devices.


text:
Arduino UNO serial send and receive issue
I am trying to send and receive data from a PIC16F88 to an Arduino Uno. My problem is that the serial communication stops when the Arduino is not connected to the USB cable. For my application I need the Arduino to still perform its operations with a battery. I have tried both software and hardware serial. Is it possible for the Arduino to send/recieve data when not plugged into the USB cable?

Yes, it should be possible. But please post your code, there's not much we can do to help you without seeing the code you're using.

You need a common ground between the Arduino and the PIC. Connect both grounds one to each other.

Is the Arduino running at all when on battery?  You could be trying to pull too much current from the battery and killing the circuit.  Another cause is that some programmers pull the reset pin to low when unplugged; took me a while to figure out that one.


text:
Identifying a counterfeit or authentic Arduino
I would like to know how I can identify a fake or counterfeit Arduino board.  For example this product, which is shown below.

I am concerned that it is cheap (about $12 when converted) and I was wondering if it is like a 'legal cheap version' or is it an unauthentic one?  If it is not authentic, would it be legal to purchase it?

Arduino mainly have a trademark to protect themselves and this seems to be in violation of that.. Possessing / using it shouldn't get you in trouble, but selling them is a bad idea...
(Selling an Arduino-based device with just the name / logos changed is perfectly legal, but it goes against the spirit of Open Hardware)

It looks like an R3 Uno, but then pictures can be misleading.
However:

Arduino is open source - anyone can make one
Because of that there are many many "clones" of the Arduino
A clone, as long as it's got the right circuitry (and an Arduino is incredibly simple) is as good as the "real thing".

The only problem Arduino have with clones is the use of the Arduino name and logo.  IIRC they don't mind you claiming "Arduino Compatible", but trying to be an Arduino they don't much like.
If it's just their reference designs re-printed (which you can download for free from the Arduino Uno web page) and no further design work has been done, then although it isn't made in Italy by Arduino, it's still an Arduino.
That's the beauty / curse of open source - anyone can make one.
However, that specific one looks like it fits into the "claiming to be an Arduino" category.  It uses Arduino artwork and logos, and tries to make it look like it's an Arduino made by Arduino in Italy, when in fact it isn't.  Legally speaking, they are ripping off the Arduino brand.  Practically speaking, since it's all open source, the actual device (assuming the components aren't counterfeit) should be perfectly fine.
If they were to change the artwork, so it didn't look quite so much like an Arduino, and had something like "Arduino Uno Compatible" on it, then it would be categorized as a clone, and would be fine - you'd know where you were standing.  As it is though, the artwork on it is breaking copyright laws.
The image shown is too low quality to give much information about it, but the two big pointers that it's not made by Arduino are:

The PCB is too blue (real Arduinos are teal)
The polyfuse is the wrong colour (green instead of grey/gold)

And there is no guarantee that the parts on the board aren't counterfeit and you might get burned in some other way, e.g. the recent FTDI driver issues.

@David FTDI hasn't been used on Arduino boards for a number of years now.  They all use an ATMega8U2 or similar programmed with CDC/ACM.

I think it's important to point out that as this board appears to use Arduino logo and branding it is not an "Arduino Clone" it is a "Counterfeit Arduino".

@akellyirl I was actually doing that while you posted that comment ;)

@Majenko-notGoogle I drew the comparison to fake parts, not specific parts.  Equally the microcontrollers used could be sub-standard, be relabelled cheaper parts, contain engineering defects etc.

Yes, open source hardware is a good thing... but I've gotten a bad one a couple of times. They usually say 'Design in Italy' rather than 'Made in Italy' as a way to avoid legal troubles. The few I got had peeling tracings, cold solder joints, intermittent USB communication, and a voltage regulator that got oddly hot.

@JarrodChristman The simple answer is to build your own :P

@Majenko-notGoogle, true enough!

Thanks guys. But what I really want to know is, if I purchase one of these, am I breaking their rights? We are told to purchase one for a small university project and even if it is a counterfeit, it should be enough. But question is, is purchasing it illegal or not.

Purchasing it isn't illegal (AFAIK, IANAL), but selling it is (AFAIK, IANAL).

No, it's a counterfeit. See here - particularly the 'components' section:
http://arduino.cc/en/Products/Counterfeit
Also, as far as I'm aware, Arduino boards are not produced in China but in Italy.


text:
Grove temperature sensor with Arduino Yun
I try to test Grove - Infrared Temperature Sensor on Arduino Yun with the sample code but it does not work. In the console it shows that the object temperature is out of range all the time. However, when I try to test it on Arduino Uno, it works fine.
My sketch:
#include <math.h>
#include<Console.h>
//#include <NewSoftSerial.h>       //if display in LCD(seeed serial LCD driver)
//#include <SerialLCD.h>           //if display in LCD(seeed serial LCD driver)
//#include "temp.h"

const int temp_analog_in = A0;  // Analog input pin connect to temperature sensor SUR pin
const int objt_analog_in = A1;  // Analog input pin connect to temperature sensor OBJ pin
float temp_calibration = 0;     //this parameter was used to calibrate the temperature
//float objt_calibration=0.000; //this parameter was used to calibrate the object temperature
float temperature_range = 10;  //we make a map of temperature-voltage according to sensor datasheet. 10 is the temperature step when sensor and
//object distance is 9CM.
float offset_vol = 0.014;      //this parameter was used to set the mid level voltage,when put the sensor in normal environment after 10 min,
//the sensor output 0.For example,the surrounding temperature is 29℃，but the result is 27℃ via the sensor,
//you should set the reerence to 0.520 or more,according to your sensor to change.
//the unit is V

//SerialLCD slcd(11,12);
float tempValue = 0;
float objtValue = 0;
float current_temp = 0;
float temp = 0;
float temp1 = 0;
float temp2 = 0;
unsigned int temp3 = 0;
const float reference_vol = 0.500;
unsigned char clear_num = 0; //when use lcd to display
float R = 0;
float voltage = 0;

long res[100] = {
  318300, 302903, 288329, 274533, 261471, 249100, 237381, 226276, 215750, 205768,
  196300, 187316, 178788, 170691, 163002, 155700, 148766, 142183, 135936, 130012,
  124400, 119038, 113928, 109059, 104420, 100000, 95788, 91775, 87950, 84305,
  80830, 77517, 74357, 71342, 68466, 65720, 63098, 60595, 58202, 55916,
  53730, 51645, 49652, 47746, 45924, 44180, 42511, 40912, 39380, 37910,
  36500, 35155, 33866, 32631, 31446, 30311, 29222, 28177, 27175, 26213,
  25290, 24403, 23554, 22738, 21955, 21202, 20479, 19783, 19115, 18472,
  17260, 16688, 16138, 15608, 15098, 14608, 14135, 13680, 13242, 12819,
  12412, 12020, 11642, 11278, 10926, 10587, 10260, 9945, 9641, 9347,
  9063, 8789, 8525, 8270, 8023, 7785, 7555, 7333, 7118, 6911
};

float obj [13][12] = {
  /*0*/             { 0, -0.274, -0.58, -0.922, -1.301, -1.721, -2.183, -2.691, -3.247, -3.854, -4.516, -5.236}, //
  /*1*/             { 0.271, 0, -0.303, -0.642, -1.018, -1.434, -1.894, -2.398, -2.951, -3.556, -4.215, -4.931}, //→surrounding temperature,from -10,0,10,...100
  /*2*/             { 0.567, 0.3, 0, -0.335, -0.708, -1.121, -1.577, -2.078, -2.628, -3.229, -3.884, -4.597}, //↓object temperature,from -10,0,10,...110
  /*3*/             { 0.891, 0.628, 0.331, 0, -0.369, -0.778, -1.23, -1.728, -2.274, -2.871, -3.523, -4.232},
  /*4*/             { 1.244, 0.985, 0.692, 0.365, 0, -0.405, -0.853, -1.347, -1.889, -2.482, -3.13, -3.835},
  /*5*/             { 1.628, 1.372, 1.084, 0.761, 0.401, 0, -0.444, -0.933, -1.47, -2.059, -2.702, -3.403},
  /*6*/             { 2.043, 1.792, 1.509, 1.191, 0.835, 0.439, 0, -0.484, -1.017, -1.601, -2.24, -2.936},
  /*7*/             { 2.491, 2.246, 1.968, 1.655, 1.304, 0.913, 0.479, 0, -0.528, -1.107, -1.74, -2.431},
  /*8*/             { 2.975, 2.735, 2.462, 2.155, 1.809, 1.424, 0.996, 0.522, 0, -0.573, -1.201, -1.887},
  /*9*/             { 3.495, 3.261, 2.994, 2.692, 2.353, 1.974, 1.552, 1.084, 0.568, 0, -0.622, -1.301},
  /*10*/            { 4.053, 3.825, 3.565, 3.27, 2.937, 2.564, 2.148, 1.687, 1.177, 0.616, 0, -0.673},
  /*11*/            { 4.651, 4.43, 4.177, 3.888, 3.562, 3.196, 2.787, 2.332, 1.829, 1.275, 0.666, 0},
  /*12*/            { 5.29, 5.076, 4.83, 4.549, 4.231, 3.872, 3.47, 3.023, 2.527, 1.98, 1.379, 0.72}
};

float binsearch(long x)// this function used for measure the surrounding temperature
{
  int low, mid, high;
  low = 0;
  //mid=0;
  high = 100;
  while (low <= high)
  {
    mid = (low + high) / 2;
    if (x < res[mid])
      low = mid + 1;
    else//(x>res[mid])
      high = mid - 1;
  }
  return mid;
}

float arraysearch(float x, float y) //x is the surrounding temperature,y is the object temperature
{
  int i = 0;
  float tem_coefficient = 100;
  i = (x / 10) + 1;
  voltage = (float)y / tem_coefficient;
  //Serial.print("sensor voltage:\t");
  //Serial.print(voltage,5);
  //Serial.print("V");
  for (temp3 = 0; temp3 < 13; temp3++)
  {
    if ((voltage > obj[temp3][i]) && (voltage < obj[temp3 + 1][i]))
    {
      return temp3;
    }
  }
}

float temp_measure()
{
  unsigned char i = 0;
  float current_temp1 = 0;
  int signal = 0;
  tempValue = 0;

  for (i = 0; i < 10; i++) //
  {
    tempValue += analogRead(temp_analog_in);
    delay(10);
  }
  tempValue = tempValue / 10;
  temp = tempValue * 1.1 / 1023;
  R = 2000000 * temp / (2.50 - temp);
  signal = binsearch(R);
  current_temp = signal - 1 + temp_calibration + (res[signal - 1] - R) / (res[signal - 1] - res[signal]);
  //current_temp1=current_temp;
  //slcd.setCursor(0,1);
  //slcd.print("sur T:");
  //slcd.print((int)current_temp1,DEC);
  Console.print("Surrounding temperature:");
  Console.print(current_temp);
  return current_temp;
}

float objt_measure()
{
  unsigned char i = 0;
  unsigned char j = 0;
  float sur_temp = 0;
  unsigned int array_temp = 0;
  float temp1, temp2;
  float final_temp = 0;
  objtValue = 0;
  for (i = 0; i < 10; i++)
  {
    objtValue += analogRead(objt_analog_in);
    delay(10);
  }
  objtValue = objtValue / 10;
  temp1 = objtValue * 1.1 / 1023; //+objt_calibration;
  sur_temp = temp1 - (reference_vol + offset_vol);
  Console.print("\t Sensor voltage:");
  Console.print(sur_temp, 3);
  Console.print("V");
  //slcd.setCursor(11,1);
  //slcd.print((int)(temp1*10000),DEC);
  array_temp = arraysearch(current_temp, sur_temp * 1000);
  temp2 = current_temp;
  temp1 = (temperature_range * voltage) / (obj[array_temp + 1][(int)(temp2 / 10) + 1] - obj[array_temp][(int)(temp2 / 10) + 1]);
  final_temp = temp2 + temp1;
  if ((final_temp > 100) || (final_temp <= -10))
  {
    Console.println ("\t out of range!");
  }
  else
  {
    Console.print("\t object temperature:");
    Console.println(final_temp, 2);
    //Serial.println("℃");
  }
  ////////////////////////////////////////////////////
  //The fllowing code is used for display by serialLCD
  /*
    slcd.setCursor(0,0);
    slcd.print("obj T:");
    if((final_temp>=0)&&(final_temp<=100))
    {
      slcd.print(final_temp,DEC);
    }
    else if((final_temp<0)&&(final_temp>=-10))
    {
      slcd.setCursor(10,0);
      slcd.print('-');
      slcd.print(abs(final_temp),DEC);
    }
    else
      {
        slcd.setCursor(5,0);
        slcd.print("out of range");
        }*/
  //////////////////////////////////////////
}

void setup()
{
  Bridge.begin();
  Console.begin();
  while (!Console);
  Console.println("Hi, what's your name?");// initialize serial communications at 9600 bps:
  //slcd.begin();//Add while using LCD to display
  //slcd.backlight();//Turn on the backlight of LCD while using LCD to display
  analogReference(INTERNAL);//set the refenrence voltage 1.1V,the distinguishability can up to 1mV.
  //analogReference(INTERNAL1V1);//(mega only)set the refenrence voltage 1.1V,the distinguishability can up to 1mV.
}
//If use LCD to display, adding below code to clear the screen in time
void loop()
{
  temp_measure();
  objt_measure();

  /*
    if(clear_num==10)
      {
        slcd.clear();
        clear_num=0;
        }
    else
      clear_num++;
  */
}

I am sure that I connected the wires properly. The exact same wiring configuration is used with Arduino Uno.

What's the current output?

The current out put is 5V.

Sorry, I meant "what does the sketch print right now?"


text:
Issue with adding a library: No such file or directory
I downloaded a Library called "Morse" which I got from the Arduino website:
http://arduino.cc/en/Hacking/LibraryTutorial
(all the way at the bottom of the page there is a link called Morse.zip)
And basically added the library. Then when I import the library, it is included to the sketch. However when I try verifying it, the following error message appears:

to see the image clearer you can right click it and click on "Open image in new tab"
Basically it says:
In file included from sketch_nov28a.ino:1:
C:\Users\Marko\Documents\Arduino\libraries\Morse/Morse.h:10:22: error: WProgram.h: No such file or directory
Now I tried reinstalling the Arduino IDE, I tried adding the library again as well as using the manual method that was stated in that first link above, and the error persists.
What I did notice was that in that second line of the error message, something caught my eye: "...\Morse/Morse.h:10:22:..."
There is a forward slash!(/) Now it seems weird to me that with would happen, especially given that all the other examples I saw of this error online have a backslash (\). This could be the problem.... but even if it is, how do I fix it? I tried going to preferences... does anyone know?

That library is for the older version of the Arduino ide. To fix this you need to open Morse.h and change WProgram.h to Arduino.h.


text:
Unable to load sketch: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41
I've stumbled upon what I've later found it's quite common error, but there seems not to be simple troubleshooting way and solution (people often try various things, sometimes they succeed, sometimes not).
I am using DAGU mini driver, I was able to load sketch as described here - chose Arduino NG ATMega8 as board, connect to my PC via USB (with the driver listed on the product page).
Later on I've plugged RedBot wheel encoders sensor and write some simplistic program to check whether it works at all. I've summarized the steps in a github issue, so that it's easy to reference it.
When I tried to upload the sketch I've receiced stk500_initialize(): (a) protocol error, expect=0x14, resp=0x42, stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41. The full log is included in comment on that github issue.
The D13 diode is making series of 3-blink bursts - 8 bursts after start. More diagnostic I did in the github issue as well.
My question (apart from obvious 'how to fix it!?!' ;) ) is whether there is some kind of documentation for this protocol? On the various topics I've found people seem to have somewhat different problems (the numbers and messages were different). I just want to know why the first few messages are exchanged OK (avrdude receives some basic info from the chip), but later ones (namely Send: A [41] . [81]   [20]) are producing protocol errors.

Ordered programmer, will see if it's just corrupted bootloader

AVR programmer helped.
Meaning the bootloader somewhat got corrupted and I had to burn new one.


text:
How to make Arduino communicate with MySQL?
I am trying to send data from my Arduino to my database but it seems that the process is not successfully beginning. Here is my code for Arduino:
#include <Process.h>
#include <Bridge.h>
int temperature;
void setup() {
  Bridge.begin();  // Initialize Bridge
}
void loop() {
  int temperature = random(0, 100);
  Process p;
  p.begin("143.248.181.36/db.php");// 143.248.181.36 address of localhost.
  p.addParameter(String(temperature));
  p.run();
  delay(5000);
}

I am using xampp and I put db.php inside the htcocs folder. Can anyone point out why it does not work?

I'm not familiar with those libraries, but a quick look gives me the impression that Bridge and Process are used together to make system calls over serial connection on the host system. Based on that..
First, looking at Arduino Process Tutorial Process.begin() should call the process that you want to call. Maybe something like this:
p.begin("curl"); // Assuming you have curl installed on your host system
p.addParameter("http://143.248.181.36/db.php?temperature=SOMEVALUE");

Second, your PHP script is broken.
/ check connection

^ That comment is missing a second slash /
You should definitely get the PHP/MySQL part working standalone before attempting to integrate Arduino in the process. I'm a bit doubtful that $argv gets populated unless you're running the script from command line. If you're making a GET HTTP request (as you would with curl) you might wanna try instead
$temperature = $_GET['temperature'];

If the above works as a workaround, you should get an entry into your MySQL table if you visit the URL below with your browser.
"http://143.248.181.36/db.php?temperature=100"

In any case, get the PHP script working first in your browser. One step at a time.


text:
Is there a pullup on I2C?
I am using an Arduino Uno R3.
It is not clear on the schematic whether there are pullups on the A4 and A5 I2C pins.
Are there hardwired pullups or do I have to add them myself?

There are very weak internal pullups, but they are not strong enough to be considered compliant with I2C specs. Supply your own external 2.2k-10kohm pullup resistors.

No. There are potential internal pullups, but not AFIK activated.
You can quite safely connect I²C to Raspberry P1 (3.3V).


text:
Serial Communication over Desktop to Arduino
I have a USB 2 Serial adapter and the device is working fine. I see the device perfectly configured in my System.
I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter. Below is my Arduino code:
int i = 0;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  for(i=0;i<6;i++)
  {
  Serial.write('H');
  delay(100);
  }
}

But when I try to read thru terminal software of data received at my COM port I see some junk character incoming. I am pretty sure that I am using same baud rate / flow setting both side. Why am I facing this issue - do I need to connect any other pins also as I just need to receive data at system side?

I have a USB 2 Serial adapter...I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter.

You must not connect Arduino pins directly to a D-SUB connector of a USB-Serial adapter, as those connectors traditionally carry higher voltage, opposite sense RS232 signals.

The voltage is too high, and likely to cause damage to your Arduino's processor
The signal is inverted in sense from the logic-level signaling used by your Arduino's processor.

If you actually needed to make this connection, you would need to either use a "logic level" USB serial adapter (sometimes informally called a USB-TTL adapter).  These terminate in various types of connections such as bare wires or header pins/sockets - but basically never in an D-SUB connector.  Or you can use an inverting line driver and receiver such as the MAX2232 type devices, or even an old 1488/1489 pair.
But it's not clear that you should be doing this at all - an Arduino Mega already has a USB-serial converter onboard - that is the interface you use to program it, and it would ordinarily be simplest to use that for runtime communication as well.


text:
Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?
Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?

Those are two different questions. Please edit one of them out of this post and create a new post with it.

Zero, Mega and Tre all have the same basic pinout layout as Uno, which provides at least physical compatibility for the pins. Sparkfun has a breakout board for the Intel Edison.
Mini, Micro & Nano obviously have a different pin layout. I would consider them mainly for projects that have challenging space requirements, since their main advantage is their small size. The Micro should be the easiest to plug'n'play (native USB COM serial). Nano is still stuck with FTDI drivers, so it's going to require separate drivers from the Uno/Mega family. And finally Mini doesn't have USB at all.
Maybe take a look at Wikipedia list of Arduino boards and compatible systems to evaluate better what suits your needs best.


text:
USB mouse/keyboard passthrough feasible?
I'm looking to achieve the following:
USB HID Mouse (or Keyboard) -> [ Arduino device ] -> PC
                                       |
                                        `-> Internet

Basically, I want to connect a keyboard or mouse to an Arduino device, do some processing, send some data over the internet and then pass-through the USB data to the PC as if the Arduino wasn't even there.
My question is twofold: what hardware should I use? Right now I'm looking at the following peripherals:

Arduino Uno R3 SMD
Arduino Ethernet Shield
SparkFun USB Host Shield

Since I'm a complete neophyte when it comes to Arduino, I wanted to double-check and make sure my parts will fit together as well as work towards my goal. I was also contemplating the Arduino Leonardo (since it seems to provide mouse/keyboard out-of-the-box without reflashing the firmware), but I'm not sure I understand what that decision might entail.
Which brings me to my second question: is this feasible software-wise? I found this blog which has some information about pass-through connections, but the mouse library seems to be unfinished. I'd hate to invest 150+ dollars into a project that is doomed from the start.
Thank you!

To connect an external USB device to AVR you need USB Host supported on AVR side. Overhelming majority of AVR chips supports USB device only. There is e.g. AT90USB1287 chip exception. It even exists an AVR USB Key 2 device which can be used instead of normal Arduino unless you want make own PCBs.
Arduino UNO Mouse HID emulates USB mouse internally in Arduino. Implementing is easy when you have USB device AVR chip using LUFA library. But it's not case using external mouse. On the other side you can use legacy serial mouse or PS/2 keyboard as workaround.


text:
Multiple timers with different frequencies
I have to use multiple timers (for example, to blink different LEDs) with different frequency (for example, 7.3 Hz). Cannot you tell me, what is the preferred way to implement it?
Just now I use one simple TimerOne timer and just check what LEDs should be inverted and what are not, but I don't think it's a good idea.
#include <TimerOne.h>

#define PIN_RED 52
#define PIN_GREEN 50
#define PIN_BLUE 48
#define PIN_YELLOW 46

#define N_LEDS 4

float freqs[N_LEDS] = {1, 2, 3, 4};
int pins[N_LEDS] = {PIN_RED, PIN_GREEN, PIN_BLUE, PIN_YELLOW};

long int usec_to_invert[N_LEDS];
long int full_usec_to_invert[N_LEDS];

boolean led_states[N_LEDS];

int who_is_next()
{
  int next_to_invert = 0;
  for(int i = 0; i < N_LEDS; i++)
  {
    if(usec_to_invert[i] < usec_to_invert[next_to_invert])
    {
      next_to_invert = i;
    }
  }
  return next_to_invert;
}

void process_timer()
{
  int to_invert_now = who_is_next(); // Смотрим, кого надо инвертировать на этот раз
  long int time_past = usec_to_invert[to_invert_now];

  for(int i = 0; i < N_LEDS; i++)
  {
    usec_to_invert[i] -= time_past;
  }
  led_states[to_invert_now] = !led_states[to_invert_now];
  digitalWrite(pins[to_invert_now], led_states[to_invert_now]);
  usec_to_invert[to_invert_now] = full_usec_to_invert[to_invert_now];

  int next_to_invert = who_is_next();
  long int time_to_pass = usec_to_invert[next_to_invert];
  if(time_to_pass <= 200)
  {  // The interrupt processor should finish work
    Timer1.setPeriod(200);
  }
  else
  {
    Timer1.setPeriod(time_to_pass);
  }
}

void setup()
{
  Serial.begin(115200);
  for(int i = 0; i < N_LEDS; i++)
  {
    pinMode(pins[i], OUTPUT);
    led_states[i] = false;
    full_usec_to_invert[i] = (long int)(1000000. / freqs[i] / 2.);
    usec_to_invert[i] = full_usec_to_invert[i];
  }

  int next_to_invert = who_is_next();
  Timer1.initialize(usec_to_invert[next_to_invert]);
  Timer1.attachInterrupt(process_timer);
}

void loop()
{
   delay(1000);
}

My suggestions would be:

Implement a class that handles the queue and timer settings and uses callbacks.
If you do not need perfect accuracy, remove the loop making the program wait and do that part just setting the timer.
digitalRead() on an output pin returns the value it was last set to, therefore you do not need to waste that extra RAM.
DO NOT wait in the ISR "process_timer()", since you might lose other interrupts! (for the Serial communication, for example)
is it neccessary to have only values above 200? if not, then don't prevent them from going below that.

--or
use a total overkill system for this situation, such as my multitasking-library arduOS that also covers a some other things.


text:
Arduino Uno PWM
My scheme is very basic: I use RGB LED with Arduino Uno. 5v is connected to anode, and pins 9-11 are connected to cathodes.
When using following sketch, my LED is producing white colour, which red, green and blue components are on:
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup(){}

void loop(){
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}

But when I refer to docs for PWM:
A call to analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on)

When I write 0 to all pins, I expect led to be off. What am I missing?

With your LEDs connected to +5V (AKA "Common Anode"), the PWM signal is reversed.

When the output is "on", the voltage on the pin is 5v.
When the output is "off", the voltage on the pin is 0V.

The difference in voltage between +5V and the pin for those two different states is:

"On" = 5V - 5V = 0V
"Off" = 5V - 0V = 5V

So you can see than when the output is off the LED will on because it causes a difference in voltage from one side of the LED to the other, so current can flow.  When the output is on the voltages either side of the LED are the same, so no current will flow.

Since you've connected to the cathodes the pins are sinking current. As such the LEDS are active low with 0 being almost fully on and 255 being fully off.

Your LEDs are connected to the supply voltage. The output must be low to allow the LED to shine.
Output 0 ==> LED on

I guess this is very basic, but I don't get why.

When you set the pin value to 0 you are making that pin act as ground. Since the LED had a single anode that receives 5V. When the difference between the anode and cathode is high (Anode - 5V & Cathode - 0V) the LED turns on. When the difference between the anode and cathode is low (Anode - 5V & Cathode - 5V) the LED is off. The larger the difference between the two the brighter the LED. In your code use analogWrite(redPin, ~0); then everything should work. Change 0 above to whatever value you want, less than 255, and it should work. Also do the same for the green and plus pins too.

Note that PWM doesn't influence voltage, it just creates pulses.


text:
Arduino GSM Shield web server hangs
I use official Arduino GSM Shield with Uno R3.
I uploaded web server examples from official GSM library. I use a simple python script to make TCP/IP connections to my GSM Shield web server. I send simple requests from my computer to shield, and it responses back.
At first, this worked like a charm. I even connected a led to arduino uno, and started turn it on and off. But after some time, I get timeout errors from my script.
I turned on debug mode of gsm shield. At first, it displayed normal stuff. When connection gone between my computer and shield, it doesn't showed anything on serial window.
I thought there is something wrong with shield, but when I send a request from my computer; light of the shield indicates that there is a transmission incoming; but nothing shows on serial window. I think after some time, connection between arduino and gsm shield gets broken.
What could be done to make this web server more stable? I don't want it stop working after half an hour.
Edit: Other than loop function, my code is same as web server example in the Arduino examples.
// I connected leds to D11 and D12 to see what happens during program.
void loop(){
  GSMClient client = server.available();

  digitalWrite (11, HIGH);

  if (client) {
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();

        // when it receives 1, D12 pin is high for 3 seconds.
        if (c == '1') {
          digitalWrite (12, HIGH);
          delay(1000);
          client.stop();
          delay(2000);
          digitalWrite (12, LOW);
        }
      }
    }
  }
}

Can you post a link to the exact example code you used? Have you made any modifications to it?

@PeterR.Bloomfield I just added what I have changed in web server example.


text:
Atmega168 breaking out of ISR
I wrote a code to handle an ISR triggered by UART input. I'm looking for 2 characters or more. I can handle extra characters and garbage values, but problem arises when I get less than 2 chars, specially when an empty string is sent to the atmel. The UART_receive() on the atmel gets stuck at: while ( !(UCSR0A & (1<<RXC0)) );
Is there any way I can break out of this? The code is posted below:
unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

The actual ISR in question is posted below. It reads the value, sets a flag, and exits as soon as possible.
ISR(USART_RX_vect)
{
    len = USART_Receive_string(uart_string,4); //makes space for 2 character and "\0"
    UART_flag = 1;
}

The the buffer is set up in main()
unsigned char uart_string[20];

I don't see an ISR here. Your code is for UART Rx polling. Do you have a Uart RX ISR in parallel, which reads from UDR0? This may cause problems. Or is this function called inside the ISR? And hopefully your *x points to a reserved array big enough to hold your string. Otherwise you will overwrite other data in memory.

Edited my question. Included the actual ISR now.

Just implement some timeout functionality, so the the while loop will break if no new data is transmitted withing the specified time.

Do you know how can I do that? like put one of the timers into an ISR? Will it work if it's already stuck in this ISR?

Receiving multiple characters within an ISR is a big waste of time. Keep your ISR short. Interrupt when a char is received, get the single character and put it in a buffer, then exit the ISR. Let main() do the rest.

... Then, each time through the main() loop you could check to see if the string terminator has been received. When you detect that, you process the string and clear the buffer. No blocking code anywhere.

You really shouldn't try to receive a string of multiple characters in an ISR - rather, receive only one, or at most however many are then available.  If you want to wait for a full string, do that in your main loop, not your ISR.

Just to second @Tut and Chris Stratton: Look at the USART_RX_vect ISR in HardwareSerial.cpp, which is a good example: read one char, store it, done.

I agree, make the ISR store a single character in a "ring buffer". Or a regular buffer where you reset the index after each message. This is more a design fault as a code fault. What OP is trying to do is not encouraged or a really bad code-model/design.

First of all, you shouldn't share a simple variable between ISRs and the main loop: unsigned char uart_string[20]; should be volatile unsigned char uart_string[20];. Moreover, you must define it out of any scope.
Also, using possibly blocking loop in an ISR is strongly not recommended. In fact, whenever your microcontroller enter an ISR, everything else is stopped: thus, an ISR should last as short as possible. Plus, the USART_RX_vect triggers whenever a single character is received: this means that you'll have to wait for the next one. Thus, you mustn't use ISR like that: I would just use a global volatile variable to monitor the amount of received characters. Then, in the main loop, I would analyze the input characters whenever this counter is greater or equal than 2
.
Finally, in your ISR, you try to read four input characters: '/0' is only one character, in the ASCII table it's called NULL, so you should only read up to three characters.

As a fundamental principle of design you should not be expecting to receive multiple characters in the ISR.
The interrupt fires when a character has been received, so that is all your program should count on finding.  You can if you really want to poll the UART when you are done reading the first character and see if another has arrived, but there would generally not be time for that to have happened and you definitely should not be waiting for it in the ISR.  Rather, if the ultimate consuming code needs multiple characters, then that should hold off executing dependent code until multiple invocations of the ISR have resulted in the collection of the needed number of characters.
Things can get a little more complicated on parts with multi-stage UART FIFOs, but that is not the case here.

I think I may have a very simple solution. Completely overlooked this while I was messing with the timers. I took the hint from a I2C routine in some threads in the the forum here.
This works with empty strings as well as large strings with garbage values. It doesn't seem to hold the system anymore, so it works for my purpose.
Anything I should add here?
int count_for_break = 0;
while ( !(UCSR0A & (1<<RXC0)) )     // wait for another char - Waits for 200 cycles.
        {
            count_for_break++;
            if(count_for_break > 200)
                break;
        }
//then reset the counter upon break or char receive.

If you do this, make sure you stay in the loop for at least a full character time at the lowest baud-rate you expect to use. This can work if the entire string is sent at once, but may fail if there are gaps between characters such as can occur with typing using terminal programs or when using VCP adapters such as USB to serial. Failure may be avoided if you save your received characters if the string is incomplete. A better solution is to receive one character per interrupt and not waste time waiting for another (see my comments above).

I would suggest using code like this:
//Above your program, global variable.
char uartRXbuffer[100];//Adjust size!
int  uartRXbufferIndex = 0;
//bool uartRXmessage = false;

ISR(USART_RXC_vect){
   uartRXbuffer[uartRXbufferIndex++] = UDR;//read UART register into buffer. And increase index by 1.
   if(uartRXbufferIndex > sizeof(uartRXbuffer){
      //uartRXmessage = true;
      uartRXbufferIndex = 0;
   }//else if(uartRXbuffer[uartRXbufferIndex-1] == "\n"){
   //   uartRXmessage = true;
   //}
}

void loop(){
   HandleBuffer();
}

void HandleBuffer(){
   //Do something with your buffer values.
   //if(uartRXmessage){
      if(strstr(uartRXbuffer,"Command1")){
        //Code for when "Command1" is found in your buffer.
      }
   //}
//uartRXmessage = false;
}

I havent tested this code, but the idea is correct I believe.
You can un-comment the uartRXmessage stuff if you only want to handle the buffer when there is an end-of-line character or when the buffer is full.
Alternatively you can implement a ring buffer.


text:
Arduino UNO R3 possibility
Can I use an ultrasonic sensor, ir sensor, serial communication with MATLAB on computer and i2c communication with a D6T MEMS thermal sensor simultaneously in Arduino UNO ?

Yes, it is possible for the arduino handle communicating over serial and I2C in real time, I've done it frequently. The IR sensor should not pose a problem either.
The ultrasonic sensor might use a timed pulse to send its information that can take a relatively long time, and the basic ultrasound code will just wait for it to finish without doing anything else. The delay itself will not cause you problems but if a lot of data is being sent to the arduino very quickly over serial it might miss some. These delays can be worked around with interrupts/some clever coding but I doubt it will ever be a problem.


text:
Burn Arduino Bootloader - Atmega8L
I am making an RGB LED project right now using the Arduino UNO board.
At this point everything is working fine so I would like to transfer this onto a small microcontroller circuit to be put inside the enclosure. Since the enclosure is small, I cannot fit the UNO board inside it, hence I want to make a small circuit on perfboard with minimal components.
I read that you can burn the arduino bootloader on a standalone AVR (hooked up to power, filter caps and 16Mhz crystal) which can then execute Arduino code.
Any idea how can I do this? Also can I do this on an ATmega8l AVR, since my code is small enough to fit in one? No point wasting a 328 if 8L can do the job.
Thanks!

If you have the ability to burn the bootloader to a chip then you have the ability to burn the program to it without using the bootloader.

No need for a bootloader. Just upload your program to the ATMega8 using your Uno as an ISP programmer. If you do more projects like this, it would be a good idea to buy a separate programmer like mpflaga is suggesting.

Also, why the '8L instead of the '88PA (or even '48PA)?

@IgnacioVazquez-Abrams 8L because I had several of them lying unused in my parts box. Regarding burning the bootloader, I understand now that the bootloader is only required to do stuff like uploading using USB etc. Has nothing to do with the actual compiled program

The Bootlader
If you want to burn the bootloader to the standalone AVR that you will be using, you can do so using a programmer like the USBasp. Or, you can simply use the Arduino  itself to do this.

Open the ArduinoISP sketch from File > Examples.
Upload it.
Push reset on the Arduino.

Wire it up
Next, wire up the AVR on a breadboard as shown here: Arduino ISP

If you are using a variant/derivative, use a crystal that matches the crystal on your board. You might have not_in_sync() trouble if you don't.
Add a 10uF capacitor between RESET and GROUND on the Arduino, if you are using Uno, or something similar.

Burning the Bootloader
Then select Arduino as ISP as the programmer.

Goto Tools > Programmer.
Select Arduino as ISP.

Now click on Tools > Burn Bootloader.
Verifying it all works
Once that is done, open the Blink LED example and try uploading it to the AVR. You have to use the Upload using Programmer option from File > Upload using Programmer. You can verify if it is successful, by connecting an LED to pin 19 of the AVR, and checking if it blinks.
Notes:

Remember that the pins on an AVR don't map to the corresponding pins on the Arduino, even if they are both the same chips. Search for "AVR to Arduino pin mapping" for your chip on Google. Here's the ATMega8 to Arduino pin mapping.

Don't forget to connect the ground lines of the AVR and the Arduino.

This worked for me using an ATMega8A-PU. It should work with the 8L too.

Post here if you have any problems. Glad to help :)

"First, you have to burn the bootloader to the standalone AVR that you will be using." Incorrect. You do not need the bootloader in order to use ISP, nor do you need it in order to use the Arduino libraries.

Yes, I am aware of that. OP: "I read that you can burn the arduino bootloader on a standalone AVR". I assumed the OP wanted to burn the bootloader. Will re-word the answer. Thanks for pointing it out :)

Thanks guys. I realize now my wording was quite incorrect.

You can program the 8u2 by either using a ISP programmer such as Pocket AVR Programmer or directly over USB using the FLIPS software as documented
In reference to:

"hence I want to make a small circuit on perfboard with minimal
  components"

I would recommend getting Tiny AVR Programmer or alike to program ATtiny's and at use the ATtiny's directly for small specific tasks. Hence you can avoid the cost of the whole UNO if not needed. You can even emulate limited USB connection as done with the DigiSpark. They even support internal oscillator. So they often need now external parts. They can be often applied without PCB.

Maybe coffee needed?

I would add there are several hardware library Add-on's such as https://code.google.com/p/arduino-tiny/ that give the Stock IDE native support for the Tiny's.

The question mentions the ATmega8L.

Problem with Atmega8A-pu
Make sure the correct com port is selected then on the tools menu select Arduino NG or Older as the board type then choose the ATmega8 as the processor from the tools menu and upload any example Program probably i prefer blink to test (courtesy-PARC-India).
All the best


text:
Flash "sketch" hex over ISP, without bootloader - possible?
I'm wondering if it's possible to flash the arduino sketch into a AVR, without using a bootloader - over ISP. I'd use the BSD programmer, which is basically parallel port with some resistors.
Let's say I use the Arduino IDE, try to upload with "verbose" (no actual arduino is attached) - it shows path to the hex in the verbose output, and I "steal" the file.
Now I'd flash it using avrdude onto a blank 328 via ISP - would that work?
I assume there needs to be a 16Mhz crystal, is that it? Any other pitfalls I have to be careful about?

You don't need the arduino bootloader on the chip, if you are programming it using ISP.
It looks like BSD is no longer supported by avrdude.
In the Arduino 1.5 IDE you can add programmers, so you can do the uploading right from the IDE, instead of 'stealing' the hex file and manually uploading from the command line.
If the chips are blank you probably need to change the fuses first.
You don't need a 16mhz crystal. The atmega328 has an internal 8mHz oscillator inside.

Avrdude seems to support BSD just fine, look: bsd              = Brian Dean's Programmer, http://www.bsdhome.com/avrdude/ in the programmers list. The link is dead though, but there's schematics on google.

-c bsd doesn't work on my 2 versions of avrdude. But that might be because I'm on a Mac. So Windows might work fine.

Macs don't usually have a parallel port, so it's not surprising that a parallel port programmer isn't supported on it.

Edited to mention that using the internal oscillator means you can't use the UART reliably ( you can calibrate it but if the temperature changes it will be wrong again)

@cb88 I think that only applies to the higher baud-rates. Also, please add this information as a comment, instead of an edit. I don't think such an edit is appropriate.

Probably if you have ideal code setting up the baud rates... but it certainly isn't foolproof and the Arduino guys are known for getting those not quite right.... I think their code there is a bit better these days but it's still a likely source of headaches. And they acutally had more issues at low baud rates.


text:
C# and Arduino problem with serial port
I would like to establish a communication between my C# program and my Arduino Duemilanove. I tried lot of different tutorials, but none of them were the same, and I'm a little bit confused.
Actually my code is:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InterfaceArduinoWindowsFOrm {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      serialPort1.PortName = "COM3";
      serialPort1.BaudRate = 9600;
      serialPort1.Open();
    }

    private void pictureBox1_Click(object sender, EventArgs e) {
    }

    private void tabPage2_Click(object sender, EventArgs e) {
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    }

    private void toolTip1_Popup(object sender, PopupEventArgs e) {
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
      Console.WriteLine("test");
    }

    private void button1_Click_1(object sender, EventArgs e) {
      serialPort1.Write("5");
      Console.WriteLine(serialPort1.IsOpen);
    }
  }
}

Arduino:
/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.
  modified 8 Nov 2013
  by Scott Fitzgerald
  http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // Create servo object to control a servo.
// Twelve servo objects can be created on most boards.
int pos = 0;
int message = 0; // This will hold one byte of the serial message
                 // variable to store the servo position.

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // Attaches the servo on pin 9 to the servo object
}

void loop() {
  if (Serial.available()) {

    // Check to see if there is a new message
    message = Serial.read();

    // Put the serial input into the message
    Serial.print(message);

    if (message == '5') {
      Serial.print("test");
      for(pos = 0; pos <= 180; pos += 1) {
        // Goes from 0 degrees to 180 degrees
        // in steps of 1 degree

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }

      for(pos = 180; pos>=0; pos-=1) {
        // Goes from 180 degrees to 0 degrees

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }
    }
  }
}

The problem is, when I click my button, nothing happens, but obviously if I remove the if statement, the servo motor code works.

Did you make sure that the C# button event is fired, and that the Serial connection is established properly? Also, what happens if you open the Arduino COM terminal and press 5?

Hum yea , i tested with some console writte and Button work , what do you mean by : press 5?

I mean that, in your C# code, you just send "5" to the serial port. As part of the debugging - pin pointing where the problem lays - did you use the Arduino Serial console to send "5" the same way you send it from C#, and made sure it works there? Because if sending "5" from the Serial console in the Arduino IDE doesn't work, the C# way won't work either.

I follow lot of tutoriel covering this , the code is really similar as mine , but , when I try to use the serial monitor , and I try to fire button event , it say that Com3 is already in use and unauthorized ... 5 is only a message id to call the arduino IF statement ....

Yes, I get that 5 is the trigger. What I'm trying to understand is whether that trigger works or not. You cannot use Arduino IDE Serial Monitor while running your C# code since the Arduino COM port can interface only one serial port at a time. Try using the Arduino IDE Serial Monitor after closing the C# serial port and not in parallel to it.

Ok , but how to make sure if my arduino trigger is activated

As I suggested; do not run the C# app, only use the Arduino IDE Serial Console to send '5' and examine the results.

A ok ! But how to send 5 from serial monitor , just input 5 on the input text ?

Yes. If you do that, do you get the desired result?

I can confirm you this in arround 1 hour

Since you are sending from the Arduino the received serial data back to the C# application (Serial.print(message);), I would advise to check what you receive on the C# side.
Register to the DataReceived event of the SerialPort as so:
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

And add an event handler:
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    string data= port.ReadExisting();
    // check here what data you received, if any
}

This way you could confirm that the Arduino gets the data properly from the C# side to begin with. Next step would be to understand if this if statement treats the data properly:
if (message == '5')

But starting from examination of what you get from the C# side will help you decide where exactly is the problem.

EDIT : NeverMind I missundarstood your post i'm sorry, But i acctualy don't understand your answer, do you mean that I try to send from Arduino to C# because, Me I want to do the opposite...

Yes, I mean that you try send from Arduino to C# (you are already doing that) and see what you get. This will help you understand where is the problem.

Ok so i Will try if i understand to directly send from arduino to c#

You are already doing it... the line "Serial.print(message);" sending the message back to the C# code. Just see what you get from the C# side as I explained.

Hooo yea it was a test code , but I forget to read from C# I'm sorry if I didn't understand but it's because I forget this line ...

any progress with this?

Tomorow , i CAN continue working on this ,i had´nt GOT the time until now , tomorrow I can tell you if it's working

Ok , i test right now what you said about serialDataReceivedEvent with a  DataReceivedHandler method : { /---what you write --/ Console.WriteLine("received data "+ data); }  I connected the arduino with USB cable and launched the C# program , but obviously I don't compile my program at the same time as it say that COM3 port is already in use ... So, I received some data but it seems encrypted , for example : "Z?" Or "J?"   I will try other message stay tuned,      Edit : apparently message seems to work , yea. I successful receive data from my arduino to my C# program ! Now lt go arduino part!


text:
How to continuously calibrate sensor
I have a problem in calibration an LDR sensor. I want to let the sensor goes all day long and I'm using the LDR sensor as a presence sensor. The calibration values (min and max) changes all the day, and I need to detect only the peaks, or continuously change the min and the max values. Are there some defined pattern or algorithms to use?

In this situation, it may be useful to look at the differential of the signal.
One way to do this is to store the value, wait some time and read another value. You can then do:
dv = current_value - last_value
Or if you have some time metric (Perhaps clock ticks, or a rtc):
dv = (current_value - last_value) / (current_time - last_time)
You would then want to only count significantly large changes in dv. As the day progresses the light value will only change at a small rate but if someone were to block the light then there will be a large difference between current_value and last_value, causing dv to be largely negative (Indicating a loss of a lot of light) and when they no longer block the light you will get the opposite, indicating there is no longer an obstruction. (Or rather, less of an obstruction.)

yes I came at this solution too

Anyway, cool. Where to find some more documentation and algorithm about this kind of simple signal processing things in C?


text:
Are the Arduino Micro, Mini, etc plug'n play?
Also, what about the micro/nano/mini arduinos? Are they easily plug'n'play like the uno?
(This is an edit from another of my questions)

The ones that have a USB connector are plug-and-play with a USB host. The ones that don't need a USB-to-UART bridge.

What's a UART? I'm totally new to this. Also, do the arduinos I mentioned have breadboard-style connectors like the uno?

A UART is what implements the "serial" connection. They come with bare plated holes, so some basic soldering experience is required.


text:
atmega328p on breadboard using ftdi to upload sketches @8mhz 3.3v
I'm having trouble getting the atmega328p chip to upload sketches using my ftdi. It always comes up with an error saying not in sync.
I have an 8Mhz crystal with 22pf capacitors. The weird thing is I could flash the bootloader using my avrispmkII @ 3.3v. AFAIK this tells me the chip is running. I have an led connected to pin7. It doesn't flash when turn the power on.  However it does flash when powered from 5v and everything is working fine. I could upload sketches using the ftdi.
I have the ftdi on a breakout to pin headers. I have the reset pin wired up to the DTR via a 100nf capacitor. The reset has a 10k pull up. CTS pin is grounded. The usart is as follows tx (atmega) ---> rx(ftdi)  and rx(atmega) to tx(ftdi). I have also switch between 3.3v and 5v logic using the vccio pin on the ftdi. I.e. vccio = 5v if atmega is 5v.
I know the programmer need to know what voltage am using, how critical is it, since I don't have a 3.3v regulator to hand. I used a lm338 and it's coming out as around 3.2
I selected arduino pro/mini @ 8mhz 3.3v atmega328p when I flashed the bootloader
##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=57600

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x05
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

##############################################################

output from avrdude
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

pin 7 of the 328P is VCC. Per the ATmegaBOOT_168.c "/* onboard LED is used to indicate, that the bootloader was entered (3x flashing) */". Where this pin is PB5, pin 19 of the 328p or D13. Or is YOUR code attempting to blink a pin.

once programmed voltage is very flexible. See SFE's BigTime Watch Kit it runs directly on a coin cell with oscillator. which runs with "Arduino Pro or Pro Mini 3.3V/8MHz" bootloader. Where the Battery drops over time. Note your fuses are BrownOut below 2.9V so your 3.2 should be fine.

To clarify: it reads as if you are saying it ALL works when using the FTDI, even programs. But it does not when the FTDI is connected through the Breakout board. Are you saying FTDI is directly connected and the Reset circuit is not present.

To clarify the atmega 328 is on the breadboard. The ftdi has its auto reset in tact and connected. I used a bench supply at our lab. I t actually starts working at 3.5 and above. Why?

is it 3.2V at 328's VCC or at the LMN338. Is there any AC to it?

By AC  you mean ripple right? Do I just measure it as if it's an ac source

if so it's  3.2vdc between vcc - gnd pins. And the ripple at those pins is 0.004V ripple.

Let us continue this discussion in chat.

I would suspect that the 328P's fuses were not programmed as defined in the boards.txt This needs to be explicitly done.
uno.bootloader.low_fuses=0xff
uno.bootloader.high_fuses=0xde
uno.bootloader.extended_fuses=0x05
uno.bootloader.path=optiboot
uno.bootloader.file=optiboot_atmega328.hex
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F

if not done. several things can go wrong.

oscillator won't start on external crystal
oscillator will be at wrong speed code
wont start at bootloader

Thats not for the bootloader am using. I'm using the arduino pro mini bootloader. That is for the newer uno. I have checked they match what's in the boards.txt

Fuses are correct. See avrdude output at the bottom of the question

yes, that was added to the question after


text:
Arduino: The program exited the loop early and execute setup() repeatedly
I'm working with Arduino Uno, Adafruit PN532 NFC/RFID Shield and along with other modules. I'm posting this test program because I found there's conflict with the serial output while writing code to integrate all the modules together. I tried troubleshooting by running this code. The result wasn't what I'd expected.
In Arduino, as far as I know, setup() only runs once after starting the program and then loop() will be executed repeatedly. I ran the example sketch called readMiFare provided by Adafruit alone and it was fine. This code can be found at https://github.com/adafruit/Adafruit_NFCShield_I2C/blob/master/examples/readMifare/readMifare.pde. However, when I did the following in main,
void setup()
{
  Serial.begin(115200);
  nfctestsetup();
}

void loop(void)
{
  nfctestloop();
}

the following conflict showed up. When happened was that whenever I scanned a card to the reader it executed the loop() partially and exited the loop. Even worse, it executed the setup() again and again whenever I scanned a card.

In nfctestsetup(), I just commented out    Serial.begin(115200); from readMiFare.
My hardware setup was a no brainer since I'm using I2C.

Appreciate the help.
After spending a good amount of hours on troubleshooting, I found something interesting. When I commented out all other files except NFC and main, it worked like a charm. So I suspect there could be redefinitions on the pins that the NFC shield uses on other files. I suspect the following code in the other file gave me the problem because I commented out the rest of the code in this file and ran this block of code together with NFC and main. In fact, it's the last line of code in this block that gave me the problem.
Also, I probed on the RESET pin (see the readMiFare link above). It generated a high-low-high pulse whenever I scanned a card. Is this related to the problem?
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 3     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

Any thought is appreciated.

Spitballing:  A better question might be, what did you do that is causing the Arduino to constantly reset itself?  I'd verify that the pinout of your Arduino is the pinout that your Adafruit board is expecting- if you've got a short somewhere, or an input/output difference somewhere, that could be causing this.

Sounds like you're not providing enough power and the board is brownouting.

adafruit-nfc-shield. This is how they plug this nfc shield to the board. No wiring necessary. My UNO was connected to the computer via USB. The serial output was fine when I ran readMiFare alone. It didn't reset itself.

In setup after Serial.begin put Serial.println(MSUSR,BIN); MCUSR = 0x00; This will print the reset reason:
• Bit 3 – WDRF: Watchdog System Reset Flag
• Bit 2 – BORF: Brown-out Reset Flag
• Bit 1 – EXTRF: External Reset Flag
• Bit 0 – PORF: Power-on Reset Flag

thanks all for your advice. I found out what the problem is. I have other files that redefine pin2 which is already used by the NFC shield. I appreciate your help. Took me some time to realize my mistake but I learned a thing or two about debugging. Thank you for your time.

This can happen when your sketch uses too much memory - the board can no longer assign addresses so it resets leading to an endless loop. Try reducing the amount of memory you are allocating.

Adafruit support team helped me out on this. I just had to reduce the memory size used by adding wrapping the strings in the print function with F().

Please mark this question as answered in that case :)


text:
Arduino Digital Input Causing Output Problems
I am working on a simple project using an Arduino Mega 2560 that involves reading a 12-bit binary encoder signal and which is used to cycle a digital pin high and low (depending on the angular location of the encoder).
My problem is that when the digital output pin is told to go low, it only goes down to about 4V. I also noticed that it would occasionally dip down to ground, instead of just 4V. Much to my surprise, when I unplug the Arduino, the digital output pin is still reading 4V. When I turned off power to my encoder which is connected up the the Arduino through 12 digital input pins, the output pin dropped down to 0V. When I turn the encoder back on it goes back up to about 4V.
I have tried connecting the output pin to ground and obviously the voltage goes to 0, but as soon as I remove the connection to ground the voltage springs back up to around 4V. It appears as though somehow the voltage being fed to the digital input pins (in the form of a ~5V digital input signal) is preventing the digital output pin from going to ground. I have no idea why this is the case, I have searched all over and could not find any similar complaints. My code is posted below, any help is greatly appreciated!
unsigned long CamAngle = 0;       // Variable to store encoder value
unsigned long PrevCamAngle = 0;   // Variable to store previous encoder value
int i = 0;                        // Cycle index
int BDC[] = {683,2048,3413};      // BDC angle (12-bit encoder value)
int TDC[] = {0,1365,2731};        // TDC angle (12-bit encoder value)

boolean TDCycle = false;          // TDC Cycle
boolean BDCycle = false;          // BDC Cycle
boolean Cycle = true;             // Encoder rollover cycle (replaces TDC cycle 0)

void setup()
{
  pinMode(37, INPUT);           // Encoder bit 0 (PORTC-0)
  pinMode(36, INPUT);           // Encoder bit 1 (PORTC-1)
  pinMode(35, INPUT);           // Encoder bit 2 (PORTC-2)
  pinMode(34, INPUT);           // Encoder bit 3 (PORTC-3)
  pinMode(22, INPUT);           // Encoder bit 4 (PORTA-0)
  pinMode(23, INPUT);           // Encoder bit 5 (PORTA-1)
  pinMode(24, INPUT);           // Encoder bit 6 (PORTA-2)
  pinMode(25, INPUT);           // Encoder bit 7 (PORTA-3)
  pinMode(26, INPUT);           // Encoder bit 8 (PORTA-4)
  pinMode(27, INPUT);           // Encoder bit 9 (PORTA-5)
  pinMode(28, INPUT);           // Encoder bit 10 (PORTA-6)
  pinMode(29, INPUT);           // Encoder bit 11 (PORTA-7)

  pinMode(30, OUTPUT);          // Set PORTC pin 8 to output (stop pin float)
  pinMode(31, OUTPUT);          // Set PORTC pin 7 to output (stop pin float)
  pinMode(32, OUTPUT);          // Set PORTC pin 6 to output (stop pin float)
  pinMode(33, OUTPUT);          // Set PORTC pin 5 to output (stop pin float)

  digitalWrite(30, LOW);        // Set PORTC pin 8 low (stop pin float)
  digitalWrite(31, LOW);        // Set PORTC pin 7 low (stop pin float)
  digitalWrite(32, LOW);        // Set PORTC pin 6 low (stop pin float)
  digitalWrite(33, LOW);        // Set PORTC pin 5 low (stop pin float)

  pinMode(53, OUTPUT);          // Set pin 53 (PORTB-0) as digital output
  digitalWrite(53, LOW);        // Set pin 53 (PORTB-0) LOW

}

void loop()
{

  // Cam Angle Update
  PrevCamAngle = CamAngle;      // Set variable to previous encoder value
  CamAngle = (PINA << 4) + PINC;    // Read encoder, set variable to value

  if (TDCycle == true && CamAngle >= TDC[i])  // Wait for encoder to reach angle if cycle active
  {
    PORTB = 0;                                  // Set digital pin 53 LOW
    TDCycle = false;
    BDCycle = true;
  }

  if (BDCycle == true && CamAngle >= BDC[i])  // Wait for encoder to reach angle if cycle active
  {
    PORTB = 1;                                  // Set digital pin 53 HIGH
    TDCycle = false;
    BDCycle = true;
    i++;
    if (i > 2)                                  // Reset every 3 cycles (3 cycles per revolution)
    {
      i = 0;
      BDCycle = false;
      Cycle = true;
    }
  }

  if (Cycle == true && CamAngle < (PrevCamAngle + 1))  // Wait for encoder to cycle back to 0
  {
    PORTB = 0;                                  // Set digital pin 53 LOW
    BDCycle = true;
    Cycle = false;
  }

}

As you can see I am utilizing direct port manipulation, however I have the same issues when I use the Arduino library commands as well.  I'm fairly certain this is some sort of hardware issue, however I could be wrong.

Could you post a picture of the wiring?

Have you linked the ground of the encoder to the arduino's ground?

Yes, the encoder ground is linked to the Arduino's ground.  I will try to get a schematic of the wiring up shortly.

What is the output connected to? Also is there any resistor between the pin and the connected device?

Sounds like a pull-up / pull-down resistor problem. You're leaving the pin floating instead of giving it the physical ability to go to 0V.

In addition to a schematic of your wiring, also post actual pictures as well. All of us have had many "oh duh" moments where someone looks at our circuit and immediately points out a wiring mistake.

I think you have two issues here.
First:

Much to my surprise, when I unplug the Arduino, the digital output pin is still reading 4V.

With a powered device connected to the input pins, the overvoltage protection diodes power your 5V line with what is called "parasitic power". Those diodes are supposed to clamp an input pin to not exceed 5V, but if the power is off, they actually supply 5V (assuming at least some of the pins are high), hence powering up the processor. It is not designed to do this, and you should not power off the processor in this way.

Second:

My problem is that when the digital output pin is told to go low, it only goes down to about 4V.

I tried out your code, but without the encoder to hand, I just comment out the three "if" tests:
//  if (TDCycle == true && CamAngle >= TDC[i])
...
//  if (BDCycle == true && CamAngle >= BDC[i])
...
//  if (Cycle == true && CamAngle < (PrevCamAngle + 1))

A multimeter on pin 53 reads 0.98V, however this is because the pin is being turned on and off quickly. I can't work out for sure whether some or all of these conditions would be satisfied in sequence (they don't seem directly related). One thing you could do, since you seem to want pin 53 either on or off is use "else", eg.
if (TDCycle == true && CamAngle >= TDC[i])
{
...
} else if (BDCycle == true && CamAngle >= BDC[i])
{
...
}
else if (Cycle == true && CamAngle < (PrevCamAngle + 1))
{
...
}

Now you won't have multiple attempts to turn the pin on and off through one turn through the loop.


text:
Simple IR sensor
I had an infrared 38khz sensor that I used to read my TV remote control commands. It worked fine but I burned it. I had not another 38khz IR sensor so I tried to use my infrared reflective optic sensor like the one below:

I press my TV remote control button and when I try to read the HIGHs and LOWs it does not work. The sensor shows in my Serial that it received the infrared light but it does not sense the lows/high.
As far as I know, this sensor is not 38khz, it listens in all frequencies that are infrared. So why it does not work? It should work cause it listens in all frequencies. Why it can detect the HIGHs/LOWs that the remote control sends?

Just get one out of an old VCR or other electronic device. Manually detecting the 38kHz carrying frequency and filtering out ambient noise is a pain.

You didn't post the code that used to work with the standard 38Khz IR sensor, but I believe you used digitalRead to determine a HIGH or LOW value, by thus determine if there is an IR emitting in place.
The reflective optic sensor works differently, the output is analog, and changes according to the amount of IR light it sens. In addition, it has a built-in IR led next to the IR sensor, so if you want to use this as the IR detection sensor you had, first you need to disable the IR led to prevent interference.
The second step would be to use analogRead, and compare the result to a pre-defined threshold. For example, since analogRead returns result in the range of 0...1023, you can treat everything from, say, 512 and above as logic 'HIGH'. If you are working with libraries that detects the IR signal, you will need to alter them accordingly.

digitalRead works perfectly. I use it with TCRT1000, but external light like sun or luminescent lamp can interfere.

Good to know. I always used it along with analogRead. It kind of make sense when I think about it, since the MCU might interpret top half values as digital HIGH.

I didnt use digitalRead cause people say it's slow. I used -->> while (irSensor_PIN & (1 << pino_sensor_infravermelho)) { <<--. I think my TCRT1000 is with problem. I will buy another one cause  Martynas said it is gonna work. NOTE: I disabled the infrared LED emitter from the component, of course :)

Samul :)))) You made my day. Because i said it won't work perfectly. As i said, the sun and other light will interfere. The voltage may rise that MCU will think its 1. You would probable easier get simple IR sensor :) and it would be more reliable. Something like this http://www.adafruit.com/product/157


text:
ATtiny85 minimum setup to blink led
What would be the (very) minimum schematic to make a ATtiny85 blink a led?
Restrictions are:

There must be a C program compiled and uploaded to it, just like an Arduino board would have. The code would use a simple "delay" to wait a little bit before changing the LED state.
The LED must be controlled by a "digital output port" just like an Arduino board would be.

This is the main question. Although I thought to ask a similar question with the restriction of "blinking exactly once per second", that would change completely the schema (not being a MINIMAL after all). So lets restrain to the main question. Maybe some day we can discuss the version 2.0!

I don't get the question. You set up the pin, toggle the pin, delay the appropriate length, and then go back to the toggle.

I'm talking about the protoboard components needed on it. Lets (fairly) assume that this is a pedagogical question to those who grab one chip for the first time. A small explained minimal schema would be greatly appreciated.

Oh, the schematic? The IC, a power supply, a resistor, and an LED.

Oh, sure. Let me edit my english. Thanks.

Also, support Proposition 12.

This schematic shows a complete connection of a blinking led.

Red cable = +5V (pin 8)
White cable = Ground (pin 4)
Resistor = 1 end at pin 5 (IO 0) and the other in the LED anode (+)
Led anode (+) in the resistor, cathode (-) (small leg) in the ground
Resistor = 330 Ohms

The arduino in the picture is not necessary, just used to give power. But in the video linked below its used to burn the ATtiny85. The resistor can be a 330 ohms for a simple project like this.

Youtube Video with a simple explanation
I hope this explanation will enlighten who wants to start on it.
--
Edited:
If you want to record your ATtiny85 using Arduino UNO as ISP, then you will also need:

10 uF electrolytic capacitor

Here a picture of the pins:

You forgot the decoupling.

@Klaus Warzecha , what is the hardware port (pin?) you're writing about?

You want a 100nF capacitor as well, right by the supply pins.

Ignacio Vazquez-Abrams has already outlined the schematics.

There must be a C program compiled and uploaded to it, just like an Arduino board would have.

There are however some differences between a fully equipped Arduino board with an ATMega328P and a bare ATtiny85 you would have to care for in your code:

A bare ATtiny85 runs at 1 MHz (8 MHz internal oscillator, CKDIV8). Define F_CPU accordingly.
The ATtiny85 only has one hardware port, PB. There's a reason Ignacio used PBx in his scheme ;)

On the plus side, the ATtiny85 allows to toggle a pin by setting the corresponding bit in PINB.
PINB |= (1 << PB0);

Here is the absolute minimal schematic required to blink a LED beyond power and decoupling:

Refer to "Which resistor to use for this LED" to calculate the appropriate value for R1.

Would you be kind to expand all pin connections in that little box called PBx? Without that, the mystery would be solved only by google.

It's one of the GPIOs on the IC.

Correct me if I'm wrong: pins: 1=reset, 2,3=free, 4=gnd, 5=LED, 6,7=free, 8=+5V.

It's all in the datasheet.

My setup would be:

a 10k resistor between Vcc and reset pin (pull-up)
a 330k put in serial with a led,  connected between, e. g. PB0 and gnd.

That's all.
For programming, I use an ISP programmer.  I use a cheap Arduino Nano clone board for that.
I can run my ATtiny85 at 16Mhz internal oscillator,  but important: I remarked that I had better results after having burnt the bootloader onto the ATtiny85, even if it is not needed because there is no USB serial chip besides the MCU.
But perhaps using avrdude to program the ATtiny85 fuses bits could avoid to burn this useless bootloader (taking 1/4 of flash memory). If someone has a solution, he is welcome.

What would that 10k resistor be used for? Thanks.

http://electronics.stackexchange.com/questions/58673/reset-pin-on-attiny84-85-2313-clarification


text:
9v adapter burned out Leonardo style board
My first experience with Arduino ended in a tragedy. I bought a Leonardo from ebay and upon arrival, attached it to my laptop. Programmed a simple blink demo with the onboard LED. It started working. Then detached it from USB and plugged in a 9v adapter. The board started smoking and it doesn't work anymore. I measured the voltage of the adapter and it reads 9.7v. So, what is the reason of this tragedy?
Edit:
I think that the smoke was from a component close to the processor. Right now, when I attach a 9v battery to the board, both the ON LED and the L LED remains on. The processor also warm.

I hate to sound like a prick but if you bought a knock-off then it could be absolutely anything.

Well, it looks like a legitimate made-in-italy one! How can I detect if it is fake or not?

If you bought it on eBay then it's a knock-off. They are very, very good at making exact copies. Except where it counts, as you've discovered.

Did you check the polarity of the adapter? If it's reversed the diode (SMT version of a 1N400x) will overheat.

I checked the polarity of the adapter and it seems OK. When I attach the COM cable of the multimeter to the inner contact of the adapter, it shows +9.7v. Does it confirm that the polarity if OK?

Common to inner, V to outer? If it reads +9.7 it's the reverse of most adapters.

Sorry, I made a mistake in my previous comment. It reads -9.7v. So, it's correct. And the center pin is marked as positive on the adapter too. So, it looks fine.

Post a picture. Perhaps seeing what failed will give a clue.

@Craig: I am not sure if a picture helps or not, since the board looks totally normal. I think that the smoke was from a component close to the processor. Right now, when I attach a 9v battery to the board, both the ON LED and the L LED remains on. The processor also warm.

While it is possible someone shipped a board with a fake regulator or under-rated or reverse polarity filter cap, I'd be inclined to suspect an "evil" 9v adapter first.  Once zapped it may be nothing but a heating element - potentially a mild one if a weak-current source like a 9v "transistor" battery is used.

On the assumption that is now worthless, could you put your volt meter (set to Volts, DC) black to GND, red to 5V pins (you may need hookup wire), plug it in and read the voltage; then do the same on 3.3V, and VIN, and post the results here.