text:
How to write RFID data using the RFID-RC522 chip
I have got this library+code example from a friend, to read RFID numbers using the RFID-RC522 chip:
RFID.ino
#include <RFID.h>
#include <SPI.h>

/**
* RFID pins
* MOSI: Pin 11 / ICSP-4
* MISO: Pin 12 / ICSP-1
* SCK: Pin 13 / ISCP-3
* SS: Pin 10
* RST: Pin 9
*/

RFID rfid(10, 9);
unsigned char prevNum[] = {0,0,0,0,0};

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
    if (rfid.isCard()){
        if (rfid.readCardSerial() && (
            rfid.serNum[0] != prevNum[0]
         or rfid.serNum[1] != prevNum[1]
         or rfid.serNum[2] != prevNum[2]
         or rfid.serNum[3] != prevNum[3]
         or rfid.serNum[4] != prevNum[4]
        )){
          Serial.println(rfid.serNum[0]);
          Serial.println(rfid.serNum[1]);
          Serial.println(rfid.serNum[2]);
          Serial.println(rfid.serNum[3]);
          Serial.println(rfid.serNum[4]);

          prevNum[0] = rfid.serNum[0];
          prevNum[1] = rfid.serNum[1];
          prevNum[2] = rfid.serNum[2];
          prevNum[3] = rfid.serNum[3];
          prevNum[4] = rfid.serNum[4];
        }
    }
}

RFID.h
/* RFID.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
 * Created by Miguel Balboa (circuitito.com), Jan, 2012.
 */
#ifndef RFID_h
#define RFID_h

#include <Arduino.h>
#include <SPI.h>

/******************************************************************************
 * Definitions
 ******************************************************************************/
#define MAX_LEN 16   // Largo m�ximo de la matriz

//MF522 comando palabra
#define PCD_IDLE              0x00               // NO action; Y cancelar el comando
#define PCD_AUTHENT           0x0E               // autenticaci�n de clave
#define PCD_RECEIVE           0x08               // recepci�n de datos
#define PCD_TRANSMIT          0x04               // Enviar datos
#define PCD_TRANSCEIVE        0x0C               // Enviar y recibir datos
#define PCD_RESETPHASE        0x0F               // reajustar
#define PCD_CALCCRC           0x03               // CRC calcular

//Mifare_One  Tarjeta Mifare_One comando palabra
#define PICC_REQIDL           0x26               // �rea de la antena no est� tratando de entrar en el estado de reposo
#define PICC_REQALL           0x52               // Todas las cartas para encontrar el �rea de la antena
#define PICC_ANTICOLL         0x93               // anti-colisi�n
#define PICC_SElECTTAG        0x93               // elecci�n de tarjeta
#define PICC_AUTHENT1A        0x60               // verificaci�n key A
#define PICC_AUTHENT1B        0x61               // verificaci�n Key B
#define PICC_READ             0x30               // leer bloque
#define PICC_WRITE            0xA0               // Escribir en el bloque
#define PICC_DECREMENT        0xC0               // cargo
#define PICC_INCREMENT        0xC1               // recargar
#define PICC_RESTORE          0xC2               // Transferencia de datos de bloque de buffer
#define PICC_TRANSFER         0xB0               // Guardar los datos en el b�fer
#define PICC_HALT             0x50               // inactividad

//MF522 C�digo de error de comunicaci�n cuando regres�
#define MI_OK                 0
#define MI_NOTAGERR           1
#define MI_ERR                2

//------------------ MFRC522 registro---------------
//Page 0:Command and Status
#define     Reserved00            0x00
#define     CommandReg            0x01
#define     CommIEnReg            0x02
#define     DivlEnReg             0x03
#define     CommIrqReg            0x04
#define     DivIrqReg             0x05
#define     ErrorReg              0x06
#define     Status1Reg            0x07
#define     Status2Reg            0x08
#define     FIFODataReg           0x09
#define     FIFOLevelReg          0x0A
#define     WaterLevelReg         0x0B
#define     ControlReg            0x0C
#define     BitFramingReg         0x0D
#define     CollReg               0x0E
#define     Reserved01            0x0F
//Page 1:Command
#define     Reserved10            0x10
#define     ModeReg               0x11
#define     TxModeReg             0x12
#define     RxModeReg             0x13
#define     TxControlReg          0x14
#define     TxAutoReg             0x15
#define     TxSelReg              0x16
#define     RxSelReg              0x17
#define     RxThresholdReg        0x18
#define     DemodReg              0x19
#define     Reserved11            0x1A
#define     Reserved12            0x1B
#define     MifareReg             0x1C
#define     Reserved13            0x1D
#define     Reserved14            0x1E
#define     SerialSpeedReg        0x1F
//Page 2:CFG
#define     Reserved20            0x20
#define     CRCResultRegM         0x21
#define     CRCResultRegL         0x22
#define     Reserved21            0x23
#define     ModWidthReg           0x24
#define     Reserved22            0x25
#define     RFCfgReg              0x26
#define     GsNReg                0x27
#define     CWGsPReg              0x28
#define     ModGsPReg             0x29
#define     TModeReg              0x2A
#define     TPrescalerReg         0x2B
#define     TReloadRegH           0x2C
#define     TReloadRegL           0x2D
#define     TCounterValueRegH     0x2E
#define     TCounterValueRegL     0x2F
//Page 3:TestRegister
#define     Reserved30            0x30
#define     TestSel1Reg           0x31
#define     TestSel2Reg           0x32
#define     TestPinEnReg          0x33
#define     TestPinValueReg       0x34
#define     TestBusReg            0x35
#define     AutoTestReg           0x36
#define     VersionReg            0x37
#define     AnalogTestReg         0x38
#define     TestDAC1Reg           0x39
#define     TestDAC2Reg           0x3A
#define     TestADCReg            0x3B
#define     Reserved31            0x3C
#define     Reserved32            0x3D
#define     Reserved33            0x3E
#define     Reserved34                0x3F
//-----------------------------------------------

class RFID
{
  public:
    RFID(int chipSelectPin, int NRSTPD);

    bool isCard();
    bool readCardSerial();

    void init();
    void reset();
    void writeMFRC522(unsigned char addr, unsigned char val);
    void antennaOn(void);
    unsigned char readMFRC522(unsigned char addr);
    void setBitMask(unsigned char reg, unsigned char mask);
    void clearBitMask(unsigned char reg, unsigned char mask);
    void calculateCRC(unsigned char *pIndata, unsigned char len, unsigned char *pOutData);
    unsigned char MFRC522Request(unsigned char reqMode, unsigned char *TagType);
    unsigned char MFRC522ToCard(unsigned char command, unsigned char *sendData, unsigned char sendLen, unsigned char *backData, unsigned int *backLen);
    unsigned char anticoll(unsigned char *serNum);
    unsigned char auth(unsigned char authMode, unsigned char BlockAddr, unsigned char *Sectorkey, unsigned char *serNum);
    unsigned char read(unsigned char blockAddr, unsigned char *recvData);
    unsigned char write(unsigned char blockAddr, unsigned char *writeData);
    void halt();

    unsigned char serNum[5];       // Constante para guardar el numero de serie leido.
    unsigned char AserNum[5];      // Constante para guardar el numero d serie de la secion actual.

  private:
    int _chipSelectPin;
    int _NRSTPD;

};

#endif

Using the code I have now I can read RFID data, and read them via the Serial monitor.
Now, if I want to write RFID numbers to a card, can I do this with this library, or what other library should I use that is capable of writing?

The library you refer to is called RFID by Miguel Balboa.
It is equipped with several examples showing you how to read and write data. Check them out.
If you are looking for some more background information on what happens when you write data on a tag, check out the first video of of the MakeCourse of the University of South Florida.
At 21:30 it explains how to write data.


text:
Why is SoftwareSerial causing arduino to reboot?
I'm trying to design an RC controller using an Arduino and an XBee Series 2 Pro. I have the hardware serial running for debug information and I want the XBee to be connected to a soft serial on pins 8 and 9.
My arduino keeps restarting, or at least the setup function keeps looping, every time I try to send data through the XBee. If I modify the code so the XBee runs on the hard serial, the program works, but I would rather not have that setup because then to load new code onto the arduino I have to open the controller and disconnect the XBee.
I tried changing the pins that the soft serial runs on and that makes no difference, nor does unplugging the power to the XBee but leaving the serial connections in. I also tried to write another pin high to make sure there's enough current, and that didn't cause a restart.
My arduino is connected to the XBee, 4 potentiometers, and 1 switch.
#include <XBee.h>
#include <SoftwareSerial.h>

#define NOTE_A3  220
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330

#define THR_JOYSTICK A0
#define YAW_JOYSTICK A1
#define RL_JOYSTICK A2
#define FB_JOYSTICK A3
#define POT A4
#define TOGGLE 4
#define SPEAKER_PIN 3
//#define WAKE_PIN 10

#define YAW_MIN 0
#define YAW_OFFSET 386
#define YAW_MAX 815

#define RL_MIN 0
#define RL_OFFSET 359
#define RL_MAX 800

#define FB_MIN 0
#define FB_OFFSET 355
#define FB_MAX 795

#define THR_MIN 0
#define THR_OFFSET 0
#define THR_MAX 754

const int ESC_MIN = 764;
const int ESC_OFFSET = 1500;
const int ESC_MAX = 2000;

XBee xbee = XBee();
SoftwareSerial nss(13,12);
uint8_t payload[10];
// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40c67584);
ZBTxRequest packet = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

