body:
I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call.
At the moment I have the following code on Arduino:

>     #include <SPI.h>
>     #include <Ethernet.h>
>
>     byte mac[] = {
>       0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
>     };
>     IPAddress ip(192, 168, 1, 177);
>
>     EthernetServer server(80);
>
>     void setup() {
>       Serial.begin(9600);
>       while (!Serial) {
>         ;
>       }
>
>       Ethernet.begin(mac, ip);
>       server.begin();
>       Serial.print("server is at ");
>       Serial.println(Ethernet.localIP());
>     }
>
>
>     void loop() {
>       float temperatureIndoor;
>       float temperatureOutdoor;
>       EthernetClient client = server.available();
>       if (client) {
>         Serial.println("new client");
>         boolean currentLineIsBlank = true;
>         while (client.connected()) {
>           if (client.available()) {
>             char c = client.read();
>             Serial.write(c);
>             if (c == '\n' && currentLineIsBlank) {
>               client.println("HTTP/1.1 200 OK");
>               client.println("Content-Type: application/json;charset=utf-8");
>               client.println("Server: Arduino");
>               client.println("Connnection: close");
>               client.println();
>
>               temperatureIndoor = 22.77;
>               temperatureOutdoor = 15.55;
>               client.print("{\"0\":{\"TemperaturaInterior\":\"");
>               client.print(temperatureIndoor);
>               client.print("\",\"TemperaturaExterior\":\"");
>               client.print(temperatureOutdoor);
>
>               client.print("\"}}");
>               client.println();
>               break;
>             }
>
>           }
>         }
>         delay(1);
>         client.stop();
>         Serial.println("client disconnected");
>       }
>     }
>

I'm trying to get values with the following ajax call:

        $.ajax({
         url: 'http://192.168.1.177/',
         type: 'post',
          data: { tag: 'getData'},
          dataType: 'json',
                      async: false,
             success: function (data) {

    $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
    $('#TemperaturaExterior').val(data.TemperaturaExterior).show();

              }
             });

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino:
{"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}

I'm not getting the values.
Any idea?
Thanks

NOTE:

This what I get when ask to arduino to give me the values:

![enter image description here][1]

  [1]: https://i.stack.imgur.com/Tc7fw.jpg

title: Get JSON data from Arduino with AJAX

Answers: 2

body: Ouch man you are getting burned by CORS. This stack overflow box isn't big enough for me to explain how much of a pain CORS is and how much trouble it will cause you. That being said there is a really good recourse that will help explain how to get this working with a couple of http headers http://enable-cors.org/. Good luck

body:
This is more of a Stack Overflow question, but I'll help you a bit. The problem has nothing to do with your Arduino per-say. It has more to do with your PHP/Ajax.

Your code is suited for a completely local setup, but pulls from a remote site, which violates some security protocols build into your browser and jQuery. You need to change your code to this:

    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
        data: { tag: 'getData'},
        dataType: 'jsonp',
        async: false,
        success: function (data) {
            $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
            $('#TemperaturaExterior').val(data.TemperaturaExterior).show();
            }
        });
    (may need slight modifications since you didn't include all PHP/html code)

For more information, see the [jQuery documentation][1], particularly look at data types and what it says about cross-domain json vs jsonp.

[Here][2] is a relevant SO question.

  [1]: http://api.jquery.com/jquery.ajax/ "jQuery Documentation
  [2]: https://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain


body:
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?

title: How to write RFID data using the RFID-RC522 chip

Answers: 1

body:
The library you refer to is called [RFID][1] 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][2] of the University of South Florida.

At 21:30 it explains how to write data.

  [1]: https://github.com/miguelbalboa/rfid
  [2]: http://makecourse.weebly.com/week10segment1.html


body:
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;
    }

title: Why is SoftwareSerial causing arduino to reboot?

Answers: 2

body:
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

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


body:
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

title: Arduino clock needed to print the time a button is pressed while continuing to count the time?

Answers: 3

body:
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][1]
if you look on the site [here][2]  use the time library you can then use  *variable name* = now();

  [1]: http://www.pjrc.com/teensy/td_libs_Time.html
  [2]: http://playground.arduino.cc/code/time

body:
You probably want to read the button press on LCD using "read_LCD_buttons" function. See an example at: [Arduino LCD KeyPad Shield](http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)).

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.

body:
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.

<!-- language-all: lang-c++ -->

    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);
        p.write(':');
        p.print(minutes/10);
        p.print(minutes);
        p.write(':');
        p.print(seconds/10);
        p.print(seconds);
        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.


body:
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()?

title: Does data coming in on Arduino serial port store for some time?

Answers: 2

body: 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.

body:
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.


body: Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?

title: Arduino Start en Stop

Answers: 1

body:
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](https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing) 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.


body:
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();

    }

title: Passing VAL(0-179) to OLED

Answers: 1

body:
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, "=", val);
    mydisp.print(temp);


body:
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

title: Serial device file no longer shows up in /dev/ after working fine for months

Answers: 1

body:
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:

