text:
How to integrate smoothing into project (HVAC thermostat / controller)
I am working on building a "simple" HVAC thermostat. This is my current sketch.
    // include the libraries for gizmos
#include <LiquidCrystal.h>
#include <dht11.h>

dht11 DHT11; // Figure out what this line does
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

// These constants won't change:
const int ACledPin = 8;      // Air Conditioner LED (RED)
const int HTledPin = 9;      // Heat LED (YELLOW)
const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

const int RELAY_01 = 6;    // RELAY 1 PIN 9
const int RELAY_02 = 10;   // RELAY 2 PIN 10

void setup() {
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
  Serial.begin(9600);    // Serial setup

  pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
  pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
  pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
  pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

  // Leaves the relays in default "off" (no noise/click)
  digitalWrite(RELAY_01, HIGH);
  digitalWrite(RELAY_02, HIGH);

}

void loop() {

  float analogValue = (DHT11.fahrenheit()); // trying to set up the temp reading as an int variable
////////////// if then ////////////////
// if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ACledPin, HIGH);
    digitalWrite(HTledPin, LOW);
    digitalWrite(RELAY_01, HIGH);
    digitalWrite(RELAY_02, LOW);
  }
  else {
    digitalWrite(ACledPin, LOW);
    digitalWrite(HTledPin, HIGH);
    digitalWrite(RELAY_01, LOW);
    digitalWrite(RELAY_02, HIGH);
  }

Serial.println(analogValue);  // print the analog value:

// Set up the LCD Stuff
  lcd.setCursor(0, 0);      // Set cursor to top left
  lcd.setCursor(0, 1);
  lcd.print(analogValue, 1);
  lcd.print("F");

  delay(1000);

}

I want to add "smoothing" to the temperature reading. I Found this tutorial http://arduino.cc/en/Tutorial/Smoothing and have it working the way I want it.
// Define the number of samples to keep track of.  The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input.  Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
#include <dht11.h>
dht11 DHT11; // Figure out what this line does

const int numReadings = 5;

float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total
float average = 0;                // the average

void setup()
{
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  Serial.begin(9600);    // initialize serial communication with computer:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:
}

void loop() {
  // subtract the last reading:
  total= total - readings[index];
  // read from the sensor:
  readings[index] = (DHT11.fahrenheit()); //analogRead(inputPin);
  // add the reading to the total:
  total= total + readings[index];
  // advance to the next position in the array:
  index = index + 1;

  // if we're at the end of the array...
  if (index >= numReadings)
    // ...wrap around to the beginning:
    index = 0;

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println("");
  Serial.print("Realtime: ");
  Serial.println(DHT11.fahrenheit(),2);
  Serial.print("Average:  ");
  Serial.println(average);
  delay(2000);        // delay in between reads for stability
}

I'm new to Arduino and don't know the best way to do this. I'm not certain how to do multiple loops/delays in a single project, or if I even need to.
EDIT:
I've ended up with this based on the comments from @Craig. The only thing that needs some adjustment are the first 4 readings are low, so it would be nice to somehow ignore, probably not a big deal in the long run.
Example readings on startup;
Realtime: 77.00
Average:  15.40

Realtime: 77.00
Average:  30.80

Realtime: 77.00
Average:  46.20

Realtime: 77.00
Average:  61.60

Realtime: 77.00
Average:  77.00

Final code
// include the libraries for gizmos
#include <LiquidCrystal.h>
#include <dht11.h>

dht11 DHT11; // Figure out what this line does
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

// These constants won't change:
const int ACledPin = 8;      // Air Conditioner LED (RED)
const int HTledPin = 9;      // Heat LED (YELLOW)
const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

const int RELAY_01 = 6;    // RELAY 1 PIN 9
const int RELAY_02 = 10;   // RELAY 2 PIN 10

// START ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////
const int numReadings = 5;
float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total

float get_smoothed_temp() {
    total = total - readings[index]; // remove oldest reading
    readings[index] = DHT11.fahrenheit();
    total += readings[index];
    index = (index + 1) % numReadings;

    return (total / numReadings);
}
// END ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////

void setup() {
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
  Serial.begin(9600);    // Serial setup
  for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:

  pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
  pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
  pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
  pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

  // Leaves the relays in default "off" (no noise/click)
  digitalWrite(RELAY_01, HIGH);
  digitalWrite(RELAY_02, HIGH);

}

void loop() {

  float analogValue = (get_smoothed_temp()); // trying to set up the temp reading as an int variable
////////////// if then ////////////////
// if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ACledPin, HIGH);
    digitalWrite(HTledPin, LOW);
    digitalWrite(RELAY_01, HIGH);
    digitalWrite(RELAY_02, LOW);
  }
  else {
    digitalWrite(ACledPin, LOW);
    digitalWrite(HTledPin, HIGH);
    digitalWrite(RELAY_01, LOW);
    digitalWrite(RELAY_02, HIGH);
  }

Serial.println(analogValue);  // print the analog value:

// Set up the LCD Stuff
  lcd.setCursor(0, 0);      // Set cursor to top left
  lcd.print("Real F:");
  lcd.setCursor(0, 1);
  lcd.print("AVG  F:");
  lcd.print(analogValue, 1);

  delay(1000);

}

What's the difference between the relay pins in the HT/AC pins?

What you want to do is replace your call to DHT11.fahrenheit() with a call to a new function (e.g. get_smoothed_temp()) that keeps track of the last several readings and returns the smoothed value.
const int numReadings = 5;
float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total

float get_smoothed_temp() {
    total = total - readings[index]; // remove oldest reading
    readings[index] = DHT11.fahrenheit();
    total += readings[index];
    index = (index + 1) % numReadings;

    return (total / numReadings);
}

You will still need to set the readings array to all zeros in the setup function.

Your running average code is fine.
A quick way to start up fast is to take your first reading in setup, and fill the array with that value instead of zero.  That way you always get a reasonable temperature from the smoothing, it just gradually drifts from the first reading to the average of multiple readings  (rather than from 0 - a bogus value - to the that average).
This can work for the exponential smoothing too (old average = first reading).
An alternative is to only average as many samples as you have put into the array (1 then 2, then 3 etc until it's filled).  That takes extra code to handle just the first few results, tho, and the simpler approach suggested above (initially fill the array with a legitimate reading) is usually fine.

Good idea. I'll give that a shot.

I'm not certain how to do multiple loops/delays in a single project

You can't do this.* Software threading is the only way to do something like what you want, but it's too complex for what you need. What you want is to use the millis() function to return the time and
// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

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

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

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

You can then pull button changes while you wait for a new reading. Another way would be to use an interrupt to interrupt the flow of the program when a button changes. I won't get into that.
For your use, you can use this template I made:
long previousMillis = 0;        // will store last time temp was updated
long interval = 1000;           // interval at which to check the temp (milliseconds)

void setup() {
  //Foobar
}

void loop()
{
  //Bar of foo
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    //Check Temp
  }
}

*Not to be confused with the loop statement.

I've just done a fan controller (using digital sensors - DS18b20, in my case) and chose an exponential average for smoothing the readings because it doesn't require storing or managing old data and I could get the smoothing I needed. During setup I took a reading from each sensor and preset the averages to those values. That gives the system a "running start"; it doesn't need to wait for enough samples for the averages to settle.
The exponential average I chose was (3 * oldAverage + tempr)/4 because it gave the performance I needed and is easy and fast to calculate without floating point. Multiplying by 3 is done by shifting and adding; dividing by 4 is done by shifting.
Here's the routine I used. It could easily be put in-line; the compiler probably will:
int16_t xpavg(int16_t tempr, int16_t oldAverage)
{
   // (3*oldavg + 1*tempr)/4
   return( (((oldAverage<<1) + oldAverage + tempr) + 2) >> 2 );
}


text:
How does RXD/TXD request signal look betwen 16u2 and 328p on oscilloscope?
I have a broken Arduino Uno. The man tells that he connected power supply and USB at the same time.
I got the new 16u2 (empty) chip. then asked my friend to re-solder it. He was using an air soldering station, but that did not work out. Then I try do that by myself. After 6 or 8 time I was successful. I think.
With stk500v2 programmer thru ICSP I burned in the hardware called:
Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

which I found in Arduino "hardware" folder.
I then burned bootloader to 328p controller:
optiboot_atmega328.hex

That hardware also from Arduino folder.
The problem is that I can upload sketch
error: avrdude: stk500_getsync(): not in sync: resp=0x00

meaning that device not recognizing.
My PC founds Arduino in device manager. 328p with ICSP programmable and working. (checked with blinking.hex 13 pin)
When pressing reset button the 13 led turns of then blinks fast several times that means the boot loader installed property.
Right after pressing upload the Rx blinks 3 times after that I am getting error.
Strange isn't it?
So what I what to know:

I suppose the first must start blinking Tx led?
Can anyone show me how must look like rxd txd interrupts?
So about my assumption that I overheated 16u2 and it does strange things. What are you thinking about that?

You used both ICSP connectors, right?

yes. one to 16u2 near 16u2 another to 328p near 328p

Have you plugged an oscilloscope on RX and TX already? Could you post a picture of what you observed?

I cant put picture. but I can describe... I see 3 negative packets about to 1.7 V in 5ms. weight of packet about 3mm and its RxD scope.. on TxD I see only all line pushed  down about 0.3V for a moments... but I feel that its not that what I want. can anyone answer my question before? which first impulse I must see RxD or TxD because the impulse what I described is RxD.

See screenshot below. The Rx on the Uno (incoming data) should flash first.

The programmer sends STK_GET_SYNC and the board replies STK_INSYNC:
Sent: STK_GET_SYNC / CRC_EOP  (30/20)
Got: STK_INSYNC / STK_OK (14/10)