void setup() {
  //start serials
  Serial.begin(9600);
  nss.begin(9600);
  xbee.setSerial(nss);

  //pin modes
  pinMode(THR_JOYSTICK,INPUT);
  pinMode(YAW_JOYSTICK,INPUT);
  pinMode(RL_JOYSTICK,INPUT);
  pinMode(FB_JOYSTICK,INPUT);
  pinMode(POT,INPUT);
  pinMode(TOGGLE,INPUT);
  pinMode(SPEAKER_PIN,OUTPUT);

  //delay to allow inputs to settle
  delay(1000);

  //the speaker will need a total resistance of at least 125 Ohm
  //so if it's an 8 Ohm speaker, an additional 117 is needed etc...

   //calibrate THR
  int first = millis();
  tone(SPEAKER_PIN,NOTE_A3);
  int reading = analogRead(THR_JOYSTICK);
  while(reading > THR_OFFSET + 5 || reading < THR_OFFSET - 5) {
    delay(20);
    reading = analogRead(THR_JOYSTICK);
  }
  int dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate YAW
  first = millis();
  tone(SPEAKER_PIN,NOTE_B3);
  reading = analogRead(YAW_JOYSTICK);
  while(reading > YAW_OFFSET + 5 || reading < YAW_OFFSET - 5) {
    delay(20);
    reading = analogRead(YAW_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate FB
  first = millis();
  tone(SPEAKER_PIN,NOTE_C4);
  reading = analogRead(FB_JOYSTICK);
  while(reading > FB_OFFSET + 5 || reading < FB_OFFSET - 5) {
    delay(20);
    reading = analogRead(FB_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate RL
  first = millis();
  tone(SPEAKER_PIN,NOTE_D4);
  reading = analogRead(RL_JOYSTICK);
  while(reading > RL_OFFSET + 5 || reading < RL_OFFSET - 5) {
    delay(20);
    reading = analogRead(RL_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //done
  tone(SPEAKER_PIN,NOTE_E4);
  delay(200);
  noTone(SPEAKER_PIN);
  delay(15);
  tone(SPEAKER_PIN,NOTE_E4);
  delay(200);
  noTone(SPEAKER_PIN);
  delay(15);
  tone(SPEAKER_PIN,NOTE_E4);
  delay(350);
  noTone(SPEAKER_PIN);
}

void loop() {
  int POTReading = analogRead(POT);
  int toggle = digitalRead(TOGGLE);

  int throttleValue = mapLimit(analogRead(THR_JOYSTICK) - THR_OFFSET,THR_MIN,THR_MAX - THR_OFFSET,0,ESC_OFFSET);
  int yawValue = mapLimit(analogRead(YAW_JOYSTICK),YAW_MIN,YAW_MAX,ESC_OFFSET-ESC_MAX,ESC_MAX - ESC_OFFSET);
  int rightLeftValue = mapLimit(analogRead(RL_JOYSTICK) - RL_OFFSET,RL_MIN,RL_MAX - RL_OFFSET,0,ESC_MAX - ESC_OFFSET);
  int frontBackValue = mapLimit(analogRead(FB_JOYSTICK) - FB_OFFSET,FB_MIN,FB_MAX - FB_OFFSET,0,ESC_MAX - ESC_OFFSET);
  int potValue = analogRead(POT);
  int toggleValue = digitalRead(toggle);

  //throttle
  payload[0] = throttleValue >> 8 & 0xff;
  payload[1] = throttleValue & 0xff;
  //yaw
  payload[2] = yawValue >> 8 & 0xff;
  payload[3] = yawValue & 0xff;
  //RL
  payload[4] = rightLeftValue >> 8 & 0xff;
  payload[5] = rightLeftValue & 0xff;
  //FB
  payload[6] = frontBackValue >> 8 & 0xff;
  payload[7] = frontBackValue & 0xff;
  //Pot
  payload[8] = potValue >> 8 & 0xff;
  payload[9] = potValue & 0xff;
  //toggle
  payload[10] = (byte) toggleValue;

  //wake XBee
  //digitalWrite(WAKE_PIN,LOW);
  xbee.send(packet);
   if(xbee.readPacket(500)) {
     if(xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
       xbee.getResponse().getZBTxStatusResponse(txStatus);
       if(txStatus.getDeliveryStatus() != SUCCESS) {
         //the remote XBee didn't ACK
         tone(SPEAKER_PIN,NOTE_C4,100);
       }
     }
   } else {
     //error or something
     tone(SPEAKER_PIN,NOTE_E4);
     noTone(SPEAKER_PIN);
     tone(SPEAKER_PIN,NOTE_E4,50);
   }

    //sleep XBee
    //digitalWrite(WAKE_PIN,HIGH);
    delay(100);
}

int mapLimit(int val, int fromLow, int fromHigh, int toLow, int toHigh) {
  int result = map(val,fromLow,fromHigh,toLow,toHigh);
  if(result > toHigh) {
    result = toHigh;
  } else if(result < -toHigh) {
    result = -toHigh;
  }
  return result;
}

10 bytes in payload were being used, but payload was declared using int payload[10] when it should have been int payload[11].

Just a guess, but maybe your Arduino power supply isn't juicy enough. I had the same problem running 2 modules + LCD on a Arduino powered via USB.
Try to find a power supply somewhere between 9 and 12V (from an old router, modem or cellphone you don't need anymore), and use it to power your Arduino instead of relying on the the USB port alone.
http://playground.arduino.cc/Learning/WhatAdapter

It turned out that payload was allocated with 10 int values but I was using 11 so that caused the crash I guess.

source: Stack Exchange

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

sort: votes


text:
Arduino clock needed to print the time a button is pressed while continuing to count the time?
I'm making a clock using an arduino uno and a compatible freetronics screen. So far it can count the time in a 24 hour loop after which it repeats and counts again. The screen had a number of buttons built onto it and I want to get it so that when one of the buttons on the screen is pressed it prints the time that it was pressed on the top line of the screen while continuing to count and print the time on the second line of the screen.
How can I edit my code below to do this when a button is pressed? What sort of command do I need to add?
#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 0, hours = 8;

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

void setup()
{
  Serial.begin(9600);
    lcd.begin( 16, 2 );

}

void loop()
{
setClock();

/**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 lcd.setCursor ( 0, 1);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);

}

void setClock()
{
currentMillis = millis();
/**
 * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

Any help will be greatly appreciated, thanks

What is your question?

How do I programme it so the button will print the time on the top line of the screen when pressed?

Since you will have to deal with two different times, I suggest
writing a small class for representing those times in broken-down form.
This is a reduced version of the classical strcut tm. Times are made
Printable so you can just print() them to the LCD. I included an
increment() method to add one second to this time.
class BrokenDownTime : public Printable {
    uint8_t hours;
    uint8_t minutes;
    uint8_t seconds;
public:
    void increment();
    size_t printTo(Print &p) const;
};

/* Increment the time by one second. */
void BrokenDownTime::increment()
{
    if (++seconds >= 60) {
        seconds = 0;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }
}

/*
 * Print to anything that inherits from the Print class (Serial,
 * LiquidCrystal, etc.). This makes times `Printable'.
 */
size_t BrokenDownTime::printTo(Print &p) const
{
    p.print(hours/10);
    p.print(hours%10);
    p.write(':');
    p.print(minutes/10);
    p.print(minutes%10);
    p.write(':');
    p.print(seconds/10);
    p.print(seconds%10);
    return 8;  // 8 bytes written
}

The main program checks in loop() for the button being pressed. When
this happens, it saves the current time as lastPress. If the button
was ever pressed (variable button_was_pressed), the recorded time is
displayed on the first line:
#include <LiquidCrystal.h>

#define BUTTON_ADC_PIN A0

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

/* Detect a press on `left', change the thresholds for other buttons. */
bool buttonPressed()
{
    int reading = analogRead(BUTTON_ADC_PIN);
    return reading > 405 && reading < 605;
}

/* Update `now'. */
void updateTime()
{
    static unsigned long last;
    if (millis() - last >= 1000) {
        now.increment();
        last += 1000;
    }
}

void setup()
{
    lcd.begin(16, 2);
}

void loop()
{
    static BrokenDownTime lastPress;
    static bool button_was_pressed;

    updateTime();

    /* Record the time of the button press. */
    if (buttonPressed()) {
        lastPress = now;
        button_was_pressed = true;
    }

    /* Display the recorded time on the first line. */
    if (button_was_pressed) {
        lcd.setCursor(0, 0);
        lcd.print(lastPress);
    }

    /* Display the current time on the second line. */
    lcd.setCursor(0, 1);
    lcd.print(now);
}

I did not test the program, but I hope you get the idea.

You probably want to read the button press on LCD using "read_LCD_buttons" function. See an example at: Arduino LCD KeyPad Shield.
So your part of your code would probably be:
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5
int lcd_key     = 0;

void loop()
{
 setClock();

 /**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 printValueAtLine(0);

 lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)
 {
   case btnSELECT:
   {
     printValueAtLine(1);
     break;
   }
   case btnRIGHT:
   {
     // code in case other buttons like  btnRIGHT, etc are pressed
     break;
   }
   case btnNONE:
   {
     //do nothing
     break;
   }
 }
}

void printValueAtLine(int line)
{
 lcd.setCursor (1, line);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);
}

The code is untested and you may have to make minor corrections to it.
Also, rather than saving values in global variables, you might want to use local ones using libraries suggested by wobbler.

use a second variable called TNow and when the button is pressed pass it the value of currentMillis. parse  and use this as the value to display. or have misunderstood your question? wondering why you aren't using a time library. such as this
if you look on the site here  use the time library you can then use  variable name = now();

I do not understand what you mean by this.

The Time library is probably a good choice if this grows into a “real” clock. For the OP’s toy program, however, it looks a bit overkill: Whenever you ask it to break a time value into hours, minutes and seconds, it also computes the year, month, day-of-week and day-of-month, just in case you may need it later. That's a lot more expensive than incrementing an (hours, minutes, seconds) triplet. And it's times are not Printable, so you still have to write your own print routine.

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


text:
Does data coming in on Arduino serial port store for some time?
I am using Arduino Uno and my question is when data is coming on Rx pin and at that time our program is not checking Serial.available()
Then after some time the program will check Serial.available().
Can we read data? Does it get stored in memory?
If stored how to remove that?
Is the answer the same for Software.Serial()?

Yes.  The serial port uses a ring buffer (also known as a circular buffer) for storing the incoming data until you want it.  That buffer is 16 bytes in size on the smaller Arduinos and 64 bytes in size on the larger one.  A similar ring buffer is used to store transmitted data until the port is ready to transmit it in the background.

What happens if the buffer is full and my PC writes an extra character?  Does the PC block until there is buffer space, is an old character dropped or is the next character dropped?

The next (incoming) character is dropped.

Note that when the IDE is on a Raspbian, HardwareSerial.cpp is located at /usr/share/arduino/hardware/arduino/cores/arduino - go into HardwareSerial.cpp and look at where it detects it has more than 1000 bytes of memory (The Rpi3 has 2048) and that is where the ring buffer setting is 64. I haven't found any need to expand it, but it can be done.

Only if you installed it through apt - which generally installs an ancient (1.0.6 IIRC) version. Sensible people download the tar file from Arduino's website.

I used sudo aptitude install arduino months ago and it is version 2:1.0.5 - and it works great.  Since it installed it never occurred to me to look elsewhere.  (Except on Windows, of course).

Ouch - even older than I thought.  Arduino used to (years ago) push up to the debian repos. They haven't done it for a long long time now. 1.8.4 has been released (I just published UECIDE packages for it) and you really should be on that or something close to it these days...

OK, I see 1.8.4 there as a tarball.gz - Will get it.  (What is UECIDE?)

Better than Arduino's IDE ;)

I notice that I am at 1.8.2 on Windows.  So I can update both of them, also.  (This means updating 8 computers now, thanks very much.  ;-)

Let us continue this discussion in chat.

Yes.  The receive ring buffer is 64 bytes and will discard anything past that until the program reads them out of the buffer.

But be careful:  In serial monitor, any number of bytes more than 64 and ending with Enter will give you Serial.available==63 at the Arduino - and no \n at the end.  This is important especially if you are using readline() in Python.
However, when NOT in the serial monitor, you can actually get the result Serial.available==64 and use Serial.read() to get them in sequence.  No \n is required.
So be careful debugging in the serial monitor when it comes to buffer size and newlines.  It is subtly different when programs are talking vs the serial monitor.
Most important difference is that a program can send a single byte and continue.  Serial monitor will send a single character, but is blocked until you press newline to get it to transmit.  Yet serial monitor does not send the newline character.

Simple scenario:  You want the Arduino to respond to a single-byte command code send via the serial cable from a Raspbian system running a Python data logging program based on something the Arduino reads or by time of day.
You need to trigger the Arduino to take some action as a result.
So on the Arduino you want to first clear the receive buffer by simply reading it out like so:
Arduino code to read a single-character command:
byte ch;
void setup() {
  Serial.begin(9600));
  while (Serial.available>1) ch = ser.read();
}
void loop {
  if (Serial.Available==1 && Serial.read()=='X') {
     .....respond to the X command....
  }
  else
     ....etc...
  delay(60000);
}

Note that when a Rpi Python program is sitting there waiting for linein=ser.readline() the Arduino transmit buffer size is not relevant.  Python collects each byte as it comes in until the \n then returns the string to linein.  The line can be very long.  I have tested it to 100 bytes.

Software.Serial acts exactly the same way.

When you start the Python program it will do a ser=open("/dev/ttyUSB0",9600) to communicate with the Arduino, which causes the Arduino to reset just like starting the serial monitor does. It is good practice to run the above setup code to clear the Arduino's receive buffer so you know you have an empty channel both ways.


text:
Arduino Start en Stop
Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?

Power it through one of these: http://www.dealec.co.uk/acatalog/Timeguard-TS800B-24-Hour-Mechanical-Plug-In-Timeswitch-6519.html#SID=2

What are you trying to accomplish? Why do you need it stopped? Is it to save power or to quit doing its function? The suggestions would be different in each case.

@Majenko: mechanical? Really? :-)

Really stop Arduino is possible, it's called sleep mode, but the UNO is designed so badly with respect to power consumption that you may as well keep it running.
To have it done something at a specific time you could connect a real time clock (RTC) breakout board (SparkFun has a couple). Use a 1 second timer interrupt to read the clock and compare it with (a table of) times where you want things done. A table could hold the time, an output (e.g. for a relay) and the new status (on or off). If you have just a couple of those you can store them in the RTC's battery-backed up RAM.
edit
You can use your PC's time, all the hardware you need is the USB cable. On the PC you run a program that sends the current time to the Arduino. (There are Processing examples of how to communicate with the Arduino on the Net.)
Note that without an RTC your PC will have to be on all the time and connected to the Arduino. You could use the PC just to sync the Arduino's clock and keep time yourself, but the clock of the Arduino is not very accurate.
Getting the time from the Internet is also possible, but then you'll need a Wifi or Ethernet shield to make the connection.

thanks for the answer, but I want to use the time of my pc or internet. Is it still possible?

See the edit of my answer.


text:
Passing VAL(0-179) to OLED
I´m using Spark Fun Micro Pro board 5V: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
and to that i´ve hooked a true color OLED from digole: http://www.digole.com/index.php?productID=859
I manage to get my VAL from my potentiometer on screen. But when I exceeds val "10", and then go back to lets say "9", the zero from "10" is still there. It looks like:  "90" instead of "9". The problem is of course that the second (and third) number don't go away.. Im sure there is a simple way of doing this but I can't get my head around it..
I´ve tried using clearScreen but that function makes the OLED blink in a unpleasant way every time it clears... Hope you get my question, english isn't my native language, as u maybe can tell =)
Thanks
void loop()
{
  val = analogRead(potpin);        // reads the value of the     potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 179);  // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val)  sets the servo position according to the scaled     value
  mydisp.clearScreen();
  mydisp.setPrintPos(9, 6);
  mydisp.print(val);

  delay(200);  // waits for the servo to get there
 // mydisp.clearScreen();

}

Instead of printing "10" or "9" etc, print "10 " or "9 ".  Add an extra space at the end of what you print which overwrites the character that was there before.
mydisp.print(val);
mydisp.print("  ");

I used 2 spaces there, in case you go from 3 digits straight to 1.
Another method is to "format" the number using sprintf:
char temp[4];
sprintf(temp, "%3d", val);
mydisp.print(temp);

Ok, but the problem is that I print (val). So what should I write to add a " "(space) after the (val)?

Just print spaces to the display. See my edit.


text:
Serial device file no longer shows up in /dev/ after working fine for months
I am using an Arduino MEGA connected to my Linux workstation via USB. I have been using this setup for several months with no issues.
A few days ago, the usual serial device file (/dev/ttyACM0) stopped showing up when I plug in the device)

Haven't re-flashed recently.
Unable to reflash.
Removing the devices only shield does not do anything.
Have not changed my physical setup recently.
Connector cable is confirmed working with a different device.

Is this a case of bad hardware, or is there a possible fix other than buying a new device?
dmesg results: None (cleared buffer and re-ran dmesg after plugging / unplugging device)
usb-devices:
T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1a.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
S:  Product=EHCI Host Controller
S:  SerialNumber=0000:00:1d.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=8087 ProdID=0024 Rev=00.00
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=02 Lev=02 Prnt=02 Port=03 Cnt=01 Dev#=  3 Spd=480 MxCh= 0
D:  Ver= 2.00 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1bcf ProdID=2805 Rev=20.15
S:  Manufacturer=6047B0021601A0218M7NB
S:  Product=HP HD Webcam [Fixed]
C:  #Ifs= 2 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=0e(video) Sub=01 Prot=00 Driver=uvcvideo
I:  If#= 1 Alt= 0 #EPs= 0 Cls=0e(video) Sub=02 Prot=00 Driver=uvcvideo

T:  Bus=02 Lev=02 Prnt=02 Port=05 Cnt=02 Dev#=  4 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=0bda ProdID=0001 Rev=68.17
S:  Product=CSR BS8510
C:  #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
I:  If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb

T:  Bus=03 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=1d6b ProdID=0002 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

T:  Bus=04 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=5000 MxCh= 2
D:  Ver= 3.00 Cls=09(hub  ) Sub=00 Prot=03 MxPS= 9 #Cfgs=  1
P:  Vendor=1d6b ProdID=0003 Rev=03.13
S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
S:  Product=xHCI Host Controller
S:  SerialNumber=0000:26:00.0
C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

ls-usb:
Bus 002 Device 004: ID 0bda:0001 Realtek Semiconductor Corp.
Bus 002 Device 003: ID 1bcf:2805 Sunplus Innovation Technology Inc.
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Please give us any relevant output from dmesg and also lsusb and usb-devices

The fact that dmesg gives you nothing at all is the most telling fact.  The there was a communication problem, or the firmware had messed up on the USB interface chip, then you'd expect something to show up - even if it was something along the lines of "device not accepting address 8: -71"
We can ignore the main ATMega2560 chip since that has no bearing on the USB interface.  Instead we're interested in the ATMega16U2 (or whatever is on your board version).
So some things you need to confirm by probing around on the board with a multimeter, or better still, an oscilloscope:

Check that there is power to the board through the USB.
Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
Grab the datasheet for your ATMegaxxU2 chip and get the pinout.  Check that there is power on the pins there should be power on.
Check that the RESET pin of the ATMegaxxU2 chip is HIGH.

If you have a hardware programmer, or another Arduino you can use as a hardware programmer, connect it to the 2x3 header (you may need to populate it first) and try get it to identify the chip ID.  Try to re-flash the USB interface firmware.
Another thing to check is the USB socket itself.  Those big chunky USB sockets look strong, but they're actually quite flimsy inside.  The metal leaves that the plug presses against can bend with time and not make a good contact.  Using a fine needle try lifting them up slightly so they make better contact with the cable.  I think Arduino are the only people that still use them in an active product these days ;)


text:
Using Arduino command line on windows
I have an nmake file;
  srcpath = ..\pilot
  cmdline =  "C:\Program Files (x86)\Arduino\arduino.exe"
  cmdflags = --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files
  prefs = --pref sketchbook.path=$(srcpath) --pref build.path=build
  deps = $(srcpath)\pilot.ino $(srcpath)\commands.h $(srcpath)\publish.h $(srcpath)\motor.h

  pilot.hex :$(deps)
    type $(srcpath)\pilot.ino
    $(cmdline) $(cmdflags) $(prefs) $(srcpath)\pilot.ino

The file types out fine, but Arduino returns an error;
"failed to open sketch ..\pilot\pilot.ino"
I am setting --pref sketchbook.path=$(srcpath), but I have tried with and without (and many variations of both) and get the same error.
This is the command that is currently being invoked, and looks correct to me;
"C:\Program Files (x86)\Arduino\arduino.exe" --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files --pref sketchbook.path=..\pilot --pref build.path=build ..\pilot\pilot.ino

Any ideas?

It looks like the given path is wrong. Have you tried supplying a full path?

You are kinda correct. I posted my own answer

srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot
bldPath = $(srcPath)\build
arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe"
arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt
prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath)

deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h  $(srcPath)\motor.h

pilot.hex : $(deps)
#   type $(srcPath)\Pilot.ino
    $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino

Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)

I guess it's just a matter of understanding what is the working directory. If you're unsure about it, you can set it with --curdir (that, I've just found out, is undocumented), then you can use relative paths

The way the 'type' command succeeded, and Arduino would complain not found, tells me it was not doing working dir relative by default. And yes, I did not know of --curdir - that might have worked. It also seems to ignore the preferences-filename, but it put the file with its Arduino given  name in the right place. I am just happy I can run from VS.


text:
DHT11 with Mysql
I need help to record databаse from dht11 sensor to mysql server.
this is my code:
#include <DHT.h>
#include <Ethernet.h>
#include <SPI.h>

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

IPAddress server(192,168,0,102); // IP Adres (or name) of server to dump data to

#define DHTPIN 2 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

float temperature = 0;  // TEMPERATURE VAR
float humidity = 0; // HUMIDITY VAR
String data;

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

    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
    }

    dht.begin();
    delay(10000); // GIVE THE SENSOR SOME TIME TO START

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

}

void loop(){

    currentMillis = millis();
    if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
        previousMillis = currentMillis;
        temperature = (float) dht.readTemperature();
                humidity = (float) dht.readHumidity();
    }

    if (client.connect(server, 3306)) {
          Serial.print("temperature=" );
          Serial.println( temperature );
          Serial.print("humidity=" );
          Serial.println( humidity );
          Serial.println("-> Connected");
            if(client.connected()){
            // Make a HTTP request:
            client.print( "GET /add_data.php?");
            client.print("temperature=");
            client.print( temperature);
            client.print("humidity=");
            client.print( humidity);
            client.println( " HTTP/1.1");
            client.println( "Host: 192.168.0.102" );
            //client.println(server);
            client.println( "Connection: close" );
            client.println();
            client.println();
            client.stop();
          }
        }
    if (client.connected()) {
        client.stop();  // DISCONNECT FROM THE SERVER
    }

    delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

I connected to database but can't make records. this is output on serial monitor:
temperature=21.00
humidity=73.00
-> Connected
this is my php:add_data.php
<?php
    // Connect to MySQL
    include("dbconnect.php");

    // Prepare the SQL statement
    $SQL = "INSERT INTO test.test.temperature (temperature ,humidity) VALUES ('".$_GET["temperature"]."', '".$_GET["humidity="]."')";

    // Execute SQL statement
    mysql_query($SQL);

    // Go to the review_data.php (optional)
    header("Location: review_data.php");
?>

dbconnect.php=>
<?php
$MyUsername = "root";  // enter your username for mysql
$MyPassword = "fifa2005";  // enter your password for mysql
$MyHostname = "localhost";      // this is usually "localhost" unless your database resides on a different server

$dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
$selected = mysql_select_db("test",$dbh);
?>

review_data.php=>

    <title>Arduino Temperature Log</title>

Arduino Temperature Log

        ID
        Date and Time
        Temperature
        Humidity

    <?php
    // Retrieve all records and display them
    $result = mysql_query("SELECT * FROM temperature ORDER BY id ASC");

    // Used for row color toggle
    $oddrow = true;

    // process every record
    while( $row = mysql_fetch_array($result) )
    {
        if ($oddrow)
        {
            $css_class=' class="table_cells_odd"';
        }
        else
        {
            $css_class=' class="table_cells_even"';
        }

        $oddrow = !$oddrow;

        echo '
';
        echo '   '.$row["id"].'	';
        echo '   '.$row["timestamp"].'	';
        echo '   '.$row["temperature"].'	';
        echo '   '.$row["humidity"].'	';
        echo '
';
    }
    ?>

You should compare the result client.connect against 1 to make sure it's really connected. (The result might be negative, indicating an error.) Do you see the connection in the server log? If so, it's not really an Arduino problem.

I compare the result of client.connect and everything is ok. :) Maybe i should try in stackoverflow for php :)

I meant if (client.connect(server, 3306) == 1). And yes, if that is the part where you have problems with, then do so.

Hey!  Let's all inject some SQL into that incredibly insecure query!!! :)

i'm not sure why my old code doesn't work, but this is my new one and it is working fine. Maybe it will help someone.
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>
EthernetClient client;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192.168.0.101";
dht DHT;
int interval = 5000; // Wait between dumps
#define DHT11_PIN 2
void setup()
{
  Ethernet.begin(mac);
  Serial.begin(115200);

  //Serial.println("Humidity (%),\tTemperature (C)");
}
void loop()
{
  Serial.print("Temperature2 = ");
    Serial.print(DHT.temperature);
    Serial.println(" *C");

    Serial.print("Humidity = ");
    Serial.print(DHT.humidity);
    Serial.println(" ");

  // READ DATA
  //Serial.print("DHT11, \t");
  int chk = DHT.read11(DHT11_PIN);

  if (client.connect(server, 80)) {

    client.print( "GET /diplomna/Arduino/add_data.php?");
    client.print("temperature=");;
    client.print( DHT.temperature );
    client.print("&&");
    client.print("humidity=");
    client.println( DHT.humidity );
    client.println( "HTTP/1.1");
    client.println( "Connection: close" );
    client.stop();
    Serial.println("CONNECTED");
  }
  else {
    // you didn’t get a connection to the server:
    Serial.println("–> connection failed/n");
  }
  delay(interval);
}

You can break down testing in steps.
Call your PHP page from the browser with some dummy parameters and see if it saves them in the DB.
If that part works use a network sniffer, like WireShark to sniff the TCP connection and make sure the correct data is sent to the PHP server from the Arduino.
Depending on which part is not working you can ask the question in the appropriate stack exchange.

You have one problem in the construction of your HTTP GET request on Arduino side:
        // Make a HTTP request:
        client.print( "GET /add_data.php?");
        client.print("temperature=");
        client.print( temperature);
        client.print("humidity=");
        client.print( humidity);

You forgot to separate both request arguments with an ampersand. It should be:
        // Make a HTTP request:
        client.print( "GET /add_data.php?");
        client.print("temperature=");
        client.print( temperature);
        client.print("&humidity=");
        client.print( humidity);

Note the "&humidity" instead of just "humidity".

I fixed my mistake and made several checks, but still there is something wrong.I'm not sure that add_data.php receive data or my mysql query is wrong.


text:
Sending sensor readings from Arduino to Raspberry Pi over 433 MHz
I'm building a garden monitor, so I got myself an Arduino Nano, a soil humidity sensor, an air humidity and temperature sensor as well as a luminosity sensor. Since I had not one but two Raspberry Pis laying around I thought I'll handle the receiving end with one of them. I also got a 433 MHz RF kit.
The trail of the information will look like this: Sensor(s) -> Arduino -> 433 MHz Transmitter - - - 433 MHz - - - 433 MHz Receiver -> Raspberry Pi
Now my question is, what libraries should I use? I checked rc-switch (it has libs for both Arduino as well as RPi) and managed to send some codes but it seems that I'll need to write my own protocol to use this to transmit even simple data as it wasn't developed for sending data, rather simple switch on / switch off signals to simulate remotes.
VirtualWire would seem as the ideal candidate but the problem is it doesn't have an RPi equivalent.
Any suggestions?

You could look into the RadioHead library - there might be a port for RPi, though I couldn't find one with a (very) quick google. This library works well, I use it actually with RFM69H 433 MHz radios (from Moteinos), a little more expensive than the simple 433 kits, but also supports encryption which might be important down the line. If you can't find a good library for RPi one solution could be to have a second Arduino acting as a receiver and sending data serially to RPi. This is what I use with a regular desktop PC which is my home server.
I also found a discussion about connecting a RFM69 to the RPi here which might give you more information about the process in general, even if you won't use the same radio.

There is custom made library to solve this issue  here and i recomend you read this discussion.

I might be getting it wrong, but these discussions are about RPi -> Arduino communication, whereas I want the opposite.

I think it goes both ways... You always use hardware anyway... Use ht12d/e encoder decoders on bothsides and convert ua data inton4 bit binary... Its easier than it sounds...

Presuming you want to get results quickly, I recommend you have a look at openHab This is a Java based home automation framework and server that has plugins for many existing protocols.
Once you get your protocol running it is just a matter of plugging it into openHab for charting and storage. I use for inside home measurements:

Also this post will help you further with connect 433 to RasPi and Arduino.
Specifically for temp and humidity sensors there is the reverse engineered Cresta protocol, that is also used in a lot of commercial sensors. See this Github repo for Arduino code. Also findable for Raspberry Pi.

The sensors I mentioned are for Arduino. So the link would look like this: Sensor(s) -> Arduino -> 433 MHz Transmitter - - - 433 Mhz - - - 433 MHz Receiver -> Raspberry Pi. I edited my question to include this information.

I am fairly new to Arduino but have had a basic experience with python on RPi (Model 2). I am trying to connect ultrasonic sensors (for distance measuring) on Arduino  and then send (RF transmission) the value to Raspberry Pi. I am not able to figure out how to write a code for receiving the transmitted code. I have to receive the code, decode it and then update it in my SQLITE database (on the same RPi).
I have already tried RFSniffer but I am unable to receive value other than "INT". RPi shows nothing if I send any "CHAR" or "STRING".
Please do suggest me how should I proceed.
Thanks in advance
Pradeep Verma


text:
connection between two ARDUINO with xbee
I have a setup where two XBEES modules are talking to each other, both using XBEE shields, one attached to an UNO ARDUINO and the other a MEGA ARDUINO. One XBEE sends the data and the other receives it and switch on or off a LED.
The problem is the receiver one don't work.
This is the sender code
int led = 13;
const int bouton = 2; String inputString;
void setup() {
pinMode(led, OUTPUT);
Serial1.begin(9600);
Serial.begin(9600);
digitalWrite(led, LOW);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
Serial1.println(inputString);
inputString="";
}
}

This the receiver one
int led = 13;
String inputString;
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}

if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
Serial.println("LED ON");
}

if (inputString == "off"){
digitalWrite(led,LOW);
   Serial.println("LED OFF");
}
inputString="";
}
}

I get on the serial monitor of ARDUINO UNO what i wrote in the serial monitor of ARDUINO MEGA but the LED don't switch on or off :/

This question is purely on Arduino, and should be (/have been) posted on Arduino.stackexchange.com.
It has nothing to do with "electronics design". And the only relevancy is due to it being a microcontroller, but Arduino actually has it's own StackExchange page.

Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.

"on\r\n" this is make it works thank you


text:
Conflict between OneWire and I2C?
I have two Arduino boards and I want to make them communicate via I2C. The first board (slave) should read a temperature value from a DS18B20 sensor (OneWire) and send it to the second board (master) via I2C.
So, I tried to merge some code from the standard examples (Wire/master_reader, Wire/slave_sender and dallas/simple).
When I use the two sketches bellow, the serial monitor of the master board is printing the "hello " message, but when I enable the request temperature lines (slave code)
sensors.requestTemperatures();
sensors.getTempCByIndex(0);

the serial monitor shows nothing.
I wander if there is a conflict between OneWire and I2C, or if I've made some serious mistakes in the code.
Any suggestions would be appreciated.
Master
#include <Wire.h>

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

void loop(){
    Wire.requestFrom(2, 6);
    while(Wire.available()){
        char c = Wire.read();
        Serial.print(c);
        }
    delay(500);
   }

Slave
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(){
    sensors.begin();
    Wire.begin(2);
    Wire.onRequest(requestEvent);
 }

void loop(){
}

void requestEvent(){

    //sensors.requestTemperatures();
    //sensors.getTempCByIndex(0);

    Wire.write("hello "); // respond with message of 6 bytes
}

The only thing I see in OneWire.cpp that could maybe cause a conflict, is the use of noInterrupts() -- OneWire has these timing-critical sections where the interrupts have to be disabled, and maybe that's conflicting with the I2C slave. What if you swap the master and slave roles, so the Master manages the OneWire interface (thus avoiding possible conflict with I2C slave listener), and let the Slave device echo to serial monitor?

Indeed, when the master manages the OneWire, it seems to work OK . Nevertheless, I need to collect temperature data from two or more stations (slaves) and send them to central (master), so if slave cannot manage OneWire, that would be a problem. Thank you anyway.

The OneWire stuff can be quite slow. I think I timed doing a temperature read at 12.5 mS which is a long time to be in an ISR. I think you will find that the master assumes it is going to get no response and times out, in that time.
1-Wire Peripheral Interface - for Arduino
What I suggest you do, is get the temperature in the slave, as often as you want, and then just return the temperature when requested. eg.
volatile float lastTemp;

void loop(){
  sensors.requestTemperatures();
  float t = sensors.getTempCByIndex(0);
  // protect move of 4 bytes
  noInterrupts ();
  lastTemp = t;
  interrupts ();
}

void requestEvent(){
  Wire.write ((char *) lastTemp, sizeof lastTemp);
}

Untested, but that is the general idea.
Documentation about interrrupts, and why I am turning off interrupts when moving the temperature to a global variable: http://www.gammon.com.au/interrupts

If there is a conflict, could the slave switch between i2c and one wire?
I don't know how often your device needs to poll, but if you can get away with, say, once per minute, you could poll at regular intervals, and spend the rest of the time (99%) listening for the master. If it is not polled, the number read could be queued. When the master does manage to connect, it could collect the entire queue quickly.
The master, from it's side, could poll more frequently - say once every 53 seconds. About once or twice an hour, it would fail - it would need to handle that gracefully. No matter, it would get the data next time round. Even failing several times in a row wouldn't be a problem; the data would be queued at the slave for later transfer.


text:
Arduino UNO code ignores variables selectively
This is the first code I wrote for my UNO R3 just to feel out the functions and I've already got some jankiness. Throughout this description I am referring to the first two if statements one inside the other one.
I'm trying to increment i every time the signal is activated and then j is used to create a small space of time where the button being pressed will not increment i. My problem is my if statement involving j seem to be totally ignored. I've tried multiple configurations of the if statement structure to no avail.
Here is where things get interesting. So upon setting up the serial connection back to my PC to debug this irritating problem and printing out the actual value of j (to see why it was triggering my if statement prematurely) it magically fixed the problem. It's like until the program literally acknowledges j's value in the print statement it doesn't exist but if it does it works. Any ideas on this?
Note: the serial monitor in both picture depicts consecutive iterations with the signal activated the entire time.
This picture shows the serial monitor after running with the button pressed but the print statement commented out

This picture shows the serial monitor at a space where the button was pressed and held (same time frame as image 1) but in this one it increments i to 3 and then continues incrementing j. How is this happening?

There is such a thing as "print screen" you know - makes an image that is actually readable.  Also, how about posting your code, rather than a photograph of part of your code?

The BIGGEST first thing to realise is that Te Jankiness is probably in your thinking and not in the micro controller. Once yo start from that assumption you have greater chance of sucess,

I suggest that you use {} with every if statement and also don't put two statements on the same line. This practice may seem boring but it is very important to establish good practices early

It would be far, far more helpful to copy and paste the actual code into your post. Please do this. A photograph of your computer monitor, with the code extremely blurry just doesn't cut it. You can also copy and paste the serial monitor output. When pasting your code select it and hit Ctrl+K to indent it four spaces. That turns it into a code block.

Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.
It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, Serial.print() will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.
I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the void delay(unsigned long milliseconds); function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use delayMicroseconds(unsigned int) for shorter but more precise timing. Or better yet, use the unsigned long millis(); function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.

Sorry about the sub-par pictures I was in a hurry at the time. Yes I am aware of the importance of proper syntax/style, the weird structuring of the if statements is the result of muc time spent trying different things(including maximum bracketing) but they all function precisely the same. This code  runs perfectly as long as j is printed. As for the answer from BrettAM this was my initial thought as well. But upon further investigation I do not believe this is the case. Because the code still malfunctions in the same way even with other serial printing if you dont specifically print j.

I have since written other code where this same problem persists. I will write something to specifically depict this problem since it seems to be consistent. This time I will take proper screen shots and there will be no unorthodox syntax.

@JoshWiens Try making j a volatile variable. It seems like a rather extreme thing to optimize out but that might be whats happening. Also, switching to using a time based function instead of a loop like I suggest should still fix the problem. FYI posting code would be prefered to screen shots.

Yes, and I do appreciate the original answer as it is effective(something just bugs me about losing sensory capability for any amount of time), I just was not really looking for a work around but rather the engineer in me was simply interested in why the code would be responding the way it was. Anyways though I got around to writing my tester and now it's working like a charm. Maybe I was being sloppy before? Obviously I just need to do a bit more testing. I'll post the code just in case anyone is interested in seeing it(also will keep in mind the preference to actual code rather than screen shot in the future) . Thanks for the support!


text:
Data Logging GPS with Arduino
I am working on a project for my final in a first year programming course at my high school. I would like to make an Arduino based data logging device that I can bring with my on the mountain biking trails around where I live to create a map. I have found a lot of great sources online but I do not have a small budget. I have an Arduino Uno and a breadboard. My first question is whether it is easy to interface between an Uno and my phone for data logging, or if it would just be easier to buy a microSD card shield? And I need help finding a GPS unit. I have no preference and size is not really a problem. I just need to know how to interface with the Uno. Also if you have any links to other sources I can use that would be greatly appreciated!

Perhaps start by reading about Adafruit's GPS data logging shield and see what components it has. That should give you an idea about what you need.

I've been looking at the same problem, and there is a lot of new stuff now that may still count as a DIY project, but cut out a lot of the leg-work.
On kickstarter there are a lot of new boards that can make it easy:
Here is a ready to go GPS tracking band:
https://www.kickstarter.com/projects/blipperbands/blipper-bands-safety-wherever-you-go?ref=nav_search
Spark-IO has a board that gives you 20,000 messages per month, so you could use it instead of a cellphone to send out the data.
https://store.particle.io/?product=particle-electron
U-Blox makes gps higher-end consumer GPS units that are used in autonomous drones.
There are also a lot of instructables that show how to do the GPS datalogging with while building a drone. These would be small enough and light enough to use while cycling.

first questions; is it easy? Very, do it all the time. But easy to me (30+ year programmer with some embedded experience) may not mean easy to you. Seek out a local make group or friend to help guide you if you are just starting out. I would look into a simple bluetooth adapter for the arduino, they are cheap, $5 in some places like eBay. Then find or write a phone app that log bluetooth.
second question;
Pick a GPS unit from SparkFun or somewhere like that.
If it is a serial unit it may need need some sort of FTDI adapter, which can sometimes be just a cable (and it might not need it, depends).  You really need to match the GPS with the appropriate way to hook it up and there are so many options I don't think someone will be able to cover them all. Depending on which arduino, you will use softSerial, since the hardware serial pins are probably being used by the bluetooth adapter. BTW, did this exact thing for a robot project not too long ago, work ok. I used XBees instead of bluetooth. If I did it again I would try Bluetooth as the XBee reliability wasnt very good.
Another type of connection is called I2C, and that would attach directly to Arduino UNO SDA/SCL (pins A4/A5 I think).
In both cases there are 3V and 5V devices and again you need to match things up on your own.
Now, to spoil your fun, you realize if you are carrying a phone and it is on, you are already being tracked and they are ways to view the history on the web?
In some cases it is easy to find (used to be called google tracks I think). Others are a little harder and I wont give out details, but I used to follow my ATV excursions on fire roads in the mountain all the time after I got back home.
http://junkee.com/google-maps-has-been-tracking-your-every-move-and-theres-a-website-to-prove-it/39639
Update:  gps (https://www.sparkfun.com/products/11571) -> softSerial on UNO -> tx/rx -> bluetooth (http://www.ebay.com/itm/New-Slave-UART-Wireless-Bluetooth-Transeiver-RF-Module-Serial-for-Arduino-AVR-/121643226124) -> phone logging app.
I picked that bluetooth because it claims it can do 3.3v-6v - the others I looked at said 3.3V but I bet they are all the same.  Technically, you probably do not even need the arduino in the middle, but said you wanted to learn.

I am very aware about my phone and would be using it, but it is meant to be a project to learn about the use of Arduino. But thank you!


text:
Servo - Serial communication problem
I am sending data from an Arduino Uno to an Arduino Mega via serial communication.
The data is analog value. I'm getting that data and converting it to an int. There is no problem there. However, when I connect the servo to the attached pin, the serial communication on mega becomes disconnected. When I  remove the PWM pin, the serial communication is working again. Why does the servo stop serial communication?
Wiring: Mega-- 5v and gnd pins linked to servo ( 13kg/cm ), PWM 2 pin is linked to servo's pwm input, rx2 pin is linked to uno's tx pin

Don't power your servo from either Arduino.

Okey I will try to power servo from somewhere else. But what is the problem? I want to know how does it happen.

The problem is that the arduino can not supply enough current to drive the motor. So you might blow-up/fry your arduino (too much current through it).

Actually, you are really lucky to have a working Arduino Mega after your experiment.

But i drive 5 servo together with this mega. Why that time mega did not become fried or blowed up? This not power problem..

Servo current draw varies drastically depending on load and internal control loop behavior which can vary even as the potentiometer and motor age or timing components drift with age or heat.  But it is not just the average current that counts - excessive instantaneous current draw can reset or even crash your Arduino's microcontroller.  What you are trying to do is really not sound engineering - if you are going to persist in it and insist it is not an issue, then people here won't help you.

If you draw too much current from an Arduino microcontroller it can reset itself (brownout), that results in it not responding. To solve this do not power your servo directly from the Arduino, use an external power supply.

If you are using delay function then I guess the problem is due to that. Just try once using millis function to generate PWM signal at Mega.

authors: Б. Янжинлхам


text:
arduino leonardo stops transmitting once hdmi cable is connected to a screen
I am using arduino leonardo for moving mouse pointer with head tracking using MPU6050. It works fine in general. But as soon as I connect an external lcd screen to my laptop via hdmi cable, it stops transmitting. (that is the TX led goes off altogether and the mouse stops moving) I am not able to figure out what the issue is here Will using a teensy 3.0 instead of leonardo solve this problem?

The issue is that the mouse coordinates are being set by the display device that it's attached to.
The computer sends a descriptor about the display to the HID device ( the mouse ) the mouse then uses the information about the logical size of the screen to co-ordinate the movements.
For example, to move with Mouse.move(100,100,0); you are not actually moving by 100 pixels, but by 100/(127-((-127)).
The only option is can suggest is to STOP the mouse and Restart it again - this will be easier to restart calculations again.
Heres my Logic Function to convert Percentage to appropriate values for Mouse.move();
int percentToLogic(int percent) { return percent*254/100; }

I have no idea how this answers this nearly six your old question, but I can see you put some effort into it. Typical mice transmit relative coordinates and have no idea how large the screen is or even whether or not one is plugged in.  Absolute position mice send information with respect to where they are within their own coordinate system, and likewise normally completely unaware of the monitor connectivity and its geometry.

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


text:
Set dynamically hour - DS1307
I want keep my RTC1307 always updated with my server, so I created this code to first search the time on the server then passes to getServerTime() function to divide it and set in the RTC. I use the rtc.adjust() to adjust my watch.
Problem: My watch is getting wrong, this is set 2165/165/165 165:165:85. I think the problem is in defining the time in rtc.adjust(), I'm going as follows:
//tempDate -> May 19 2015
//tempHour -> 09:25:14
rtc.adjust(DateTime(tempDate, tempHour));

Does anyone know the cause of this error?
#include <Ethernet.h>
#include <SPI.h>
#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 rtc;

byte server[] = { 192, 168, 0, 8 };
byte ip[] = { 192, 168, 0, 237 };
byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xED };

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

void loop() {
    getServerTime(getSiteData());
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
    delay(5000);

}

char * getSiteData()
{
    EthernetClient http;
    unsigned char startRead = 0, i = 0;
    char inString[50];

    if (http.connect(server, 80)) {
        http.println("GET /util/date.php HTTP/1.1");
        http.println("Host: ");
        http.println("Connection: close");
        http.println();

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

                if (c == '<' )
                    startRead = 1;

                else if (startRead) {

                    if (c != '>') {
                        inString[i] = c;
                        i++;
                        inString[i] = '\0';
                    } else {
                        startRead = 0;
                        http.stop();
                        http.flush();
                        return inString;
                    }
                }
            }
        }
        Serial.println(inString);
        http.stop();
        http.flush();
    }
    else
        Serial.println("Tentativa de conexão falhou. Sem internet ou servidor inacessivel");
}

//May 19 2015-09:17:24
void getServerTime(char* siteData)
{
    char *tempDate, //May 19 2015
        *tempHour; //09:17:24

    tempDate = strtok(siteData, "-");
    tempHour =  strtok(NULL, "-");

    rtc.adjust(DateTime(tempDate, tempHour));

}

As long as the string you are getting is exactly what you think it is, then that should be working.  I suspect that tempDate and tempHour don't contain exactly the right data.  Print it to serial surrounded by some markers (maybe "[" and "]") to ensure that it is exactly what you expect it to be.

Do you get the difference between  binary-coded decimal (BCD) and regular decimal values?

The numbers reported are typical of the time coming out as -1 or something like that.

I performed a debug and the string no contains  LF+CR, LFCR, CR+LF or CRLF

How about rogue spaces?

The numbers you are reporting are very familiar to me.  They are telling me that it is not possible to obtain the time from the RTC chip.
You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine.  This snippet works perfecty:
#include <RTClib.h>

char siteData[] = "May 19 2015-09:17:24";

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

    char *tempDate = strtok(siteData, "-");
    char *tempHour =  strtok(NULL, "-");
    DateTime now(tempDate, tempHour);

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
}

void loop() {
}

So it must be in the passing of the data through the RTC chip that is failing.
Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.

I forgot -> Wire.begin();   RTC.begin();

That'll do it ;)


text:
Arduino stk500_getsync(): not in sync
We have an arduino pro mini, we are trying to trying to upload sketch the controller but we are prohibited, as the arduino attempt to upload the sketch, it display an error of: not in sync.
We are pretty new in this are, so any help would be much appreciated.
Our setup is: -Breadboard -Connection to adapter: USB Serial. -Arduino Pro Mini as a controller
Through the Arduino Programming Client.
The processor and the port are setup op properly.
The strange thing is, it has worked sometimes these past days..
Much Thanks.
Mieer

Try pressing the reset button just before uploading, might be that the reset signal isn't sent right as it's going through the adapter.

If your error is intermittent, check all of your wiring to ensure there is nothing loose, and try hitting the 'reset' button the Arduino as the compile message changes to uploading, in case your serial adapter isn't resetting the Arduino properly.


text:
Could an `analogWrite` command and its variable output values be used to power multiple leds with same intensity?
I seem to be getting the right response on single LED but with multiple LEDS or a relay connected LED strip the voltage outputs seem to be insuffiecient.
What kind of analogWrite values does an LED respond to?

How are you driving your LED's electrically?  With multiples (in parallel) the current requirement will rapidly exceed what one micro can handle, so you probably need a transistor, FET, or driver IC to help out.  But you can still use the information from the PWM "analog out" pin.

replaced the bulb in this image with an LED strip.
http://www.instructables.com/file/FXOD7OOHTVICRIN
and the pin 7 analogWrite values are perfect for single LED but dont produce results for this strip

You need to provide details of the strip.  They come in many forms, some requirung particular signals to drive.

Single LEDs like the standard 5mm leds work from low voltages such as 1.7 - 2.1v, so can be directly driven via an Arduino pin (through a resistor to prevent excess current draw which would damage the pin).
LED strips such as automotive LED strips (12v) require the use of a relay if you are simply switching the LEDs on and off. You can't run the relay directly from an Arduino pin, you will need to use a transistor to act as a buffer between the relay and the Arduino to prevent damaging the Arduino. Instead of the motor and diode in the below diagram, you connect your 12v led strip.

If you want to control intensity, you will need to use a transistor, or a mosfet (mosfets are easier). You can then use AnalogWrite to control the intensity of the LEDs via the MOSFET. You will need to connect the control pin for the MOSFET to one of the PWM-capable pins on the Arduino (the pins which have the ~ mark next to them), otherwise you will only be able to switch the MOSFET on and off, similar to the Relay. This site has a good guide on how to do this with a MOSFET. It also has a guide on how to use a transistor, but I can't include the link yet due to not enough reputation points. It shows both the code needed, and how to connect the components to the Arduino.


text:
It is possible to control brightness of an LED strip (connected using a relay and having a seperate power supply ) using output from an arduino?
The circuit contains a relay interfacing with 12v power supply and LED strip. Can the brightness for this strip of LEDs be controlled using the analogWrite command?
This works perfectly for a single LED, but when i replace the LED with a relayed LED strip with its own adapter, it doesnt produce any perceivable output

Relays are really slow, as they are mechanical. You can't use analog-write on them. Follow something like this tutorial (except with only one color, instead of three)

Tried this tutorial and well it never really fully responds to a tweaked example code from the site. I am powering the board through usb and thats the only difference. Basically haven't connected Vin and adapter connection which is directly supplying 12v to led. Could that be a problem that even anlaogWrite of 0 and 200 are not producing much of a difference, very very mild response

As Gerben said relays are only for on/off control. If you need to fade led you should use transistor.

What kind of transistor?

It depends on power consumption (how many LEDs).

How to connect Arduino, LEDs, transistor?

This is schematics how to connect the strip. As i assume resistors are already on the strip.

And little bit simpler image :)

Most transistors don't have the gain, or ratio between "big current" and "small current" to drive a very hefty LED strip when there's a 2K resistor on the base.  In the situation you have drawn where you also have a series resistor on the LED strip it might work, but some real LED strips of the sort the OP might be controlling with a relay are high current devices that can want a fair fraction of an amp, or more.

Yes @ChrisStratton as i wrote it depends on power consumtion. The drawings are just to get an idea of how it works.

And big current its not 10amp ;)) thats in milliamps ;) but regard mA from MC;)

Yes!
In the simpler image replace R2 with a 10 Ohm resistor and Q1 with a N channel Logic Level FET.  This will allow  you to switch (PWM) amps with R1 removed.
My LED strips pull about 3 amps at 12V. Depending on the FET you use you may have to add a heat sink.  You will need to connect the low side (Ground) on the Arduino power supply to the low side on the power supply for the LED strip.  The Arduino can then operate at 5 volts and the LED at 24V or whatever depends on the rating of the MOSFET.  I would suggest using one of the PWM outputs, they will work fine with this circuit.  This works for motors but additional parts will need to be added.
Enjoy.


text:
Reading and Writing on different clock edges with Arduino SPI interface
I'm trying to simulate a certain µController to characterize and measure a certain chip.
I need to write my data on the negative edge of the master clock and read the data coming from the slave in the positive edge of the master clock. Is there any way I can have this kind of freedom in my code? Or do I have to do it manually without using the predefined SPI interface?
Also, I would like to have my master clock running continuously without going idle… is there a way to do that too?

To set the spi to shift out on falling edge and shifting in on rising edge of the clock you need to set the spi mode to 0 or 2 (depends on idle clock polarity).
More info here
To continuously generate clock signal as far as I remember you will need to write to the SPI dummy values.


text:
how to multi merge code
i do have sketch from various people out there who have build nice code to do what i need done BUT not for my application and well they grant us permission to use and or modify their code so this is what i attempt to do with your help.

I'm afraid there is no general recipe for combining code snippets. Also, you should avoid adding more questions in the comments. Please feel free to ask separate questions if you have concrete things to ask about.

Unfortunately there is no easy way to do this. All you can hope to do if you see multiple sketches, which if combined would achieve your desired goal, is to splice the code into a single sketch (by copying and pasting), and hope that there are no conflicts resulting from the merging of the different sets of code.
For simple things like two sketches using the same pins, you may be able to fix that by changing which pins are used (unless they are special purpose pins such as PWM or hardware interrupts).
For harder to diagnose problems like two libraries not working if used the same sketch, that is almost impossible to resolve unless you know the hardware or library well enough. Best option there is to find another that does the same job, but differently.


text:
Supplying near perfect DC signals from Arduino UNO
My problem seems very simple but has been impossible to find a straight forward answer searching online. I need my Arduino to output different DC voltages from six ports (probably PWM ports), like 2 V from port 3, 2.1 V from port 5 and so on. And then be able to quickly change to like 4 V from port 3, and 4.1 V from port 5 and so on. But these DC signals need to be near perfect for the highly sensitive sensor I am working with. Everywhere I've searched says to use the PWM outputs and then an RC filter but the ripple from this process is concerning, can I get the the ripple to be under a few mV amplitude? Is there more smoothing I can do beyond a simple RC lowpass filter?
TLDR: I basically need a DC voltage generator that can select between 1 and 5 volts at 0.1 V intervals, and I need to be able to do it with output from the Arduino and some external hardware that will provide a near perfect DC signal to a sensor.

Do you have any response-time requirement?  (When using an RC filter, the tradeoff for low ripple is slow response)

Would 0-4.095V in 1mV (or 0.5mV 0-2.047V) steps do for you?  Then why not use some MCP4822 SPI SAC chips?  You get 2 channels on each 8-pin chip (DIP chips are available, yes), and if you need a different voltage range you could always amplify it with a simple op-amp buffer.
So 6 ports would be 3 chips, which would entail using SCK, MOSI and three CS pins, so 5 pins in all.

(1) A multipole active lowpass filter works wonders.
Something like a 5 pole Bessel filter will probably meet your need. That needs two active stages (1 input RC pole +2 +2 ). You can use transistors in emitter follower mode with some reservations but using 2/4 of a quad opamp per filter is easier overall. I can't spare the lookup time just now (later maybe) but AD & LT and NatSemi all have good free active filter design programs.
(2) A Simple sample & hold per channel will give you steady output limited only by the drift of the opamp used. You can buy commercial S&H ICs or use std opamps. I've used even the venerable LM324 for this but there are much better - you apply the voltage via a switch to a cap[acitor at a unity gain buffer input and then turn off the switch. Again, the "switch can be as simple as an ancient CD4016 or CD4051 but much better more modern ICs are available.
With 1 x CD4051 and 2 x LM324 (or better) you can feed 8 x S&H and update them occasionally top compensate for drift.  If you add another CD4051 with identical addressing but working backwards you can read back the current capacitor voltage and "nudge" it with a simple digital on signal via a diode and high R  resistor if it is slightly off. You can even do ALL signal setting this way if required with NO PWM (or you are effectively implementing adaptive PWM without formally doing so). You eg use 4 driver lines - a fast and slow drive high and a fast and slow drive low. Each is just a digital pin + a resistor and a diode. Select one output channel with the output mux (CD4051 or whatever, and the return mux connects it to your ADC. Pump it up to about right with fast-high, top it off with slow-high and correct with slow-low if needed, then step the mux to the next channel and the S&H cap looks after it. Note that the return channel to the ADC must not load the cap significantly while reading.
If this answer attracts significant interest I can add detail and suggestions re more modern components etc. If not, the above is all a keen person needs to look into the concept.


text:
AC ceiling fan speed control using arduino Uno R3
How can I control an AC ceiling fan speed using Arduino Uno R3? I cannot understand the key behind controlling AC voltage using Arduino (though I know how to on/off ac appliances using arduino and relays).

Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.
Now that's the disclaimer out of the way, on to your question.
Unlike DC, you cannot use PWM to control the average power of AC.  That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.
For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.
If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays.  It's crude, but simple, and also probably the safest option for the beginner.
If you want proper variable speed, though, then you're going to have to chop up the waveform.  The theory is quite simple:  Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.
Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.

A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point.  While simple, these circuits aren't good.  The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc.  It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.
So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.

This should be a comment to @Majenko 's answer, but since I'm newb on this side, it goes as answer: Isn't the speed of the fan more dependent on the AC frequency than on the effective voltage? Would this really work, and in what range of speeds?

The multispeed AC motors used in ceiling fans do not use resistors to change the speed, they use different taps on the motor as an autotransformer to scale the voltage used in the motor.   http://electronics.stackexchange.com/questions/86459/whats-the-theory-behind-speed-control-of-a-multi-tap-multi-pole-induction-motor

If torque-dependent slip is built into the motor, as is true in the multi-speed fan motors, then the amount of slip and speed, relative to the no-load synchonous speed, is dependent on the load and voltage applied.    Reducing the energy input by chopping out part of the waveform also increases the slip.

@Gleb I did convert it but create a few nice answers and you'll get yourself commenting privileges.

I've read this answer multiple times over the last week, and it's still confusing. Is this for single-speed or multi-speed fans? Is there even a difference? Could you provide code samples for Arduino that would assist in understanding the cut-offs on the sine wave? Is this how wall fan-dimmer switches work?


text:
Upload sketch remotely through a serial-IP-serial connection
I tried different times to use socat and ser2net in order to upload a sketch to an Arduino Uno (connected to a PC) from my laptop, unsuccessfully. Can anyone teach me how to achieve this goal? I use Linux.

have not tried it so I wont call it an answer. I see that avrdude support TCP interface. I would try it manually first. Turn on verbose and compile it, find the avrdude command in the verbose. Then go to the output temp directory and issue it manually but replacing the ttyS with the TCP interface with IP and Socket of your ser2net, as found in the avrdude help.

Ok, but after that, there is no way to set in Ecipse Arduino Plugin avrude in order to reach an Arduino through IP... or not? :)

I've been searching through the net for some days, in order to discover how I could easily upload a sketch to an Arduino that is not phisically connected to my PC, but instead that is connected to an another one, that belongs to the same LAN. I mean:
PC1-SERVER
Arduino Uno is connected to this PC with classic USB cable.
This PC is running Ubuntu linux, and sees Arduino as a serial port /dev/ttyACM0.
PC2-CLIENT
This is the PC where I create and compile the sketch.
I want to upload the sketch to the Arduino Uno described above (so, connected to SERVER, port /dev/ttyACM0)
SOLUTION:
server-side commands:
Code:
sudo apt-get install ssh-server ser2net

sudo passwd root    (to set the root password)

sudo reboot

client-side commands (assuming 192.168.0.7 as IP address of SERVER):
Code:
ssh -L 8086:localhost:8086 root@192.168.0.7 \
'/usr/sbin/ser2net -d -C "8086:raw:600:/dev/ttyACM0:115200 NONE 1STOPBIT \
8DATABITS -XONXOFF LOCAL -RTSCTS HANGUP_WHEN_DONE "'

you can then upload sketches to arduino doing this:
Code:
avrdude -C /path/to/avrdude.conf -p atmega328p -c arduino -P net:localhost:8086 -U flash:w:/path/to/file.hex:i

NOTE:
In Eclipse, if you are using the arduino plugin, just place "net:localhost:8086" in the configuration panel, where "port:" field is required.
This solution was also posted on arduino forum.

You can use an ethernet to ttl adapter and then install a virtual com software.
What i did was the following.
I used an ethernet to 232 converter,  and tweaked the board as you can see in the attached photo, I removed the 232 chip and jumpered the ttl directly to the output.
Then I installed USR-VCOM and set a virtual com port that shows in the arduino ide, it works without any software /boot changes
I am not sure how to remote reset the arduino....  Probably someone else knows.

One of the 232 signal lines like DTR or could work like a reset. You could also make your Arduino reset if it receives a specific message, and the send the code.

"You could also make your Arduino reset if it receives a specific message" yes, the only problem is that the standard Arduino bootloaders such as optiboot are not activated after a watchdog reset so you would either need to modify the bootloader or do a hardware reset.

Basically it would require another bootloader.
You might want to check this out:
http://playground.arduino.cc/Code/TFTPBootloader1
Programming through serial
I don't have the intention to advertise a product, but I worked with an Lantronix xport which was able to receive serial information (or a telnet session) over ethernet. You might want to look into cheaper models of other manufacturers (that do not use modem like commands) you should look for ethernet to serial converters.
It should be compatible  with: http://blog.solutions-cubed.com/programming-the-arduino-uno-with-a-serial-port/
You might also connect to another PC over ethernet which then programs the arduino
This would require another PC, but can be fairly easy to set up, but cumbersome to use. You could use teamviewer or another remote desktop. Find a way to send your code (or completely program it at the other pc) and then execute the program command. You might even check if it's possible to use an raspberry PI instead of a full PC (always wanted to try this).
Use an arduino to program your arduino
You might use an arduino that receives code and then uploads it to another arduino. Not sure how that works out. Or how to get the code on the first arduino. Should work fine if you've got something like a modificated arduino webserver running.
Also details on programming arduino can be found here:
http://www.arduino.cc/en/Tutorial/ArduinoISP

Well, you've given me an idea. X tunneling through SSH connection to host, were arduino is connected, than invoke the IDE and use it remotely.

Yup, my answer was just some "brainstorming" if I re-read them, most of them wouldn't really work or just barely. But they indeed give a view on the possibilities. Creating a custom solution, to fit your needs would indeed be the best. If you want to not use another PC, you should check on how an arduino is programmed, how to send the program over ethernet and how to mimic the programming on the other side.
But establishing a connection with a PC over ethernet, and than program it through that would be the best, but a lot of options are possible here also.


text:
How to use an PCF8574P with the simplest code possible
i'm having few PCF8574P which i want to use with my arduino and multiplex them however i have no idea how to use the I2C BUS and the IC in general. There are few libraries but they're fairly complex. Is there any library which makes writing and reading from the PCF8574P easy?

Have you given Rob Tillaart's library from the Arduino Playground a try? The demo sketch might look a bit overwhelming, but at it's simplest, all your sketch should need to have to make a led blink like the standard arduino 'blink' sketch is
#include "PCF8574.h"
#include <Wire.h>

// adjust addresses if needed
PCF8574 PCF_38(0x38);  // add led to P0 (pin 4) (used as output)

void setup()
{
//your setup code here
}

void loop()
{
    //turn P0 (pin 4) of the I/O expander on and off once a second
    PCF_38.write(0, 1);
    delay(1000);
    PCF_38.write(0, 0);
    delay(1000);
}

I don't have any of these parts handy so I can only give generic advice.

This is good..simple code to blink one led. It works..I like it.
Cheers...Markus


text:
To what extent is Javascript used in robots?
I originally discouraged my friend against the use of Javascript in his robot project because I didn't know any use for Javascript outside of web developement but then I saw this book on amazon. Since I wouldn't want to mislead him could someone help me develop a better understanding of how often Javascript is used when making robots with an Arduino?

JavaScript isn't usually used to program Arduino so this site isn't really a good place to ask. You might get better answers on another Stack Exchange site, such as Robotics or Electronics.

@PeterR.Bloomfield can the question be transfered

The question is currently rather broad so it might just get closed at the other sites (which would mean it just gets sent back here). I would recommend investigating what kind of questions the Robotics site will accept, and posting a new question there accordingly.

Javascript is used for Firmata, and there is a Firmata implementation for Arduino. Cylon.JS is an entire framework, which has support for Arduinos running Firmata. (http://cylonjs.com/documentation/platforms/arduino/)

It wouldn't be my first choice for programming of robotics, but it's certainly doable.
Thanks to NodeJS, JavaScript (or ECMAScript as it is properly known) has broken free of the browser and is now a general programming language.
Thanks to the BeagleBone Black (and others), which runs most of its systems by default through NodeJS, including its web-based IDE, you can program the whole board with ECMAScript.
So yes, you can do robotics with ECMAScript, and there are platforms which do allow you to do robotics with ECMAScript.
Would you want to do it in a real industrial environment?
As I said - it wouldn't be my first choice.

Would you want to use an Arduino in a real industrial environment? :) But otherwise I can say JavaScript is used by robots to ship somewhere around 50% of all consumer goods :)

The Arduino caveat was added after this answer was written. Check the edit history. Before then it didn't specify any hardware, which is why it got closed - nothing to do with Arduino.

Dude, I made the edit. You think by posting on an Arduino SO it was about something else? I'm just saying, JavaScript does indeed drive industrial robots in some significant way, for more than an Arduino or BeagleBone ever would.

"You think by posting on an Arduino SO it was about something else?" It often is, yes. You'd be surprised by the amount of stuff about the Pi we get here - and stuff not even remotely related to Arduino.  Just because the site is Arduino doesn't mean that everyone has the intelligence to only ask about Arduino things here...

But I still stand by my answer. It may be used in the industry, but I certainly wouldn't have it as my first choice of language.  Python is used lots these days too - and that is even lower down on my list of languages...


text:
giving delay function to output
I want my arduino to give the output at a specified delay .The delay is calculated from a polynomial equation.
unsigned long t=40*Vin*Vin-760*Vin+4320;
delay(t);
digitalWrite(ledPin,HIGH);

but while doing this i was unable to get the delay accurately while observing it through oscilloscope??

Delay does not accept negative values, where does Vin come from? Do you make sure t is always positive? Post some code so we can try help you better.

@bpinhosilva, that quadratic function is positive for all values of Vin that don't cause overflow. Its min value is t=710 @ Vin=9.5

What do you mean by "i was unable to get the delay accurately"? What do you observe and what do you expect instead?

You should consider putting the pin low again after some time, as you want to measure the time between pulses?

I suggest you look into using a hardware timer rather than using delay(), I suspect it will give you more accurate timing.
Timer configuration is not as straight forwards as using delay - they don't work in milliseconds or microseconds, but instead in multiples of clock cycles, which (I find) makes configuring them a little difficult to understand, but it is possible to set the interval of a timer within its own interrupt routine.
Another advantage to using timers is that your code can do other things whilst waiting between interrupts.
Have a read here for more information and simple examples:
http://playground.arduino.cc/code/timer1
or just Google "Arduino timers" for other examples and explanations.

Perhaps you had in mind something like this fragment, which will raise ledPin for the time you calculated (in msec) then lower it again?
// ...
unsigned long t=40*Vin*Vin-760*Vin+4320;
digitalWrite(ledPin,HIGH);
delay(t);
digitalWrite(ledPin,LOW);
// ...