1. Check that there is power to the board through the USB.
2. Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
3. If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
4. Grab the datasheet for your ATMega*xx*U2 chip and get the pinout.  Check that there is power on the pins there should be power on.
5. Check that the RESET pin of the ATMega*xx*U2 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 ;)


body:
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?

title: Using Arduino command line on windows

Answers: 1

body:
    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)


body:
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=>

<?php
// Start MySQL Connection
include('dbconnect.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 '
';
        }
        ?>

title: DHT11 with Mysql

Answers: 3

body:
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.

body:
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"`.

body:
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);
    }


body:
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][1] (it has libs for both Arduino as well as [RPi][2]) 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][3] would seem as the ideal candidate but the problem is it doesn't have an RPi equivalent.

Any suggestions?

  [1]: https://github.com/sui77/rc-switch
  [2]: https://github.com/r10r/rcswitch-pi
  [3]: http://www.airspayce.com/mikem/arduino/VirtualWire/

title: Sending sensor readings from Arduino to Raspberry Pi over 433 MHz

Answers: 4

body:
You could look into the [RadioHead](http://airspayce.com/mikem/arduino/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](http://homeautomation.proboards.com/thread/7/raspberry-rfm69-sensor-node-gateway) which might give you more information about the process in general, even if you won't use the same radio.

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

body:
Presuming you want to get results quickly, I recommend you have a look at [openHab][1] 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:
![enter image description here][2]

Also [this post][3] 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][4] for Arduino code. Also findable for Raspberry Pi.

  [1]: http://openhab.org/
  [2]: https://i.stack.imgur.com/5SM7e.png
  [3]: http://www.princetronics.com/how-to-read-433-mhz-codes-w-raspberry-pi-433-mhz-receiver/
  [4]: https://github.com/mysensors/Arduino/tree/master/libraries/RemoteSensor

body:
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


body:
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 :/

title: connection between two ARDUINO with xbee

Answers: 1

body: 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.


body:
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)

<!-- language: c -->

    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

<!-- language: c -->

    #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

<!-- language: c -->

    #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
    }

title: Conflict between OneWire and I2C?

Answers: 2

body:
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 ](http://www.gammon.com.au/forum/?id=10902)

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.

<!-- language-all: lang-C++ -->

    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>

body:
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.


body:
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 after running with the button pressed but the print statement commented out][1]

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?

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

  [1]: https://i.stack.imgur.com/adizC.jpg
  [2]: https://i.stack.imgur.com/KcVYF.jpg

title: Arduino UNO code ignores variables selectively

Answers: 2

body:
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);`][1] 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)`][2] for shorter but more precise timing. Or better yet, use the [`unsigned long millis();`][3] 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.

  [1]: http://www.arduino.cc/en/Reference/Delay
  [2]: http://www.arduino.cc/en/Reference/delayMicroseconds
  [3]: http://www.arduino.cc/en/Reference/Millis

body:
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!![enter image description here][1]

  [1]: https://i.stack.imgur.com/O0SJ4.png


body: The Arduino due exclusively runs on 3.3V, so I am wondering if this can be used as a USB to serial converter just like the Arduino Uno could, or do you need to do level shifting?? Will I ruin the board if I just hook up RX and TX to a 5v device?

title: Can the Arduino Due be used as a serial to USB converter?

Answers: 1

body:
Yes it will work as a USB to serial device, however the serial will be at 3.3V not 5V. It'll still be serial though.

For it to send data to a 5V device, depending on the device, it might work.  3.3V is often around the "high" threshold for an input pin on a 5V device, but check the datasheet for the 5V device to be sure.

For receiving data the 5V will be above the 3.3V supply voltage of the main SAM3X chip, so should be avoided. As with most Atmel datasheets, actually finding the information you want is almost impossible, and I haven't found if there is a maximum "over voltage input current" or not, so to be on the safe side a full level shifting voltage divider should be used on the RX pin.


body:
I recently bought an XBee shield ([this][1]). The shield has a switch that seems to switch between USB/XBee. However, there is no USB port. What exactly is the switch supposed to do?

  [1]: http://www.ebay.com/itm/New-For-Arduino-ZigBee-XBee-Bluetooth-Bee-V03-Shield-Module-Wireless-Control-Hot/301457628487?_trksid=p2047675.c100005.m1851&_trkparms=aid=222007&algo=SIC.MBE&ao=1&asc=30543&meid=6648f5c1a8f54e9e92e799f4092616ce&pid=100005&rk=3&rkt=6&sd=221568487830&rt=nc

title: What is the function of the XBee / USB switch on an XBee shield?

Answers: 4

body: Better to check connection with tester. I think it switches connection to bluetooth module directly to your PC (with usb serial converter which is on arduino board)  or with arduino microcontroller.