Afterwards you see the bigger blocks on the lower line as the programmer sends the hex code to the board. Then about half-way through the bigger blocks are on the top as the board sends back the verification data (by reading the flash back).
The little blips would be the other side acknowledging a packet of data.

For more details see What happens when code is uploaded using the bootloader?

source: Stack Exchange

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

sort: votes


text:
Operating / pin voltages ATTiny chips
I would like to set up a project with an ATtiny chip, such as the ATtiny84 or ATtiny85, in which I interface the microcontroller directly with an XBee for both wireless serial communication, as well as monitoring a digital signal from the Xbee (digital input to the ATtiny). As the Xbee chips can handle only 3.3V and will be damaged at higher voltages (such as 5V), I was wondering whether I can simply power the entire project at 3.3V so that all digital inputs and outputs will be at that voltage?

Yes.  As given in the datasheets, normal ATtinyX4/X5 chips can run with a supply between 2.7 and 5.5V inclusive, whereas the low-power versions can run between 1.8V and 5.5V. Mind the speed restrictions when running at lower voltages though; see the "Electrical Characteristics" section of each datasheet to determine the maximum characterized speed for a given voltage.

Won't less speed affect serial communication? Isn't there an option in the bootloader or somewhere to fix this?

Sure it will, which is why you adjust your timing mechanism appropriately.

Thanks for the comments. Does that mean that when I use 3.3V as the supply voltage that the pin voltages, e.g. the HIGH signal of a digital output will be the same 3.3V?

It will be very close. See the datasheets for details.

Specifically, table 21-1 says that V_OH is going to be at least 2.5V for a 3V power supply, so maybe 2.7V for a 3.3V supply. That should provide a sufficient safety margin for the input stage of 3.3V logic.

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


text:
Can't send DHT11 temperature data to Xively from Yun
I thought this would be easy but how wrong I am... All I want to do is plot temperature data but I can't seem to get it to work. It reads it out on the serial monitor and says it has sent the data (in the serial monitor) but nothing on the Xively plots! Why?? Below is the code.
I have the API key and feedID from the Xively site. The useragent I'm assuming is the name of the project. My channels are called sensorValue1 and sensorValue2. Please help - this is taking me far too long.
#include <Bridge.h>
#include <Console.h>
#include <Process.h>

#include "DHT.h"
#define DHTPIN 0
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

 #define APIKEY "BLablablablabla" // your pachube API key
 #define FEEDID blablabla // your feed ID
 #define USERAGENT "SebYun2" // user agent is the project name

// set up net client info:
const unsigned long postingInterval = 60000; //delay between updates to xively.com
unsigned long lastRequest = 0; // when you last made a request
String dataString = "";

void setup() {
  // start serial port:
  Bridge.begin();
  Serial.begin(9600);
  dht.begin();
  while(!Serial); // wait for Network Serial to open
  Serial.println("Xively client");
  // Do a first update immediately
  updateData();
  sendData();
  lastRequest = millis();
}

void loop() {
  // get a timestamp so you can calculate reading and sending intervals:
  long now = millis();
  // if the sending interval has passed since your
  // last connection, then connect again and send data:
  if (now - lastRequest >= postingInterval) {
    updateData();
    sendData();
    lastRequest = now;
  }
}

void updateData() {
  // convert the readings to a String to send it:
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  dataString = "Temperature,";
  dataString += dht.readTemperature(false);
  delay(250);
  // add pressure:
  dataString += "\nHumidity,";
  dataString += dht.readHumidity();
  int sensorValue1 =  analogRead(A0);
  delay(100);
  int sensorValue2 =  analogRead(A0);
  dataString += "\nVoltage1,";
  dataString += sensorValue1*0.0049;
  Serial.print(sensorValue1);
  dataString += "\nVoltage2,";
  Serial.print(sensorValue2);
  dataString += sensorValue2*0.0049;
  delay(1000);
}

// this method makes a HTTP connection to the server:
void sendData() {
  // form the string for the API header parameter:
  String apiString = "X-ApiKey: ";
  apiString += APIKEY;
  // form the string for the URL parameter:
  String url = "https://api.xively.com/v2/feeds/";
  url += FEEDID;
  url += ".csv";
  // Send the HTTP PUT request
  // It is better to declare the Process here, so when the
  // sendData function finishes the resources are immediately
  // released. Declaring it global works too, BTW.
  Process xively;
  Serial.print("\n\nSending data... ");
  xively.begin("curl");
  xively.addParameter("-k");
  xively.addParameter("--request");
  xively.addParameter("PUT");
  xively.addParameter("--data");
  xively.addParameter(dataString);
  xively.addParameter("--header");
  xively.addParameter(apiString);
  xively.addParameter(url);
  xively.run();
  Serial.println("done!");
  // If there's incoming data from the net connection,
  // send it out the Serial:
  while (xively.available()>0) {
    char c = xively.read();
    Serial.write(c);
  }
}

As long as I checked, this way of uploading data to Xively only works for up to tree pairs of name,data.
If you try with more pairs at the same time the response is "Done", but nothing happens. I finally divide the upload in groups of 3 parameters, and everything is Ok.
I saw your question yesterday when I was looking for a way to upload data to Xively from Yun. It was really helpful for me. Thank you.


text:
Arduino PWM fading led
I am trying to blink an LED with PWM on Arduino.
I don't know what is wrong but my LED is not fading as expected. What is wrong?
I think that I have bad registers settings, but I am not sure.
LED is connected to Arduino pin 9.
Here is my code:
#include <avr/io.h>
#include <util/delay.h>
const int delay=1000;
void initialize_PWM()
{
    TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
    TCCR0B=1;
    DDRB|=(1<<PB1);
}

void set_pwm(uint8_t data)
{
    OCR0A=data;
}

int main (void)
{
    initialize_PWM();
    uint8_t brightness=200;
    while(1)
    {
        for(brightness=0;brightness<255;brightness++)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }

        for(brightness=255;brightness>0;brightness--)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }
    }
    return 0;
}

Which Arduino? You appear to be using port B1 which maps to D9 on ATMega328p, so Uno, perhaps? What do you see - A bright LED? A dark one? Is your LED wired right way round? Have you tried using that pin as digital I/O using library functions to confirm that the LED can work as wired? What else have you tried?

Arduino Uno with ATMega328p. I see dark LED. Wires are in right way. And LED is working when I plug it to +5V and resistor.

can't you use analogWrite( pwm )?

No, because I want use it without external libraries.

is this using the arduino ide?