body: I imagine that the switch has the same functionality as the "serial select" switch on the official Arduino Wireless Shield for XBee modules. Therefore the explanations on the switch settings given there (http://www.arduino.cc/en/Main/ArduinoWirelessShield) probably apply also to your board.

body:
In case someone does ask the same question in the future, this is the explanation for the USB/XBee switch functionality on the XBee Pro Shield V3 [![XBee Pro Shield V3][1]][1]

The switch serves to connect/disconnect the XBee Pro shield v3 to the Hardware TX->1 & RX<-0 Lines of the Arduino. Moving the switch to the USB side, allows you to disconnect the XBee Pro shield v3 from the hardware serial lines and upload code to your Arduino. If the switch is on the XBee side, this allows your XBee Pro shield v3 to use the TX->1 and RX<-0 lines of the Arduino and if you want to upload code to your Arduino, you would have to remove the shield otherwise it would result in an error trying to upload code. [![Arduino Uploading Error][2]][2]

  [1]: https://i.stack.imgur.com/aT7El.jpg
  [2]: https://i.stack.imgur.com/IRpBe.png

body:
The Xbee shield has aswitch labled Xbee/USB. This determines how the Xbee's serial communication connects to the serial communication between the microcontroller (ATmega8 or ATmega168 or Atmega328) and FTDI USB-toserial chip on the Arduino board.

In the Xbee position the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI
chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.

In the USB position, the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer -
however, **IMPORTANT** this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module.

THANKS TO RS-COMPONENTS FOR THE DETAILS!!!!!


body:
I wonder why Arduino doesn't run at 20 MHz, the frequency the AVR is specified for. Now, running at 16 MHz, we're wasting 20% performance for nothing.

I don't think there are *any* implications when you replace the 16 MHz resonator with a 20 MHz type, with probably the sole exception for the baudrate in the bootloader. Or is there?

Does anybody know why the Arduino designers chose 16 MHz?

title: Arduino at 20 MHz?

Answers: 2

body:
There's no hardware reason (as far as I'm aware) that you couldn't run a suitable Arduino at 20 MHz. You'd run into minor timing inaccuracies in software though, as the standard Arduino configuration apparently works best if the clock speed is either 8 or 16MHz.

I suspect this is largely for historical reasons. Early Arduino boards were based on chips which only went up to 16 MHz, such as the `ATmega8`. Using the same configuration for all chips just keeps everything a bit simpler and more consistent.

There is more information here about the timing issues: http://forum.arduino.cc/index.php?topic=158223.0#msg_1186708

body:
You can, and I do.

It's not technically an Arduino anymore, I guess. I made my own board, replacing a resonator on a board will require some fine soldering, but it is definitely possible.

There are some gotchas: Anything time-related (e.g. millis() ) will be run faster than is should - 25% more millis() per second. Also, the bootloader expects 16mhz, so you won't be able to reprogram it at this speed. I purchased a USBASP programmer - it hooks into the 2x3 pin grid on one side of the board, and lets you reprogram it without the bootloader (this is how the bootloader is put on in the first place!). You will need at least 4.5 volts at 20mhz to avoid problems, compared to 3.78 volts for 16mhz - this means batteries will drain somewhat quicker (3x1.5v batteries will run down pretty quick), and if you have any motors or other draw on the batteries, 3 1.5v batteries will probably not work even if they are fresh.

Alternatively, going in the exact opposite direction, the lower the clock speed, the less voltage is required - for some projects, you might not need the clock speed - you can go down to 1.8v running at 4mhz.


body:
How can I write lightweight cross correlation code for arduino? I couldnt find any solution. The measurement system contains an ultrasonic sensor and a servo  that turns from 45 to 135 degree and measures distance from 4-300 cm. Than i collect data in an array which contains distances with respect to angle. System makes several measurement like this and program finds cross correlation between new and old arrays.

http://www.instructables.com/id/How-To-Make-an-Obstacle-Avoiding-Arduino-Robot/

title: Arduino Cross Correlation?

Answers: 1

body:
Given the time scale of the measurements, performance is not an issue.
And since you are not computing in real-time, as the samples are being
measured, you can apply the definition of cross-correlation as is, and
compute it in a double loop. The only difficulty is figuring out that
cross-correlation may not be the proper tool for the job... and finding
the right one! My assumption is that you want to estimate a rotation
angle between the two measurements.

The mathematical definition of cross-correlation assumes infinite
arrays. In practice, cross-correlation is often used to locate a short
pattern inside a long signal. In this case, the computation is done only
for shifts where the pattern completely overlaps the signal. Then the
length of the result is

    length(result) = length(signal) − length(pattern) + 1

In your case, since your pattern is a previously measured signal, this
would give a single-sample result, which is useless.

You could instead compute the integral for all shifts where there is
_any_ overlap between the pattern and the signal. This is equivalent to
zero-padding the signal. This has the drawback of biasing the result: if
your signal and pattern are both featureless (positive constants), you
will find a very nice peak at zero shift!

You can remove this bias by subtracting the average from both the signal
and the pattern, and correlating (signal − avg(signal)) with
(pattern − avg(pattern)). This still carries a bias for “big”
features. Imagine for example that, after removing the averages, you
have

    pattern = [  0,   0, −20, +20,   0,   0];
    signal  = [−50, +50,   0,   0, −20, +20];