From your code you are using Timer0 in FastPWM mode with top = 0xFF.
In this mode, as used in your code, OCR0A defines the pulse width rate (more precisely, OCR0A / 256).
Timer0 uses port OC0A and OC0B to ouput PWM signals, in your code, you are using only OC0A (which is perfectly fine).
Now if you take a look at ATmega 328 data sheet, chapter 14.3.3 you will see that pin OC0A maps to port D, pin PD6 (on Arduino UNO, this is port D6, according to http://arduino.cc/en/Hacking/PinMapping168).
So this means that you have used the wrong port in your setup (Arduino pin D9 maps to OC1A, which is pin PB1 of port B on ATmega328, OC1A is used by Timer1, not Timer0).
Hence you should do the following to fix the problem:

Plug the LED to Arduino pin D6 instead of D9
Fix initialize_PWM() by replacing DDRB|=(1<<PB1); with DDRD|=(1<<PD6);

Otherwise, if you want to keep Arduino pin D9, then you will have to change the timer you use: Timer1 instead of Timer0. Updating the code is left as an exercise!

It's much too soon to optimize. Get your LED working using the standard (known working) libraries. Only then - and perhaps never, unless you find a need to - should your optimize (use direct register I/O). If it works with the libraries but not with your direct I/O, you'll know the bug lies in the direct I/O code and nowhere else, ruling out failed hardware, improper or unreliable connections, and programming errors elsewhere in your project. Right now, you don't know even that much.

The easiest way is to use the timer1 library written for arduino. You can download it here.
To install, simply unzip and put the files in Arduino/hardware/libraries/Timer1/

Prescaler set for 16Mhz
Prescale    Time per counter tick   Max Period
1   0.0625 uS   8.192 mS
8   0.5 uS  65.536 mS
64  4 uS    524.288 mS
256 16 uS   2097.152 mS
1024    64uS    8388.608mS

In general:
Max Period = (Prescale)(1/Frequency)(2^17)
Time per Tick = (Prescale)*(1/Frequency)

Instructions available using this library are:
initialize(period)
You must call this method first to use any of the other methods. You can optionally specify the timer's period here (in microseconds), by default it is set at 1 second. Note that this breaks analogWrite() for digital pins 9 and 10 on Arduino.
setPeriod(period)
Sets the period in microseconds. The minimum period or highest frequency this library supports is 1 microsecond or 1 MHz. The maximum period is 8388480 microseconds or about 8.3 seconds. Note that setting the period will change the attached interrupt and both pwm outputs' frequencies and duty cycles simultaneously.
pwm(pin, duty, period)
Generates a PWM waveform on the specified pin. Output pins for Timer1 are PORTB pins 1 and 2, so you have to choose between these two, anything else is ignored. On Arduino, these are digital pins 9 and 10, so those aliases also work. Output pins for Timer3 are from PORTE and correspond to 2,3 & 5 on the Arduino Mega. The duty cycle is specified as a 10 bit value, so anything between 0 and 1023. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.
attachInterrupt(function, period)
Calls a function at the specified interval in microseconds. Be careful about trying to execute too complicated of an interrupt at too high of a frequency, or the CPU may never enter the main loop and your program will 'lock up'. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.
setPwmDuty(pin, duty)
A fast shortcut for setting the pwm duty for a given pin if you have already set it up by calling pwm() earlier. This avoids the overhead of enabling pwm mode for the pin, setting the data direction register, checking for optional period adjustments etc. that are mandatory when you call pwm().
detachInterrupt()
Disables the attached interrupt.
disablePwm(pin)
Turns PWM off for the specified pin so you can use that pin for something else.
read()
Reads the time since last rollover in microseconds.

Example - Sets up PWM output on pin 9 with a 50% duty cycle, and attaches an interrupt that toggles digital pin 10 every half second.
/*
 *  Timer1 library example
 *  June 2008 | jesse dot tane at gmail dot com
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

Source: http://playground.arduino.cc/Code/Timer1

The OP mentioned in a comment that he does not want to use external libs (and that seemed to include arduino libs also)

Oh I've missed that probably. Sorry. Though, I'll keep this answer standing in case someone else who's searching for an answer like this.


text:
Is it possible to press a button from Arduino and my computer will get a key event?
My idea seems easy:
I connect a button with arduino, then write some code and upload it to arduino. Then I open the notepad(or any other editor) on my computer. When I press the button, there will be a character "A" displayed in the notepad.
I have tried with my Arduino uno, and use Serial.write/print function to send an A to serial port 9600, but it seems the character A only shows in the serial monitor GUI.
My question is:

Is "Arduino uno" is OK to implement this?
If not, what other board should I use?
Is Serial.write/print the correct function?
Or shall I use the Keyboard.??? function?
Do I have to write an application which runs on the computer and listens the serial port, and emit a real key event? (that's sad)

The Uno is not the best board for this. You may be able to get somewhere with the Virtual USB project but there are a couple of boards that are better suited for this.
Those are the Arduino Leonardo, Micro, and Due. In those, you can use the Keyboard Library just like you are using the Serial library now. This page has an example very similar to your project:
void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send the message
    Keyboard.print("Hello!");
  }
}

There is a micro designed more specifically for keyboard emulation, I haven't done any experimenting with it (yet), but it's very popular in the flight simulator world where these micro's are rigged up with buttons and switches and rotary encoders to simulate a cockpit. These inputs are converted to keyboard inputs (as far as I can see).
There are some general projects here: https://www.pjrc.com/teensy/projects.html
Some more keyboard specific stuff: https://www.pjrc.com/teensy/usb_keyboard.html
More info on the teensy in the arduino environment: https://www.pjrc.com/teensy/teensyduino.html
More specifically about what you're looking for, this could be quite useful: https://www.pjrc.com/teensy/td_keyboard.html
I'm not steering you away from Arduino, it's just something else to look into

Go for Teensy indeed. They're small, cheap and can be used just like 'official' Arduinos. You can keep using Arduino's editor, so aside from the board nothing will change. You do not only get keyboard emulation, you can also pretend you're a mouse, a MIDI interface and many other things.

Your example describes collecting text - does that meet your goal or do you need to generate any kind of key-event? If you don't need to generate system events, any terminal emulator (not just the Arduino IDE) should be able listen to that same port and to log whatever it receives to a file.

I need it to be some kind of key-events. My final goal is to make a custom keyboard by arduino

Check this video,
Arduino UNO as a USB keyboard (HID device) [Anything Arduino] (ep 6),
as I think this is what you are looking for.
From the youtube video you can get links to the library site and schematics.
You do need to build a small interface to connect your Arduino to a PC.
I got it for Uno and Micro, but other Arduinos with latest firmware would be OK.

When you link to an outside source it helps if you summarize what the link (the video in this case) is about or how it helps to solve the problem. This is especially useful if the link "rots." We're trying to build a durable resource here, try to think for the long term in your answers.

If you could edit your answer to provide the links in your answer that would be a good idea, as well as a copy of the schematics, quoting the source, if copyright allows that, in case the video is deleted.

I think you also need to install processing.
See this link
It enables you to program the computer-side of the application.

Do you mean I have to use some programming languages to write a program running on the computer-side? Do I have to use the "processing" language? I found it's interesting, but I'm sure why it's special with Arduino?

Processing, while a valuable addition to your arsenal when using Arduino, is not needed for your purposes. Instead, it will make things overly complex, if not impossible.


text:
nRF24L01 pipe question
I am looking through the example code found here. I know there are 6 pipes that the nRF24L01 module can use but I've been searching the internet for the address designations and have been able to find nothing. More specifically on line 37, is there a reference for where the author is getting 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL?
Thanks.

Have you looked at the datasheet for the radio IC? That certainly has more information about pipe addresses.

Check RF24 API doc for openReadingPipe() here: http://maniacbug.github.io/RF24/classRF24.html#aa7e8523f86f9f8f20c274e0c89a5fd45 it mentions you can use any values for the last address byte.

So I looked through the documentation but it doesn't mention how the pipe address is chosen. It just say they should share the first 32 bits. For example 0xF0F0F0F0(XX), does 0x count as a byte? Or is F0F0F0F0 the 32 bits that matter? Also, does it matter if it's not F0F0F0F0 as long as the pipes share those 32 bits? How about the last two significant bytes (XX)? Are those arbitrary as well?

The 0x... prefix is just to tell the value is in hexadecimal. This is because 99 in decimal is different from 99 in hexadecimal, even though they look the same. So instead we use 0x99.

The code you a using only supports 1 pipe. The nRF24L01 has 2 unique pipes (0 and 1). It also has 4 additional pipes (2, 3, 4 and 5), where you can only set the least-significant-byte. The other bytes will be the same as the second pipe (1).

Thanks for the response, I guess I just still don't understand if there's a process to set the least-significant-byte. For ex like E1 or D2 in the pipes listed above...

As most of the people have posted, the values for the pipe are arbitrary, but must follow the rules per the API:

Pipes 1-5 should share the first 32 bits. Only the least significant
  byte should be unique, e.g.

Before I answer your question, I think an explanation on Hex and Decimal values are needed.
The 40 bit hexadecimal is a number representation of base 16. A decimal is of base 10. So you can convert a Hex Value to Decimal. As this is out of scope for the question, you can google on how to convert from one to another. There are some online converters:
Hex to Decimal Converter
You will see when you convert the Hex value to decimal, that its just a number representation. When you convert, you drop the 0x and LL. As stated the 0x indicates the value is a hex value and LL means type Long Long.
So to answer your question, use the a converter to find a hex number like:
F0F0F0F0A1
F0F0F0F0A2
F0F0F0F0B4
F0F0F0F0E9

Just change the last 2 digits (least significant bit):
Pipes 1-5 should share the first 32 bits. Only the least significant byte should be unique, e.g.
   openReadingPipe(1,0xF0F0F0F0AA);
   openReadingPipe(2,0xF0F0F0F066);

Add the 0x and LL
0xF0F0F0F0A1LL
0xF0F0F0F0A2LL
0xF0F0F0F0B4LL
0xF0F0F0F0E9LL

All should work.
I am no expert on hex, as I am learning, so if I am incorrect, then please someone correct me.
Finally, the nRF24L01 datasheet makes the following point that the choice of address is not completely arbitrary:

Note: Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate.

could you please mention also, that those pipes refer only to the "6 data multi-receiver" feature (s. Nordic datasheet p39-40). by default only data pipe 0 and 1 are enabled.

@bersch - Is that relevant? The OP was asking how the pipe values are choosen e.g. where the author is getting 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL?, not how the pipes are used.

In order to choose the values, you need to know that by default there is a writing pipe and a reading pipe. In multi-receiver mode there is a writing and up to 5 reading pipes. You describe only the reading pipes. So far I didn't check that, but I believe if one choses the reading and writing pipe that share the first 32 bits, it will fail.

From my testing, the values are arbitrary as long as your pipe 0 & 1 are the same on the Transmitter and the receiver

I see. For myself I didn't check the multi-receiver feature. I use each chip for transmit and receive.

I am working on mine. I will have 1 transmitter and 4 receivers

sound interesting

The values 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL are arbitrary values and define the adresses of the senders and receivers to talk to.
If you use the Mirf library
Mirf.setRADDR((byte *)"serv1");

they can be also strings like serv1.
RF24 uses
write_register(RX_ADDR_P0, &value, 5);
write_register(TX_ADDR, &value, 5);

There's something that everyone forgets to tell you:
Pipes at receiver should be shortened after the first one
const uint64_t pipe01 = 0xE8E8F0F0A1LL;
const uint64_t pipe02 = 0xA2LL;
const uint64_t pipe03 = 0xA3LL;
const uint64_t pipe04 = 0xA4LL;
const uint64_t pipe05 = 0xA5LL;
const uint64_t pipe06 = 0xA6LL;

radio.openReadingPipe(1, pipe01);
radio.openReadingPipe(2, pipe02);
radio.openReadingPipe(3, pipe03);
radio.openReadingPipe(4, pipe04);
radio.openReadingPipe(5, pipe05);

Pipes at transmitter should be
const uint64_t pipe01 = 0xE8E8F0F0A1LL;
const uint64_t pipe02 = 0xE8E8F0F0A2LL;
const uint64_t pipe03 = 0xE8E8F0F0A3LL;
const uint64_t pipe04 = 0xE8E8F0F0A4LL;
const uint64_t pipe05 = 0xE8E8F0F0A5LL;
const uint64_t pipe06 = 0xE8E8F0F0A6LL;

uint64_t setPipeToSend = pipe01; // or pipe02 or pipe03 or pipe04 or pipe05
radio.openWritingPipe(setPipeToSend );

If you want to know which pipe's message has come, use
  uint8_t someVariable;
    if (radio.available(&someVariable))
    {
       Serial.print("pipe number ");
       Serial.printLn(someVariable);
    }

Also pipe number 6 is used for receiving acknowledge messages.
In addition, the initialization code must have radio.enableDynamicPayloads();
This one works well for me:
    radio.begin();
    //radio.setChannel(0x57); //if set should be the same at the both sides
    radio.setPALevel(RF24_PA_LOW);  // "LOW" is more stable mode
    radio.enableAckPayload(); //for autoanswers
    radio.openWritingPipe(pipe01); //for sending
    //link pipe numbers to the pipe addresses
    //radio.openReadingPipe(1, pipe01); // I use pipe01 for sending
    radio.openReadingPipe(2, pipe02);
    radio.openReadingPipe(3, pipe03);
    radio.openReadingPipe(4, pipe04);
    radio.openReadingPipe(5, pipe05);
    radio.enableDynamicPayloads(); //must have for multi pipe receiving
    radio.startListening();  //start listening

Good luck...

whats pipe defined as in your example?

I have edited the code. You can use any of these 'pipes' for sending, but don't forget (like me) to exclude that pipe from reading.

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


text:
If statement behaves erratically
I connected the output from an encoder motor to int0. this is used to increment a counter at every pulse. in the loop(), I check this counter and stops the motor if it is above certain value. But this "if statement" works erratically. The while loop should break at 380, but sometimes it breaks at 256.
Serial.print(cnt);
cnt=0;
Serial.print("  ");
Serial.print(cnt);
motor1_up(255);
motor2_up(255);
while(1)
{
    if(cnt>380)
    {
        Serial.print(" break ");
        Serial.print(cnt);
        break;
    }
}
motor1_down(255);
motor2_down(255);
Serial.print("  ");
delay(40);
Serial.println(cnt);
motor1_down(0);
motor2_down(0);
delay(2000);

Here is the serial output
 1  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389
 396  0 break 381  389
 396  0 break 256  264
 270  0 break 381  389
 397  0 break 381  390
 396  0 break 381  389
 397  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389

it is difficult to tell what the issue could be without seeing the entire code. Also the line with while(1) on it looks awful, separate it onto several lines.

Welcome to Arduino SE! It's really hard to answer this question with such a small code snippet. It's fine if you've isolated the problem, but you don't explain the code much. For example, what is the motor1_down() for? It's fine to remove snippets that aren't useful (i.e. polling from a light sensor in this scenario), but it's generally helpful to have all the libraries/methods/etc. Can you please edit your code? Thanks!

I've just come back to have another look at this. It is very unclear what it is you are doing. Is this an ISR? If so, you've go a locking while(1) in there. If it's not, then when does this get called? Please post the full code

@madivad I guess that for a rotary encoder you have no other option than use interrupts, otherwise you may miss ticks, depending on the encoder steps and the motor RPM. However, the posted code is obviously part of loop().

Ok, I see it now, I misread the question (and so I have removed my answer).

Not only must cnt variable be declared volatile, but accessing it from the main loop must also be protected because:

it can be modified by an ISR
it is longer than 1 byte

In AVR architecture (8-bits), read/write operations on bytes are guaranteed to be atomic, i.e. no function can access a byte while it is read/written by an ISR.
However, operations on types larger than bytes are not atomic!
This means that reading e.g. an int variable from your main loop might be interrupted in the middle of the operation (only 1 byte read) by an ISR that could modify the value (both bytes this time); then when the ISR is finished the main loop would resume reading the second byte -modified by the ISR- of the variable, while keeping the first original byte -not modified by the ISR.
I would advise you to write a pair of functions to read and write cnt in a protected way, i.e. with interrupts disabled:
volatile int cnt;

void set_cnt(int val) {
    uint8_t status = SREG;
    cli();
    cnt = val;
    SREG = status;
}

int get_cnt() {
    uint8_t status = SREG;
    cli();
    int val = cnt;
    SREG = status;
    return val;
}

What those functions do are:

get the current status of exceptions (from SREG register)
disable exceptions with cli()
access cnt without any risk of it being accessed concurrently
restore initial status of exceptions (to SREG register)

Everywhere in your code (except in code called from an ISR where it is not necessary), you must then call these functions to access cnt variable.

It looks like it could be a caching issue. If you're accessing a variable from the main loop and from an interrupt handler, then you need to ensure it's declared as volatile. For example:
volatile int cnt = 0;

That tells the compiler that the contents of the variable could change unexpectedly, i.e. when an Interrupt Service Routine is triggered. The result is that it always fetches the actual value from RAM, instead of relying on a cached copy which could be out-of-date.


text:
How to connect mini jack output to arduino mini pro and send sound to it?
I would like to connect arduino mini pro to mini jack output and send sound through it.
What would I need here, how can I connect the mini jack to arduino and how to send data of sounds (any library?) to that connected output?
EDIT
The sound source will be a music file ( streamed via bluetooth). I would like to be able to connect this output to a speaker and play (stream) music via bluetooth.
EDIT
Either mono or stereo will be good for me. My plan is to: stream the music via bluetooth to bluetooth module (for now I think about HC-06), send that data stream through arduino mini pro to the output mini jack.
Do I need in that case some kind of mp3/other format decoder module like VS1003B on ebay ?

Low pass filter on a PWM signal?  Best to buffer it with an op-amp too.  Or just connect it through a capacitor and use tone()?

Please improve this question.  Tell us what kind of sound you want to generate, what level of quality, what the sound source is expected to be (file? tone()?), and what you ultimately want to connect the output to.

Also tell us what you have tried, and why none of the millions of tutorials available through a very quick google search are good enough for you.

@Majenko Edited.

Still not enough information.  Tell us more.  A jack is just a socket.  There's a million ways to wire it up.  The correct one depends on things like what you will plug into the jack, what quality of audio you want, whether you want stereo or mono, etc.

@Majenko I added some information, I am trying to get some information on my possibilities here - that's the reason for my question.

I think you're staring out on completely the wrong footing and anything you try will be doomed to failure. The Arduino is nowhere near powerful enough to generate high quality audio by itself. The best you could hope for is very rough low bandwidth PWM audio where you can just about make out what it is meant to be. Pointless really. You could add a DAC, like the Adafuit Wave Shield uses, but that is still low quality (22KHz, mono, 12-bit). I once made my own audio shield for the Arduino that was CD quality, but that employed an additional MCU with DSP to do the audio processing, which was...

...10x more powerful than the Arduino, making the Arduino completely redundant. I would suggest you upgrade to a more capable platform. The Due would be better as it's a 32-bit core with built-in 12-bit DAC, but still a bit pants. Even better would be a PIC32MX470 based system and a proper I2S audio DAC.

What about this VS1053?

You could maybe link that direct to your bluetooth module (it has a UART interface) and throw away the Arduino. Whether that UART interface will take audio data I have no clue, since it says "UART for debugging purposes" yet says "Serial control and data interfaces" - it may only refer to the SPI, so you may want the Arduino to feed the data through from UART to SPI.

I do not recommend using the HC-06 chip. First of all, it is a serial chip, thus it sends text, not audio. You might be able to convert it to character codes on the phone side, but that'd be a lot of work. Also, the baud rate might not be high enough to keep up with what you want to do.

I have found docs that say the baud rate can be set up to 1382400 googledoc (of few others). Any alternative for this chip(non serial one) ?

I don't really know if there's one in breakout form for such a chip. Also, for those types of chips, they would be designed to provide a direct connection to a 3.5mm jack or to a decoder chip

@AnnonomusPenguin What about those type of integrated bluetooth mp3 decoder? ebay spk d bluetooth mp3 decoder

Yes, that'd be better. I can't give you much advice since a.) there's no datasheet so it'd be near impossible to give you correct advice and b.) that chip is beyond the scope of Arduino SE because it doesn't use an Arduino.

The Arduino Uno / Mini Pro is not really the right tool for the job. It has no native audio output such as a 3.5mm jack.
Having said that I am sure it can be done - but it won't be the best quality sound. I have no doubt that it can be achieved with one of the following methods:

using the tone() function.
by using a R-2R resistor ladder network and some sort of amplification circuit.

The Arduino Due and the Arduino M0 / M0 Pro both have inbuilt DAC's, meaning that they can output analog signals which can be used to drive a speaker circuit.
Another option is to use a Raspberry Pi which has a native 3.5mm audio jack.

Or you can use the PWM as a poor man's DAC. That's what the Mozzi sound synthesis library does.


text:
Reading speed of different arduinos
I'm thinking about using an Arduino for one of my Projekts. This would require that the Arduino can read/write a digital input/output in the order of 100kHZ to 1MHz. Is this possible or do I have to resort to my own boards using ATmegas?

Depends on what else you want to do besides read/write the digital IO.

How many pins are you changing? Digital or analog? PWM? What other code are you running? You're super vague here, as there are hundreds of different factors that will affect it. Also, some boards have different clock cycles. Can you please edit your question to make it less vague? Thanks!

You really need to provide more information for people to be able to provide anything useful.

Focussing on your final question:

Is this possible or do I have to resort to my own boards using ATmegas?

Remember, an Arduino is already just an ATMega already on a board. Designing your own board around an ATMega that is already part of the Arduino family is not going to significantly alter your project. That is unless you are going to have supplementing hardware, or go via higher clock speeds or ARM processing.

Any Arduino will do just fine. Technically, you could output 8 digital signals simultaneously at the Arduino's clock speed (16 MHz on most models), as it only takes one clock cycle to flip an output bit.
In more realistic scenarios 100kHz is no problem at all, and depending on your code 1MHz is possible as well.

Please note that using Arduino library's digitalRead() and digitalWrite() will take much more than a single clock cycle as these methods do a lot before flipping the right output bit.

It's also worth noting that while you can read an input in one clock cycle, if you want to do anything with the values you read in, you will have to stop reading the inputs.

And that's why I said technically and in more realistic scenarios. Furthermore, my claim that probably any Arduino will be able to do simple digital reading, processing and writing at speeds > 100kHz is true.


text:
How to program arduino for ethernet with only usb cable
I have arduino UNO r3 ATMEGA 328P board and this kind of a cable. But I want to make and test a program that need to get the data through ethernet port. Can I do only with them. I want to know whether they are enough to that (there are any converter or virtual devices) or should I buy anything.

You can do the programming of the Arduino through the USB cable, but in order to test and operate the program, you'll need an Ethernet shield and a cable to connect that to the LAN.


text:
SerialEvent handling when using multiple serial ports
I would like to use multiple (three) serial ports on an Arduino Due. Instead of polling the ports continuously, I would like to use a Serial.Event function for each of the ports. These handler functions will read out the incoming string from the port and parse the string (i.e. check for a pre-defined command and call a corresponding sub-routine).
I was wondering what is going to happen when serial data arrives at the same time at two different ports? For example, if the program is in the process of handling/parsing the first serial message, will it interrupt/abandon this process as soon as another SerialEvent on another port is triggered? Or will it complete the first SerialEvent routine before going to the second one?

The built in serialEvent() function on arduino only responds to serial port 0, called just "Serial" in the code. To respond to messages on "Serial1", use serialEvent1() on the Arduino Due there also exists serialEvent2() and so on.
EDIT: the serialEvent() handlers are not on interrupts; they run sequentially in-between loops. If the loop is blocking they do not get run, and they do not interrupt eachother.

I am aware of that. I meant that I intend to monitor the different serial ports with their respective SerialEventX instruction. But the same question remains: what is going to happen when, say, the SerialEvent1 function is being handled while on Serial2 a message arrives and SerialEvent2 is triggered?

They are not on interrupts, so nothing special happens.

That should be fairly simple to implement.
Each serial port has TX and RX interrupts. You just need to tie into the various interrupts.
Here is an example for a mbed, but it should be similar (both use ARM NVIC interrupt controllers).
To be clear, this wouldn't involve touching the serialEvent() function stuff at all, but rather implementing what it does using your own code.

If you set up your own interrupt handlers, you also get the benefit of being able to control interrupt priority yourself. The ATSAM3X has 16 interrupt priority levels, and a interrupt of a higher priority can pre-empt a lower-level interrupt.
I Strongly suggest you read the ATSAM3X datasheet. It describes the interrupt controller, as well as the rest of the processor peripherals.


text:
Sending wireless data over with xbee s1
I am following this tutorial to learn about Arduino wireless communication. I have 2 Arduino unos with Xbee S1s sitting on Xbee Pro shields.
I've programmed the Xbee S1s by screening into the /dev/tty/* and configuring them with: +++, ATID1234, ATMY1000 (ATMY1001), ATDL1001 (ATDL1000) and ATWR. I've double checked the values to ensure they are correct.
So i've created a super simple Sender and Receiver package:
Sender.ino
int counter = 0;

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

void loop() {
  Serial.println(counter++);
  delay(1000);
}

Receiver.ino:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Looping");
  while (Serial.available() == 0);    // wait
  int counter = Serial.parseInt();
  Serial.println(counter);
  Serial.flush();
  delay(500);
}

So first of all, when I upload my program to my arduino, I make sure that the S1s are not attached to the Pro shields which is attached to the unos.
When both of my unos are powered, I see a red light blinking but no indication of "busy blinking" which is supposed to happen when two XBee S1s are connected to the same channel. I am currently seeing a consistent blinking at about 1 second frequency.
Can someone tell me why I am only able to see "Looping" in my Serial monitor on my receiver?

So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned

Please add that as an answer, and accept your own question, if you solved it.

blah reported:

So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned.

Can someone vote this up please to remove it from the unanswered queue?


text:
Can the SPI pins of an Arduino be separated from SPI?
Are the SPI pins on the ICSP header of an Arduino Uno "separable" from the correspondent I/O pins - when one chooses to the use the ICSP header can the corresponding I/O pins be used for something else?

This is a user-level question, not about electrical engineering.

Pin assignment isn't about electrical engineering? That's quite a strict definition. While this could exist on the Arduino site, this is perfectly on topic for this site.

@AdamDavis Olin no doubt meant that anything with the word "Arduino" in it cannot be about electrical engineering. It may take him a decade or few to realise otherwise.

Where does it specify that Arduino.StackExchange is only about Arduino questions related to electrical engineering?  According the this page (http://arduino.stackexchange.com/tour) asking a question about the IDE is acceptable.   I don't think this SPI / pin question is off-topic at all.

@cbmeeks - the comments you responded to here were added to the question while it was at electronics.stackexchange.com, not here.

No.  Those pins are not separate on the microcontroller itself.  If you need to use SPI and still need more pins you may use analog inputs as digital inputs or outputs.  Otherwise you'll probably have to use an expander of some sort, or use a Mega or Due for additional inputs or outputs.

Actually, it can. You just can not use them at the same time. One needs to be careful to wire it in ways not to comprise the shared functions. Where MISO can be used as GPIO-INPUT and MOSI/SCK can be used as GPIO-OUTPUT, avoiding any pull up/downs, etc... As such electrical items may interfere with the ICSP.
For example I use the ICSP programming, along with the MISO, MOSI and SCLK pins as hard SPI and use them as Bit Bang one-wire, all on the same board and same wires. I simply ensure the SPI is properly configured each at each use.
One additionally needs to ensure that any peripherals on the shared SPI/ICSP lines are guaranteed to be in reset. Such as a pull down on such devices reset pins. Or a Pull Up on their ChipSelects. Noting that ATmega's GPIO pins are Hi-Z out of reset and during the ICSP.


text:
SRF04 Ultrasonic sensor - inaccurate readings
I have an Arduino Uno linked up to an SRF04 ultrasonic sensor. I'm using the library from here: https://code.google.com/p/srf04-library/
I'm then using the basic script "Centimeter" that comes in the examples. This gives me a reading, but it seems to be ~20-25% inaccurate. When it reads 100cm, the distance is actually nearer 80cm.
I've replaced the SRF04 with another, and the same issue occurs. Additionally, it seems when it reads out of range (or even on surfaces that give an uneven "bounce"), I get very random figures (e.g. -5cm).
Has anyone experienced something similar?

Have you used the setaverage method? If yes, what value did you use?

No, I didn't use it, just the default setting

Just don't use that library, it seems poorly designed.
Here is how the distance for roundtrip is calculated (code excerpts):
long sum = 0;
for (int i=0;i<_average;i++)
{
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    _duration = pulseIn(_echoPin, HIGH);
    sum=sum+_duration;
}
return(int(sum/_average));

If we remove the averaging stuff (as _average is 1 by default), this boils down to:
digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return int(pulseIn(_echoPin, HIGH));

pulseIn normally returns an unsigned long which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.
If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then pulseIn() should return:
3 x 2 / 340 x 1000000 = 17646 us

So far we don't see any particular problem, that's fine.
Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of 36ms will be sent by the sensor; in this situation, pulseIn() will return 36000us.
The problem here is that 36000 does not fit into an int (max value = 32767), the conversion to an int will change it into a negative value! That explains your strange negative outputs.
Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:
int DistanceSRF04::getDistanceCentimeter()
{
        return (getDistanceTime()/29/2);
}

The problem here is the int calculation, it should rather be performed as float. For a speed of sound of 340 m/s, one should divide the time of the echo in us by 29.4 (ie 1000000 / 340 / 100), not 29, that can make a difference in the final calculated distance!
If you want to go on using this library, then just forget about the getDistanceCentimeter()method and replace it with the following code:
distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

All calculation is then performed as float and converted to int distance only at the end.
Your code should also explicitly detect negative values as meaning "no object detected".

Thank you for your comprehensive answer. That makes things a lot clearer for me, both on the electronics and the physics side!

You wrote: “one should divide the time of the echo in us by 29.4 [...] not 29” Outdoors maybe. 29 is likely to be better at room temperature.

I am afraid you misunderstood my poitn: it was not 29 Vs. 29.4, but rather 29 (int) Vs. 29.4 (float). Could have been 29.0 as well. Now of course the speed of sound depends on many factors, not only pressure, but also temperature and humidity, but I would not want to enter into physics here (because it is a long time since I last went to school :-))

While BrettM discussed some excellent points that can occur with ultrasonic/sonar/'Ping' sensors I've noticed a few others when I have used these sensors.
The first and most common issue with sensors of this type is accurately identifying what is triggering the distance value. Consider at an abstract level how these work. You've got the bit that transmits a 'ping'. It transmits the 'ping' and stops. At this point the bit that listens for the 'pong' activates and starts listening. These sensors work by sending out that 'ping' and starting a timer, the first 'pong' the sensor hears triggers a stop response to the timer and distance is, roughly, figured out from here.  Notice that there is no way for the sensor to distinguish where the 'pong' is coming from. If you yodel on a mountain you don't know which surface echoed back and this is the same issue you are potentially facing with your sensor.
Typically when I work with people who are getting inaccurate readings from their sensors of the sort you are describing some variation of this issue is occurring. Often readings that are 'short' are so because there is an obstacle in the cone of the 'ping' that causes the sound to reflect back more quickly than expected for the surface you are measuring. Recall that sound is not a accurate,directed laser. Rather it spreads out in waves from the source. In my experience any objects within a roughly 160 degree arc(in my experience) in front of your sensor can cause these readings to be unusual. That can include the floor, your shoes, measuring devices. In theory the sensor is created to avoid these readings, in practice not so much.
To test if this is the case with your sensor setup I would recommend a few experiments. First setup the arduino and sensor in a fixed position and in such a way that the sensor is at the edge of a support surface with nothing but the surface you desire to measure in front of it. So, for example, set up the sensor on the very edge of a table facing a wall. Measure the distance from the wall to the support surface edge(table's edge). Some variation is normal, as described by BrettM, but 20% on 100 cm is a bit much in my experience. Once you get a solid, repeatable reading start changing the environment. Put something in the front arc of the sensor and see how that effects it. Move the sensor/support surface towards and away from the object. Typically when I see values like -5 that means something was too close to the sensor or, potentially, another sensor is interfering.
It is worth checking to confirm that there are no other range sensing devices in the area you are working within. Other devices sending out similar 'ping's can cause unusual readings(since they don't distinguish who's ping/pong is whose).

Thanks. I had done some testing as you describe, but the minus values threw me somewhat. Ill sort out a more accurate calculation then will proceed with further tests.

I can totally appreciate that. Ping sensors, what we called these sensors in my lab, are disgustingly noisy(as are most sensors honestly). They're certainly useful and valuable but there are so many things that can cause them to behave unexpectedly that data from them should always be suspect and filtered.

This is pretty standard. Altitude and air temperature will change the speed of sound enough to cause these errors, and minor variations in sensors could compound the problem. I would try calculating your own scale to convert ping time to distance using actual measurements from where you live; The library probably uses the speed of sound at sea level.
Similarly, any shape that poorly reflects or absorbs ultrasound will cause erroneous readings. There is really not much to do about this, sorry. If you have multiple sensors aimed a few degrees apart you are more likely to get one that will read the right distance.

In this case, the distance accuracy isn't so important - i'm trying to detect if someone walks by through two sensors, but it's useful to know the readings can be affected.

Distance is 25% more than expected, while the speed of sound is only 5% slower at 15,000ft (13% slower at 60,000ft). source.

That chart includes a temperature difference that would not be the case at room temperature at each altitude. Heating and AC systems also mess with pressure quite a bit. Add the 1% error coded into the library that jfpoilpret found and the variation in sensors, which I've seen be surprisingly large in other brands. Still, I agree the error is quite extreme; There may be some other unknowns.

This saved my project:
https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478?f
Please spread the word, I almost gave up. This gem seems widely unknown, I spent two full days in vain trying to improve my ultrasonic sensor's accuracy.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Have you got a satisfying answer to this question?
I'm having a same issue with my HC-SR04 sensor.
It's supposed to be mm-accurate, instead I'm getting ~30%+ off values.
E.g.) @ 30cm, the readout is ~40cm.
      @ 15cm, the readout is ~20cm.
This isn't exactly a "solution" but here's what I did.
For calculating distance, I divided by additional 1.25.

distance = (duration/2.0)/29.4/1.25

Now my readings look a lot more accurate(+/-0.5cm) within ranges of 0~30cm. And although it wasn't perfect, at 2m it read 202cm.
Not sure if this is sensor issue or Arduino issue... Maybe it's lacking power such that a portion of echo pulse is not being registered at Ardu as High. I'm running my board on USB 5V, which is in turn taken off raspberry Pi2.
Still, 25% is a huge discrepancy...
WOWOWOW OK I FOUND SOMETHING!
After writing that last paragraph, I connected Arduino to my PC (instead of RPi), uploaded the s/w without 1.25 factor, and the readings are correct! (more or less. NOT like +30% before)
So yeah, it's because of lack of power.
Hope this is the case with you as well, in which case we can finally put this issue down for good.

Very bad idea to solve an observed default of the library by adding a hard-coded constant that "seems" to compensate the default and has no scientific meaning at all. Rather change for a better library!

Yeah well if sensor was poorly manufactured and has a proportional offset, this is just about the only way to "fix" the problem. Luckily this wasn't the case!

The OP mentioned he had replaced the sensor with another one, without any effect, hence I would not consider the sensor faulty.


text:
Why voltage at AREF is given by Vin * R2 / Rtotal
In chapter 4 of Arduino Workshop on page 85 (or page 31 in the pdf) it says that the voltage at AREF in the schematic is given by:
Vin * R2 / (R2 + R1)
However, the voltage is flowing from 5V to Ground so isn't AREF actually in parallel with R1, and so shouldn't AREF be given by:
Vin * R1 / (R1 + R2) ?

You are correct.
$$V_{ref} = \dfrac{R_1}{R_1 + R_2} \cdot V_{CC}$$
or Vref = Vin * R1 / (R1 + R2) until we finally get MathJax enabled on this site.


text:
Can't send serial data throught serial pins but it works with the usb port
I am just starting out a project and I am having a little bit of trouble. I want to send data collected from an IR distance sensor, and send it with an XBee Pro S2B to my computer so I can do other stuff with it. The code I am using right now is pretty simple:
void setup()
{
  Serial.begin(9600);
}
void loop(){
 int distance = analogRead(0);
  Serial.println(distance);
  delay(1000);
}

The problem I am having is that when I turn on the arduino with batteries and disconnect the usb cable, the tx light stops turning on and no serial data is sended, AND if I connect it to the computer via USB again it won't work anyway, only works right when I upload the code. The XBees are configured correctly, I have done the chat example on the Building Wireless Sensor Networks by Robert Faludy.
Is it some code error? I must be really obvious.
By the way, when I upload the code and the serial data is sended throught usb, the data displayed on Arduino IDE's console is correct, so the sensor is wired correctly.
I am using an Arduino UNO and I have the XBee's and arduino's drivers installed correctly, and for the XBee I am using the XBee Explorer from Sparkfun

I have the same problem but in my design a supply both Arduino UNO board and XBEE module from a 1.5 A switched mode power supply.I noticed the LEDs on the XBEE module not on the UNO ARDUINO board and there is no blinking on TX or RX, so can any one help.

TX/RX LEDs do not blink when used on external power.

Upvoted, I am having the same issue. This is not a noob problem either. The bare Arduino Uno serial is not working when powered from a 12V bench supply from Vin when USB is not plugged in.

I suggest you try to flash the pin 13 LED in your loop().  It seems like the Arduino is not booting correctly on the batteries?
The serial port on the uno is kinda messy, it shouldn't really be shared with the usb port like that.  I prefer the Leonardo for these applications - where the USB serial and serial pins are totally independent.

The usb isn't intended to be used, only the pins, but only works when I upload the code and I haven't disconnected the cable. I am going to try that, will edit with the results

I just programmed it with a led flashing every second, and it works if I have the XBee disconnected, but once I plug the xbee the led starts flashing radomly very fast and no serial data is sent. I think is worth noting I am using the build-in led. Maybe it's because I am using the 5v output from the arduino to power the sensor AND the 3v3 for the XBee?

What batteries are you using?  It sounds like the Xbee is drawing too much power - you might need to move to bigger batteries.  Another way of testing would be to power the Arduino with a plug pack on the barrel connector (saves batteries until you're ready to go mobile).

I guess you're dropping down the 5V to make the 3.3v using a regulator?

"The serial port on the uno is kinda messy, it shouldn't really be shared with the usb port like that." this is a comment on the electrical design of the Arduino, not on how you are using it.

I am using 4 standard AA non-rechargeable 1.5v batteries, with a barrel jack conector. And for the sensor I am using the 5v output on the power section of the pins and for the xbee I am using the 3v3 output. This may be the most .... question ever, but those pins are outputs right? I have always thought so and I thought that the arduino had another regulator for the 3v3 output. I just tried disconnecting the XBee from the 3v3 output and the LED worked correctly, no idea of the serial data but the TX led isn't lighting up

This is the beauty of open hardware, we have the schematic - http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf  The 3.3v pin using an LM2985 regulator that can only supply 150mA, I don't think it is powerful enough for an xbee.  From http://www.digi.com/products/wireless-wired-embedded-solutions/zigbee-rf-modules/zigbee-mesh-module/xbee-zb-module the pro need 205mA, you should switch to the ZB, it needs only 40mA (or add a separate 3.3v power supply).  Until you sort out the power, the system won't behave predictably.

So I guess what I can split the output from the battery pack and use one part to power the arduino and the sensor and the other part to a 3v3 regulator with larger output? Or would I have another problem? Would I need to have 2 battery packs?

@TomKeddie the 3.3 regulator is sufficient alone, as I've seen it used several times on the Arduino Uno without any external regulators. Also, the Uno's serial port isn't messy at all. The Leonardo has two: one directly connected to the computer and the other one connected to pins 0/1, where the Uno has the computer also connected to 0/1. You can only use the pins OR the computer at a time. That's not "messy," just a limitation.

@"Annonomus Penguin"  With an xbee pro, the math above is fairly clear.  "Also, the Uno's serial port isn't messy at all."  You drive one input with two outputs (RX from ATMEGA and RX from shield) that is indeed messy, but it is not the issue here.

"So I guess what I can split the output from the battery pack and use one part to power the arduino and the sensor and the other part to a 3v3 regulator with larger output?"  I think so unfortunately (unless you can drop to the lower power xbee).  Do you have a 3.3V source you can use to power the Xbee temporarily to verify this is the problem?

You have an XBee shield on top of the Arduino UNO?
Do you have an XBee attached to the computer?
Can you describe your setup a little more.
The TX Led on the Arduino is only on the USB side, and doesn't signify TX on the XBee. The XBee itself should/could have a TX/RX leds itself. Check the Arduino schematic to confirm this.
How are you reading the Serial on the computer? Thru the Arduino serial monitor? That won't work for the XBee. You'll need another Serial monitor for the XBee attached to the computer. ie, Arduino with XBee shield. Then an XBee connected via some breakout board to the computer. The Arduino Serial monitor won't see the XBee (use hyperterm on windows or some serial port monitor on other systems).
Also, check your switch on the XBee (if you have one), most redirect the USB/Serial connection between computer/Arduino and Arduino/XBee. It's one or the other not both.

I am sorry for not clarifying a bit more in the initial question, I thought this was something simple. I am not using a shield, only a XBee explorer with pins soldered to it, and I am reading the output with CoolTerm. And I didn't know that about the TX light only working for USB... So: XBee connected to arduino via an XBee explorer with pins soldered, and the receiving XBee connected to the computer via USB using another XBee explorer. Coolterm is configured correctly, I know that because I have used the xbee to do a chat between 2 computers, and the XBees themselves are configured correctly.

Try interchanging the Tx-Rx pins of your XBee-Arduino connection.
Since you are getting correct values on the Arduino IDE, this means that both sensor and serial is working, but it sends values only when connected via USB which means that problem lies in your link between Arduino-Serial Device (in this case XBee)

Ok, I have verified this behavior with a bare Uno on an external power supply driven from Vin.
The serial is outputting, but because of the way the TX and RX LEDs are wired in the Uno, they do not activate unless the USB processor is active.
This is super dumb and super confusing, but you can clearly see it's wired up this way:

I have confirmed that serial data is coming out of the Arduino with a logic analyzer, but the LEDs do not light up.

It's not super dumb. Putting an LED and its resistor on a couple of pins would alter the behaviour of those pins if they were used for something else (eg. input). On the earlier Arduino Unos they had an LED on pin 13, now it is driven by an op-amp to try to reduce this problem.

Yes, I think I would advocate for a dual comparator, or even a couple of transistors on the lines! I suppose it could be an already-fixed firmware problem with the Uno, but I haven't had time to get the DFU tools to find out.

And yes, by oversight or design, I maintain that the Tx and Rx LEDs not lighting is "super dumb and confusing"

Finally found out how to get the Arduino Uno serial port to work without a USB cable! I used a scope to see what was going on and found that using an external power supply on the Arduino power port only showed +3.3 volts on the +5 line. I pulled the plug on the external power supply and put a regulated +5 VDC on the +5 VDC pin.  Now, both software serial and the UART ports work fine - hope this helps!


text:
Direct 5V current based on analog signal
I would like to manage many LEDs from my Arduino - 12 or so - but I do not have the available digital pins to do this. Only one LED needs to be on at one time. Instead, I was hoping to control these with an analog pin. I was wondering if there is some sort of switch out there which can take an analog signal and, based on the value, direct a 5V current to a certain LED.
I realize that I could use a second Arduino for this, but I am trying to avoid that.
Thanks in advance for any help!

Please check out this question: http://arduino.stackexchange.com/questions/117/is-there-a-way-to-have-more-than-14-output-pins-on-arduino it contains many answers enumerating several different solutions to the problem.

It should be noted that analog input pins still only output digital signals; only the PWM capable pins can emulate analog signals and they are dispersed among the digital pins.

You can accomplish this digitally with a device called a decoder. For example, the 74154 takes 4 inputs and maps those to one of 16 outputs (depending on the binary coding of the inputs). From the data sheet:

The 74HC154; 74HCT154 decoders accept four active HIGH binary address inputs and
  provide 16 mutually-exclusive active LOW outputs.

Great! I found even better results by searching for "demuliplexer". For instance, this page on the arduino site: http://playground.arduino.cc/Learning/4051 Thanks!

If you have 4 pins available, you could use charlieplexing to selectively light up 12 led.

Alternatively you could use some IC. You could use the one Greg suggested.
Or you could use a shift-register. This requires only 2 or 3 pins, an will enable you to light up any one or more leds at the same time. Most have 8 outputs, but you can connect one to the other (daisychain), so with 2 shift-registers you can individually turn on/off 16 leds. You can easily control these using arduino's shiftOut command.
You could also use a port-expander using I2C to talk to it. More complicated, and a bit more expansive. But also more powerful. It will require only 2 pins (A4, and A5).

You can use some of the analog pins to clock a shift register by defining them as a digital output.  Also two of the analog pins are also defined as I2C depending on your code. You could use 2 PCF8574s or an PCF8575 expansion board and control it that way. They can be used as inputs and outputs any order you want. There are a lot of other chips you can use to do this.  The reason I am suggesting this approach is later you will probably want to expand into other peripherals such as LCDs etc.


text:
splitable jumper wires question
I just received my starter kit from oddwires.com today and it came with a split-able ribbon cable for prototyping. I was curious if it is possible to split each wire off and use only what I need to for the tutorials or is that a bad idea? I am very excited to start playing around and learning this as it has been a interest of mine for many years.

Which starter kit? None of the ones under "oddWires Kits for Arduino" has (or shows) a ribbon cable.

the uno deluxe, but they called it "Perfect premium jumper wire pack - combinations female/male, male/male in 6"/10" lengths (40 wires)". This is what was sent to me though link

Each wire in the Dupont ribbon cable is is independent, and does not hold onto its neighbors with any real force. You can split them or join multiple wires together using larger connectors as desired.

Okay I didn't want to accidentally damage anything before I had a chance to use it. (I would hit the checkmark, but I am sure my rep isn't high enough)


text:
Arduino Micro just blinks, won't connect to PC
Edit - Sorry it's a Micro not a Nano
I have a Micro board hooked up to an EasyDriver breakout using its 5V output to power the Micro.
Today I plugged it in and instead of booting up like normal the power LEDs on the wall plug, the easy driver, and the Arduino started flashing. The Micro became very hot, but not hot enough to burn.
After that if I plug the Micro into the USB port it just rapidly blinks the pin 13 LED. The PC does not detect the device but it does receive power.
Holding or pushing the reset button doesn't seem to help at all. I've used different USB cables, and different ports on the PC as well to no effect.
Is this something it can recover from? Why did all the LEDs blink like that?

expand on the "wont connect to pc" part please

@sachleen Oh sorry, I meant to say that the PC does not detect any new devices when it's plugged in, but it does receive power.

How did you hook up the 5V power from the breakout, to the Nano? Did you use the Vin, 5V or 3V3? If incorrectly connected, you might have damages the voltage regulator.

@Gerben It was hooked up to the VIN pin on the arduino. Also I just looked at the printed board and realized that this is a Micro not a nano. Woops.

Try looking on the device manager (if your on windows) to see if it shows up in any state. If you find it, right click the icon for the device, and try updating the drivers for it. It has worked for me.

I have had a similar problem, on a Pro Micro, and the PC, in the end, could not see it, and it would not show up in Device Manager. It was, to all intents and purposes, bricked.

It could be just a question of timing the double resetting of the Micro correctly, in order to enter bootloader mode, see Pro Micro & Fio V3 Hookup Guide - Troubleshooting and FAQ - Reset to Bootloader:

While the Micro is in Bootloader mode, you should see it appear in Device Manager like so:

While it is temporarily in this bootloader mode, you should be able to upload a new sketch.

However, this did not work for me and I ended up having to burn the bootloader again, via ISP, using either a USBasp or an Arduino Uno configured as an ISP.
After a number of attempts the apparently bricked Pro Micro showed up again in Device Manager, and became fully functional:

After that, all that was required was to install the correct Windows drivers, to get rid of the yellow warning icon.  From Pro Micro & Fio V3 Hookup Guide – Installing: Windows, obtain the zip file Arduino_Boards-Master.zip. Then selecting the Pro Micro in Windows Device Manager, right click and “Update Driver Software”, following these instructions, from the link:

Unzip that zip file, and don’t forget where you’ve left its contents.
  In that zip file, you should find an INF file, which contains all the
  information Windows needs to install the Pro Micro’s driver. This
  sparkfun.inf will be found in Arduino_Boards-master → sparkfun → avr →
  signed_driver.

Once the driver was installed, then the Pro Micro should appear correctly in Device Manager

If you haven't already done so, add the following URL to the Board Manager line in the Preferences dialog in the Arduino IDE:
https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

Then opening the “Board Manager…” in the Tools/Boards menu, search for the “SparkFun AVR Boards” package and install it.

I have written two lengthy blogs about the whole experience:

The case of the broken Pro Micro
The case of the broken Pro Micro (reprise)

This seems a bit confused.  ATmega chips can handle 5v supply just fine; what makes a board  3.3v board is that either on an-board regulator or an off-board supply powers the chip with a lower voltage.  Run it on 5v instead and the ATmega will not be damaged, it will just be an ATmega running in spec at 5v...  Signals in excess of the supply voltage by more than a diode drop can indeed damage an ATmega (or many other parts) but that does not appear to be what the user is asking about.

I have something similar happen a couple of times with some atmega328s (on arduino unos). I believe it was the bootloader that some how became corrupted and so no longer responded to the computer. The only way to fix this is to reflash the bootloader using an ISP programmer. Luckily the arduino can act as an ISP programmer so all you need is another working arduino.
See https://www.arduino.cc/en/Tutorial/ArduinoISP for how to do this on an uno. The same can be done with the micro/nano as they all use the same atmega328p chip its just a matter of wiring it up correctly.
If you cannot reflash the bootloader with this method then one of the chips is probably damaged and would need to be replaced. At this point it might be easier to replace the whole board.

I've had the same problem. I fixed it through a series of resets (removing the serial cable and plugging it in again), and punching 'make upload' a few times. Eventually it accepted my upload. The problem was an invalid code upload, which caused the Arduino to reset QUICKLY after booting. As an alternative, had this not worked, I would have blanked the chip with a USBtinyISP - it will hook up easily to your Arduino.

I had similar problem to Yours. Actually I tried to run my program in Clion IDE and then something broke in Arduino. I connected my Arduino Leonardo to my second PC clicked 2 times reset button and while the Bootloader COM appeared i fastly ran blink program.
(What is important that it wasnt one trial to run this blink program so i recommend to do it 5-10times if it doesnt work).


text:
Arduino Ethernet Shield connection to PC
is it possible to connect Arduino Ethernet Shield direct to PC and send a String variable? How can I read it later on the PC?
Will this code work?
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // Shield MAC

byte pc[] = "192.168.0.13"; // pc IP
EthernetClient client;

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

  Serial.println("connecting...");

  delay(5000);
  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("Sample String");
    client.println();
  } else {
    Serial.println("connection failed");
  }

}

void loop()
{

}

No, you seem to be off on a tangent. There at least two problems:

The Ethernet library is designed to run on an Arduino board. If you set the IP address to the same as the PC IP address, the network will get confused and nothing will work reliably.
Are you asking how one can publish data from an Arduino board and read the results on a PC? This is easier. Just set up the web server example on the Arduino, and access it from a browser on your PC.


text:
Keyboardmessage on Arduino UNO
Can an Arduino UNO and Arduino Leonardo do the same things?
Some of the examples in the Arduino software say to use Leonardo e.g. KeyboardMessage.

No, the Uno and the Leonardo cannot do the same thing.  The Leonardo is a single MCU directly connected to the USB port. It is down to the software on that MCU as to how it communicates (what it enumerates as) on the USB bus.
The Uno, conversely, is a dual MCU system. It has the "main" MCU (the ATMega328P) which is what you program, and that communicates to the USB port via another MCU.  The two MCUs are connected using TTL RS-232 (UART), so the only communication you have with your computer is through the Serial object.
There are benefits and problems with both approaches.  The benefits of the Leonardo are that you can emulate keyboards, mice, etc.  The down side is that the whole USB communication is more fragile and is at the mercy of the user.  The Uno's benefits are that the USB serial is always connected and available regardless of the state of the main MCU, which is much more friendly from the PC's point of view.  The down side is that it severely limits your communication options.

Yes you can, but not with that library. This method is a little advanced and requires you to upgrade a different type of firmware to your second MCU on your Uno.
(The full tutorial is available here)
Example code from the tutorial link shown above (for process outlined below):
uint8_t buf[8] = {
  0 };  /* Keyboard report buffer */

void setup()
{
  Serial.begin(9600);
  randomSeed(analogRead(0));
  delay(200);
}

void loop()
{
  int randomChar = random(4, 130);
  long randomDelay = random(1000, 10000);

  delay(randomDelay);

  buf[2] = randomChar;    // Random character
  Serial.write(buf, 8); // Send keypress
  releaseKey();
}

void releaseKey()
{
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8); // Release key
}

Here's what you need to do:

Get a DFU programmer

Windows: Download Atmel's flip programmer from here http://www.atmel.com/tools/flip.aspx
Mac: Install MacPorts following these instructions: http://www.macports.org/install.php#pkg Once MacPorts is installed, in a Terminal window, type sudo port install dfu-programmer
Linux: from a command line type sudo apt-get install dfu-programmer or sudo aptitude install dfu-programmer depending on your distribution

(Source: http://arduino.cc/en/Hacking/DFUProgramming8U2)
Download the Keyboard LUFA firmware
You'll have to solder a resistor on a non-SMD Uno (that's outlined in the Arduino link in the second step)
Connect the Uno to your comptuer and reset the 8u2 (short the farthest left pair of metal contacts in the upper left hand corner of the Uno)
Upload the firmware using the GUI in flip, OR for Mac/Linux go to the directory where the firmware is using the terminal then:

Type this line (Still, Mac or Linux only):
sudo dfu-programmer at90usb82 erase
sudo dfu-programmer at90usb82 flash [Replace-this-with-file-name].hex
sudo dfu-programmer at90usb82 reset

Unplug/plug in your board and enjoy! Note: you'll have to flash the standard firmware to upload a new sketch and the flash the keyboard firmware again to get this to work.


text:
No usb serial on Mac
I've been using my Arduino UNO without a hith for a few days now, but suddenly I can't program it anymore.
When I try to programm my Arduino on Mac, I get the following Error:
avrdude: stk500_recv(): programmer is not responding