You would expect your correlator to find a good match between the
[−20, +20] of the pattern and the [−20, +20] of the signal. The
correlation is, however, much better with the [−50, +50] of the signal.
You may try to alleviate this by computing a normalized
cross-correlation instead, but you will at best make both matches
equally good.

My suggestion is that you completely forget about correlations and
instead think in terms of “goodness of fit”. Correlations are good for
finding scaled and shifted copies of a pattern inside a signal. You are
looking for _shifted only_ copies, with no scaling. Your question should
be: if you shift the pattern by some amount, how well does it fit the
signal? What amount of shift gives the better fit? The canonical answer
to all “goodness of fit” questions is to minimize the RMS difference
between the two: you compute the sum

    S = Σ(signal − shifted(pattern))²

Then the RMS difference is

    RMS(difference) = √(S/N)

where _N_ is the number of samples involved in the sum. The most likely
shift is the one that minimizes this error. In practice, you do not need
the square root, you just minimize

    RMS(difference)² = Σ(signal − shifted(pattern))² / N

You can implement this formula as-is, it's completely straightforward.
Just beware that _N_ depends on the shift, as it's the length of the
overlap. And avoid going to very small overlaps (i.e. large shifts).

Now, if you expand the square inside the sum, you may find that, after
all, this is not so far from a cross-correlation... And BTW, all this
has nothing to do with Arduino.


body:
This is my code:

    const int trigPin = 4;
    const int echoPin = 2;
    const int trigPin2 = 6;
    int incomingByte;
    int val, val2;
    const int echoPin2 = 7;

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

    void loop() {
      pinMode(trigPin, OUTPUT);
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      pinMode(trigPin2, OUTPUT);
      digitalWrite(trigPin2, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin2, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin2, LOW);

      pinMode(echoPin, INPUT);
      pinMode(echoPin2, INPUT);

      val = digitalRead(echoPin);
      val2 = digitalRead(echoPin2);

      if (val && val2 == HIGH) {
        Serial.println("Elephant on tracks");
      }

      if (Serial.available() > 0) {  // if the data came
        incomingByte = Serial.read();
      }
      // read byte
      if(incomingByte == '0') {
         digitalWrite(trigPin, LOW);
         digitalWrite(trigPin2, LOW);
         Serial.println("The system is OFF.");  // print message
      }
    }

Anyhow, I click upload, and as the title of this question says, have to wait forever.
Not only this code, nothing gets uploaded. It was working just fine a week ago.
I run a Windows 7 64-bit system, and have an Arduino Uno R3.
Does anyone have any suggestions?

title: Uploading... forever

Answers: 2

body:
*Comment by SR1 turned into an answer*:

Thanks for the suggestions. It finally worked. It was because of my HC-06 Bluetooth module. I don't know if the mistake was mine or if it is a fault with the module.

---

(Done to reduce "unanswered questions" on this site).

body:
From your code, I assume that the bluetooth module is connected to pins 0 & 1 on the arduino. These pins are to be kept free/floating/not connected to anything if you need to upload code to your board.

Use software serial in such cases reduces the headache


body:
I bought a ethernet shield for my Arduino Uno. I plug it my Arduino and PC with ethernet cable. There is all led is working on ethernet shield. But when i try to examples about ethernet which is in Arduino IDE as "DHCPChatServer" example.

 **I hope to see;
"Trying to get an IP address using DHCP"
"My IP address: 192.168.1.177"**

**But I just see "Trying to get an IP address using DHCP"**

Any problem with my ethernet shield?

title: arduino ethernet shield

Answers: 2

body:
When you connect your arduino directly to the PC using the ethernet cable, neither of them have any information about the network.

Most ethernet devices attach to switches, routers, and gateways, and one or more of these devices host network services such as DHCP, DNS, or provide a way to obtain those services.

Without DHCP, for instance, neither your PC nor the Arduino know what IP adress to use, what their netmask is, and whether there's a gateway to other IP addresses.

You have a few options:

 * Follow the [Automatic Private IP Addressing][1] specification, which windows computers default to when no DHCP server is present or available. Set the IP address of the Arduino to 169.254.x.y where x and y are randomly chosen numbers between 0 and 255, and set th netmask to 255.255.0.0.  The windows computer should have done the same if no static IP address was set - use `ipconfig` on the windows command prompt to find its IP address.  Your computer and arduino should be able to talk to each other.
 * Set up a router. It doesn't need to connect to the internet, it just needs to connect to both the PC and the Arduino.  It'll implement a DHCP server and make sure, at minimum, that the two devices can talk to each other and the router.
 * Set static IP addresses on both devices.  Set up the PC with something like 192.168.42.1 with a netmask of 255.255.0.0 and the Arduino with 192.168.42.2 and the same netmask.  Now they should be able to talk to each other.
 * Connect both to an existing network.  The network should already have a router with DHCP on it, so it'll take care of everything, and as a bonus you may be able to get internet access as well, which could help with testing since you can use the ethernet shield to communicate with google and other known working services, rather than trying to set up a server on the PC.

  [1]: https://support.microsoft.com/en-us/kb/220874

body: I changed my Arduino Uno with Arduino Mega and problem is solved.Thank you


body:
I'm interested in writing a C program *without* the Arduino IDE and related libraries and am trying to figure out how I can access the GPIO pins for read and write.

My *assumption* is that the GPIO pins are - at the hardware layer - just memory addresses, and so if I know what their address is I can send/receive data to and from them.

* For writing to the digital pins, do I just send an `int` with a value of `0` or `1` to the pin's address? If so, what might that code look like? Can I then assume I could poll that address for a value, which would be either `0` or `1`?
* Can I assume the same for analog pins, but instead of binary values, I'd get an integral value between `0` and `1023`?

And if I'm way off here, and pins are *not* accessed via memory addresses, then how?

Again, the solution I'm looking for wouldn't involve Arduino software, just the Arduino hardware (an AVR or ARM MCU). Bonus points for C pseudo-code examples! Thanks in advance!

title: Reading/writing to Arduino GPIO pins from raw C code

Answers: 1

body:
In theses cases you are right, using register address is the way to read/write data from/to digital pins.
In the case you use analog input, the process is similar but you have to follow some procedures before getting the value of the data.

**[GPIO REGISTERS][1]**

For AVR micro-controllers these registers are:
DDRn – Data Direction Register
PORTn – Port Output data Register
PINn – Port Input Register
n- Indicates the port name i.e. A, B, C & D
If you have arduino board and want to use these pins, look for mapping pictures about arduino and avr pins.

The following is an example from the Arduino website.

DDRD is the direction register for Port D (Arduino digital pins 0-7). The bits in this register control whether the pins in PORTD are configured as inputs or outputs so, for example:

    DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input
    DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7 as outputs
                             // without changing the value of pins 0 & 1, which are RX & TX

See the bitwise operators reference pages and The Bitmath Tutorial in the Playground

PORTD is the register for the state of the outputs. For example;

    PORTD = B10101000; // sets digital pins 7,5,3 HIGH

You will only see 5 volts on these pins however if the pins have been set as outputs either by using the `DDRD` register directly or by using the  `pinMode()` function.

**For analog read**

You just need to include the headers and start using the registers. They hold the equivalent hexadecimal values for your microcontroller. And the procedure is described in the datasheet. All you have to do is to translate it to code.

    // this code scans ADC1 for an analog signal upon request, using 8Mhz processor clock

    #include <avr/io.h>
    #include <stdint.h>       // needed for uint8_t

    int ADCsingleREAD(uint8_t adctouse)
    {
        int ADCval;

        ADMUX = adctouse;        // use #1 ADC
        ADMUX |= (1 << REFS0);   // use AVcc as the reference
        ADMUX &= ~(1 << ADLAR);  // clear for 10 bit resolution

        // 128 prescale for 8Mhz
        ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

        ADCSRA |= (1 << ADEN);    // Enable the ADC
        ADCSRA |= (1 << ADSC);    // Start the ADC conversion

        while(ADCSRA & (1 << ADSC)); // waits for the ADC to finish

        ADCval = ADCL;
        ADCval = (ADCH << 8) + ADCval; // ADCH is read so ADC can be updated again

        return ADCval;
    }

    int main(void)
    {
        int ADCvalue;

        while (1)
        {
            ADCvalue = ADCsingleREAD(1);
            // ADCvalue now contains an 10bit ADC read
        }
    }

For more information about analog read, see [this][2].

  [1]: https://techawarey.wordpress.com/2013/12/28/avr-gpio-tutorial/
  [2]: https://sites.google.com/site/qeewiki/books/avr-guide/analog-input


body:
I'm not too familiar with the Arduino C++ language, but I would like to get this native code to work.

In curl this works:

> curl "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&outputMode=json&apikey=my-apikey"^C

So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.

    sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&text=%s&outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json");
    Serial.println(request);

When I print the request, everything after the & gets truncated.

      char serverName[] = "access.alchemyapi.com";
      if(client.connect(serverName,port) == 1)
      {
        sprintf(outBuf,"GET %s HTTP/1.1",page);
        client.println(outBuf);
        sprintf(outBuf,"Host: %s",serverName);
        client.println(outBuf);
        client.println(F("Connection: close\r\n"));
      }

This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter.

title: Wifi REST API GET call - how to concatenate and pass URL parameters?

Answers: 1

body:
Concatenating the string data in memory before sending it shouldn't be necessary. Instead, you should just be able to use `client.print()` (or equivalent) to output each part of the request in sequence. For example:

    client.print("GET ");
    client.print(page);
    client.print(" HTTP/1.1\r\n");

    client.print("Host: ");
    client.print(serverName);
    client.print("\r\n");

    // etc.

That should let you output any combination of HTTP headers you need.


body: I am using an HC-05 bluetooth Module. How can I stop someone from pairing with my device by brute forcing the key? Failing that, and if someone does pair with my device, is there a way to authenticate the user? I was thinking of salted hash with a shared secret key. Is there anything better?

title: How can I stop someone from hacking in to my Arduino via Bluetooth?

Answers: 2