The USB option under serial port has disappeard (It was there before). Has anyone an idea on how to fix this?
The last thing I did is use the serial port for some communication. A reboot hasn't improved anything.
I tried programming Linux, but it resulted in the exact same result.

Related: http://arduino.stackexchange.com/questions/804/arduino-nano-uploading-gives-error-avrdude-stk500-recv-programmer-is-not-re Does that solve your issue? What board are you using?

No is doesn't solve the problem. Besides that: I use an original Arduino Uno.

On Linux go to computer>var>lock and delete the  serial port lock files

It seemed to be a hardware problem on the board. Thanks for the effort.

You could try re-flashing the firmware for the usb-to-serial chip (atmega8u2) on the uno board.

If I try to upload with no device connected, I get a dialog with the message "port is blocked" and a message in Eclipse's console window that the port is not found.
So I'm guessing you've got a sync problem. UNO should reset automatically when avrdude connects. Try manually resetting it just before you click to start the download. If that works, then the automatic reset has failed.

If I try to upload with no device connected, I still get: "avrdude: stk500_recv(): programmer is not responding"


text:
7 Segment Display SET UP
I am new to Arduino.
I have been trying to connect a 7 segment display (3 digits) to my Arduino and I was successful, but I am not doing any connection to ground. I do not find the data sheet so I am not sure if this connection is well done.
My doubt is: Is the connection to ground necessary? Or how do Arduino pins work? I am using 12 pins of the Uno to do the set up.
Thanks
My set up is the following:

Is the display common anode or common cathode?

To tell you truth @IgnacioVazquez-Abrams, I really don't know. How can I verify this? is there any special annotation on the device? or any special behavior?

Which pins control which display lights up and which ones control the segments, and which one do you have to apply the positive voltage to? (Also, your pin notation is incorrect; pin 1 is at the bottom left and they go up counter-clockwise.)

Great, thanks for the help and for the correction on my notation. Tomorrow I will keep posting the things you are requesting once I verify on the Arduino how the display is working.

Could you give a reference to the LED display? That would help check out the wiring. Also, have you already written a sketch to drive the display? Posting it here would help as well.

One danger I see in your circuit is that it seems you are driving at least 7 LED segments at the same time (by the way, why do you need 12 pins to drive 3 digits of 7 segments? 11 should be enough, considering there is also a decimal point to drive: (7+1) x 3). That might draw too much current out of the Arduino and fry it.

I second @jfpoilpret. The pins on the arduino can only provide/sink 40mA of current. I also see you added the resistors to the digits instead of the segments. That way, the more segments are on, the dimmer the display will be. It's better to put the resistors on the segments. Also use a resistor value that will limit the current to no more than 5mA per segment. That way, even if all segments are lit, the total current will be below 40mA.

I don't know exactly how your display is wired exactly, but it is certain that some sort of multiplexing is going on, since A: there is no wired ground, and B, you are controlling more LED's than you have pins going to the display.
Multiplexing manages this by using some trickery and persistence of vision. The pins for each part of the segment are all wired together. For example, the top segment on each of the three segments are all connected to one arduino pin. The common anode/cathode (depending on your specific display) for each of your three displays are wired separately however. Turning only one of the common pins on will cause only one display to function when the other pins set which segments are on. The micro controller then changes which common is active and what segments are on to illuminate the next character very quickly. It pulses between segments so quickly you cannot tell they are only on one third of the time each.
The wiring inside the display will likely look similar to this:
http://www.modd3d.com/articles/wp-content/uploads/normal-multiplexing-s.gif