body:
Configure your Bluetooth module to AT Command Mode

Then use `AT+PIN` Command to change the default PAIRING PIN of the Bluetooth Module.

Visit [this link][1] for more information about how to configure bluetooth to AT Mode

  [1]: http://www.instructables.com/id/AT-command-mode-of-HC-05-Bluetooth-module/?ALLSTEPS

body:
In case someone else asks the same question in the future, here's the answer...

Technically speaking, the Arduino cannot be hacked for the simple reason that it doesn't have an Operating System like other devices such as the Raspberry Pi, BeagleBone, Rock64 etc. So in as much as someone might be able to bruteforce the HC-05 pin and get access, there's pretty much nothing else they can do past that point, so my advice to you is that don't stress over it. However I would suggest adding a few security measures to your HC-05 Bluetooth module:

1. Change the default pin (0000 or 1234) to something else.
2. Lock the module to connect only to a specific device via the MAC Address and the AT+BIND command.

Cheers!


body:
I created a quite simple Arduino sketch:

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

    void loop() {
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);

      float voltage = sensorValue * (5 / 1023.0);
      Serial.println(voltage);

      delay(1000);
    }

I use the following circuit:

![enter image description here][1]

My multimeter measures **3.31 V**, between the pin 3V3 and GND.

I get a *sensorValue* of **730** and a calculated *voltage* of **3.57 V**. This is 8% higher that 3.3V. What is the tolerance by the AD-converter?

  [1]: https://i.stack.imgur.com/NT6sS.png

title: Arduino AD-converter tolerance

Answers: 1

body:
The absolute accuracy of the ADC in the ATmega328P when its clock is within its optimal range is given [in the datasheet][1] as 2LSB. This means that the actual value could be anywhere between 728 and 732.

Of course this depends on the accuracy of VCC, since it is being used as the ADC reference. This is why supply voltage measurements should be performed using the internal bandgap voltage instead.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


body:
I am playing around with the Sparkfun Venus GPS.  I followed [this][1] tutorial to get started.  In here the author states that you should

> Upload the following sketch to your Arduino BEFORE making any
> connections. 5V from an IO pin left high on the Arduino may well kill
> the 3.3V output from the Tx pin on the GPS module.

However, I am using the Sparkfun bi-directional logic level converter in between the Arduino and the Venus GPS (because I'm using the 5V Arduino GSM shield stacked on top of the Arduino).  In that case, would the above statement still apply?

  [1]: http://www.doctormonk.com/2012/05/sparkfun-venus-gps-and-arduino.html "this"

title: Venus GPS + Arduino. Kill 3.3V TX during sketch upload

Answers: 1

body:
<!-- language-all: lang-C++ -->

If you have a logic-converter between the Arduino and the GPS then you won't have any problems.

The warning was about having the output from the Tx pin on the GPS possibly being damaged by +5 V from the Arduino, if a previously loaded sketch made it an output and HIGH.

However you could just as easily upload a "do nothing" sketch like this:

    int main () { }

That is sound practice anyway, if you are connecting up new hardware and are not sure what the currently-loaded sketch does.


body:
I need vibration sensor for my project. I have found many sensors similar to [this one][1]. But it seems, that this sensor outputs only zeros for "non-hit" state and ones for "hit state". And I need something that can output levels of vibration, not only presence/abscense.

So is there any high-resolution vibration sensor for arduino?

Thank you!

  [1]: https://www.sparkfun.com/products/9196

title: Vibration sensor for arduino

Answers: 2

body:
I assume the OP wants the frequency of the vibration, which an accelerometer such as the ADXL345 won't give.

I have two workarounds: if the expected vibration frequency is low, say, under 100Hz, use instead an on/off vibration sensor (adafruit has them for under a dollar) and count the number of transitions. If it's more, how about a microphone and a band-pass filter?

body:
The MPU-6050 is a very low-price 3 axis gyroscope and accelerometer with both SPI and I2C interface options.

I found mine here:  https://smile.amazon.com/gp/product/B00KKR9ORI

----
EDIT:  Removed statement that it is accurate enough for this, based on comment.


body:
I am experimenting with low-power wireless arduino modules. For that, I needed 3V powered arduino so that I can do away with voltage regulators which eat up a lot of battery juice.

I am using 28 pin Atmega328p-PU dip IC with 8 MHz external crystal oscillator. Just for trying, I dumped the arduino pro mini 3.3V 8 MHz bootloader into it and it was a success. Everything is working as expected. However, I realized that SMD package which is being used in pro mini has 8 ADC pins compared to 6 in the DIP version.

Should I be worried about it?

Second feasible option is modifying the Arduino UNO board definition to use 8 MHz clock source as compared to 16 MHz and leave everything else same. Do you think this will serve my purpose?

title: Custom Bootloader on Atmega328p - PU - 28 pin DIP

Answers: 1

body: The Atmega328p has 8 analog inputs. Some packages (such as the DIP) don't have enough pins to bring all of them out, but they are in there. The SMD package brings all of them out, but it apparently the Pro Mini does not pick up two of them. The net result is the same - 6 useable and 2 unusable analog inputs.


body:
I have a device I'm working on and the only issue I'm running into is I can't manage to figure out how to get my LCD display to move around vertically with the joystick I have attached to it. I have a feeling with a tip this could be a very simple fix, but I'm just stuck. So the brief of this is that I need someone to fill in the ???'s for me provided in my example code.

    //Include the LCD Library.
    #include <LiquidCrystal.h>
    #include <Wire.h>
    //Declare the LCD object and define pins.
    #include <MFRC522.h>
    #include <SPI.h>

    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    #define SAD 10
    #define RST 5

    //Ignore The below line it is for the master code
    #define I2C_ADDR    0x27 // <<----- Add your address here.  Find it from I2C Scanner
    #define BACKLIGHT_PIN     3
    #define En_pin  2
    #define Rw_pin  1
    #define Rs_pin  0
    #define D4_pin  4
    #define D5_pin  5
    #define D6_pin  6
    #define D7_pin  7

    int n = 1;

    LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

    void setup() {

    //Booting the LCD
      lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
      lcd.setBacklight(HIGH);
      lcd.home (); // go home
      lcd.cursor();

    //Starting settings
      lcd.begin(1,0);
      lcd.clear();

    }

    //Sometimes you have to hit reset on the device

    //Joystick Defaults X=484 Y=513

    void loop() {
      lcd.setCursor(0,0);
      lcd.print("Example");
      delay(100);

    for (int positionCounter = 0; positionCounter = 1; positionCounter++) {
    if(analogRead(1) > 584) {
      lcd.scrollDisplayLeft();
      delay(30);
      } else if(analogRead(1) < 384) {
        lcd.scrollDisplayRight();
        delay(30);
      } else if(analogRead(0) < 413) {
         lcd.???????????????????();
         delay(30);
      } else if(analogRead(0) > 613) {
         lcd.??????????????????();
         delay(30);
        }
      }
    }

title: How do I scroll through the LCD vertically with joystick?

Answers: 1

body:
The LCD library provides easy functions that activate commands in the LCD itself.  The LCD doesn't have functions that do what you want, so there is no simple vertical scrolling like you're suggesting.

If you need to have it, you'll need to re-write the screen with the content you want to display when the user scrolls around. I can't make any specific suggestions as I don't know the reason you need to scroll around the display this way, but one comprehensive method would be to create a buffer of data the LCD should be displaying, then scroll it using software (move the bytes around the way you want) and then send that buffer to the LCD when it changes.

There may be other more applicable or easier tricks, but that would largely depend on your specific use case and user interface design.


body:
Recently, I have been playing around with a gyroscope and accelerometer in the hopes of building a quadcopter. I have plotted some of the data the two sensors and I am noticing that the pitch from the accelerator lags significantly behind the gyroscopic pitch.

From some research, I understand that these two are not going to equivalent values due to the mechanisms of measurement, however is it common to have such large discrepancies (i.e a difference of 20 degrees or higher) between the two sensors or is this an issue with my conversion?

I have listed the graph and source code [here][1]. Any help would be appreciated!

Sincerely,
Anand

  [1]: https://www.dropbox.com/sh/lemczvtzstgdhcj/AAAYqmxft7sWJ-tMkcKaA2d7a?dl=0

title: Comparing orientation data obtained using gyroscope and accelerometer

Answers: 1

body:
Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.

I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.

The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.

On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.

That's why you need a filter to combine them.

Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this [reading][1].

  [1]: http://en.wikipedia.org/wiki/Coriolis_effect


body:
I am trying to get values from this sensor **Airspeed v3** from eagle tree but it seems my I2C is not working properly.

I bought a module in third party mode and followed these [instructions][1] from the manufacturer website.

I went to rcgroups forum and discovered the right values for the bits mentioned in the documentation about WRITE and READ.

I started the development of a code but I cannot get the values from the sensor. It is supposed to send me a 2 byte-formatted value indicating the airspeed measured. But surprisingly when I call this method `Wire.requestFrom(AIRSPEED_ADDRESS, 2)` it returns 0, so someway the communication is not working. I have used I2C before for ADXL345 sensor and it works perfectly.

The results from these lines

    Serial.println(data[0]);
    Serial.println(data[1]);

  are just -1 indicating that no data is available to display.

Does anybody know how to get this working? Am I missing something?

This is my code right now.

    #include <Wire.h>

    #define AIRSPEED_ADDRESS  0xEA
    #define WRITE_BIT         0x00
    #define READ_BIT          0x01

    void setup() {
      // join I2C bus (I2Cdev library doesn't do this automatically)
      Wire.begin();
      Serial.begin(9600);
      Serial.println("Program started");
    }

    void loop() {
      byte data[2] = {0};
      int i = 0;
      int16_t velocidade = 0;

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      if (!Wire.write(WRITE_BIT)) {
        Serial.println("error sending write_bit");
      }
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      if (!Wire.write(0x07)) {
        Serial.println("error sending 0x07");
      }
      Wire.endTransmission(false);

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      if (!Wire.write(READ_BIT)) {
        Serial.println("error sending read_bit");
      }
      else {
        //Serial.println("ok sending read_bit");
      }
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Serial.print("bytes read from slave: ");
      Serial.println(  Wire.requestFrom(AIRSPEED_ADDRESS, 2) );
      data[0] = Wire.read();
      data[1] = Wire.read();
      Wire.endTransmission();

      velocidade = data[1] | (data[0] << 8);
      Serial.println(data[0]);
      Serial.println(data[1]);
      Serial.println(" ");

    }

  [1]: http://www.eagletreesystems.com/Manuals/microsensor-i2c.pdf

title: Reading data from airspeed v3 eagle tree

Answers: 2

body:
That's interesting but after using a different library the code worked out.

It has to follow exactly what the datasheet says in order to get things done.

The following source code makes it and get the airspeed from the sensor:

    #define SENSOR_ADDRESS 0xEA
    #include <Wire.h>
    #include <I2cMaster.h>
    TwiMaster AIRSPEED_SENSOR(true);

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

    long airspeed_update(void) {
      static struct {
        union { int16_t val; uint8_t raw[2];
        } airspeed16;
      } airspeedv3;

      long airsp;

      if(AIRSPEED_SENSOR.start(SENSOR_ADDRESS | I2C_WRITE)) {
        delay(10);
        AIRSPEED_SENSOR.write(0x07);
        delay(10);
        AIRSPEED_SENSOR.stop();
      }

      if(AIRSPEED_SENSOR.restart(SENSOR_ADDRESS | I2C_READ)) {
        delay(10);
        airspeedv3.airspeed16.raw[0]=AIRSPEED_SENSOR.read(false);
        delay(10);
        airspeedv3.airspeed16.raw[1]=AIRSPEED_SENSOR.read(true);
        delay(10);
        AIRSPEED_SENSOR.stop();
      }

      airsp=airspeedv3.airspeed16.val;
      return airsp;
    }

    void loop() {
      int airspeed = airspeed_update(); Serial.println(airspeed);
      delay(50);
    }

Get this library from [here][1].

  [1]: https://github.com/landis/arduino/tree/master/libraries/I2cMaster

body:
I found the I2C address on my Eagletree Airspeed V3 sensor to be 0x75 NOT 0xEA.

the following code adapted from first sample above works on my Nano:

    /*
     * note that timming is critical - see delay (5)
     * and bps set to 115200
     * works ok, but clean up 5-19-2019 jaf
     */

    #include <Wire.h>

    #define AIRSPEED_ADDRESS  0x75
    #define WRITE_BIT         0x00
    #define READ_BIT          0x01

    void setup() {
      Wire.begin();
      Serial.begin(115200);
      Serial.println("Program started");
    }

    void loop() {
      byte data[2] = {0};
      int i = 0;

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.write(WRITE_BIT);
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.write(0x07);
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.write(READ_BIT);
      Wire.endTransmission();

      Wire.beginTransmission(AIRSPEED_ADDRESS);
      Wire.requestFrom(AIRSPEED_ADDRESS, 2);
      data[0] = Wire.read();
      Wire.endTransmission();

      Serial.println(data[0]);
      delay(5);
    }


body:
For overcoming torque issues, I have attached 2 *identical* servos on a certain part of my robot arm and because I saw someone do the same.

Now, while writing code I realize:

    #include <Servo.h>
    ...
    ...
 shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179));
 shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179));
    ...