text:
Does millis() conflict with the PWM pins associated with timer 0?
I've read that the millis() function uses the same timer as a couple of PWM pins.
If you're using those PWM pins, will millis() still return the correct value?

They do not conflict as millis() strictly reads the immediate value in TCNT0 whereas PWM via timer 0 uses the hardware's ability to compare the value of TCNT0 with the values in OCR0x without affecting the value of any of them.

millis() just uses Timer 0 overflow counts. micros() reads the immediate value in TCNT0.

Just to add to @Ignacio's answer which has directly answered your question. The "conflict" you speak of is in relation to Timer0's prescaler.
For the most part, you can use those pins (incidentally pins 5 and 6 on the UNO) with PWM without an issue, and read the correct value of millis() (as well as get the expected delay from delay)
Where you run into problems is if you want to change the prescaler (usually to modify the frequency of the PWM signal). If you change this, then you directly affect the calculation and reporting of millis() and the length of delay(x).

You can read your timer's prescaler by the bottom bits of Serial.println(TCCR0A,BIN);  If they are '11' then your prescaler is clk/64.  You could then calculate the factor for modifying millis() and delay().

That's a very good point and I've always just steered clear of modifying it, but there's no reason if you really want/need to. The other point is that if you've modified it you already know the new prescaler and could in turn write wrappers for millis () or delay () anyway


text:
How to use String.substring?
I have the following code in which requestLine is always empty and I can't figure out why. request contains a raw HTTP request, and I want to get the first line of the request which contains the method and the URL.
boolean parseRequest(String* request)
{
  int firstEOLAt = request->indexOf('\n');
  if (firstEOLAt < 0)
    return false;
  Serial.println(firstEOLAt);
  String requestLine = request->substring(0, firstEOLAt);
  Serial.println(requestLine);
  // ...rest of the parsing will go here...
  return true;
}

The first println returns 26 as you would expect for the string "GET /ilyen_nincs HTTP/1.1" (25 characters long), but then requestLine is always empty. I wonder why?

GET /ilyen_nincs HTTP/1.1\n is 26 characters long so string indices are from 0 to 25. Since, your second argument in substring(0, firstEOLAt); exceeds the end index of the string, you are running into unexpected behavior as per the documentation and getting an empty string.

Caution: make sure your index values are within the String's length or you'll get unpredictable results. This kind of error can be particularly hard to find with the second instance of substring() if the starting position is less than the String's length, but the ending position isn't.