will turn `shoulder1` by 20* and then `shoulder2` by another 20*, ie. an overall turn of 40*; that too with too much load on servos, as the other servo would be inactive at the time first is active.

I want to achieve 20* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?
______
Can I possibly move them [both at the same time][1] - something like [multithreading][2] on arduino? Here's what I tried:

 void rotateTwoServoInSync(int angle) {
  for(int i = 0; i<angle; i++) {
   shoulder1.attach(9);
   shoulder1.write(i);
   shoulder1.detach();
   shoulder2.attach(10);
   shoulder2.write(i);
   shoulder2.detach();
  }
 }

Will it work? Is this approach recommendable?

  [1]: http://playground.arduino.cc/ComponentLib/servo
  [2]: http://forum.arduino.cc/index.php?topic=4854.0

title: How to control 2 servos at same time in sync?

Answers: 4

body:
`analogRead()` and `map()` are slow; only perform them once.

    unsigned char rot = map(analogRead(p1), 0, 1023, 0, 179);
    shoulder1.write(rot);
    shoulder2.write(rot);

body: If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.

body:
Spehro's answer is the most obvious. But note that there is no such thing as identical servos. You may stress them if you connect them through a stiff connection.

If you want to have two mechanical parts make the same movement the proper solution is to connect them mechanically, rather than have two servos doing the same action.

body: To operate two or more servos at the same time you need to interpolate their movements, first moving one servo a little, then moving the next one, back and forth until all servos arrive at their destination point. I haven't seen a library yet that accomplishes this for you so you probably need to write your own routine. Here is a project where I interpolated three servos and includes the code: https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/