body:
To ensure that relay doesn't switch between NO-NC when controller is *away* relay will need some memory.

Imagine having a 1 bit memory driving relay. If arduino dies/restart, its own GPIO may change, but relay's memory will remember last state and stay there, till controller instructs otherwise, granted relay circuit and its memory element don't lose power.

This also means there will be at least 2 lines required from uC to control this relay now.

I'd prefer to use some kind of serial shift register, e.g. [CD4094](http://pdf.datasheetcatalog.com/datasheet2/e/0zfy3x112ch42r82d060wl0jtocy.pdf), [CD4042](http://pdf.datasheetcatalog.com/datasheet2/9/0oqf0076icwadgde9su7g9oihq3y.pdf), [CD4099](http://pdf.datasheetcatalog.com/datasheet2/c/0ho1jgpu09kii6i650li4579diky.pdf) etc because that allows me to control more than one relays from same 2 lines on uC.

You may find some other part more suitable for your application.


sender: user

message:
Relay doing opposite to digital pin

I have a Arduino UNO with a Ethernet shield which hosts a basic HTML page with a button on it which controls a Relay module.

I'm trying to connect to a computer's power button so I can turn it on remotely.

I have found out that the relay basically does the opposite to the digital pin's output

Normally open Relay

HIGH = Open

LOW = Closed

I connected it through a NOT Gate made using a NPN transistor and it works perfectly how I wanted it.

Now to the question... Is there a way to write the code to make the digital pin = HIGH straight away and fast enough to not allow the relay to close the circuit and accidentally turn the computer on/off when the Arduino restarts, so I don't have to use a NOT Gate.

sender: assistant

body:
The relay module you have is this one from SainSmart:

* http://www.sainsmart.com/arduino/arduino-components/relays/sainsmart-2-channel-5v-relay-module-for-arduino-raspberry-pi.html

The schematic is like this:

[![enter image description here][1]][1]

As you can see you connect VCC to +5V and IN2 to your IO pin.  Setting the IO to LOW will then turn on the LED and the optocoupler together.

But that's not the only way you can connect it up.

Connect VCC to the IO pin and IN2 to GND instead.  Then you set your output HIGH to turn it on.

The arrangement shown in the schematic is commonly done because some MCUs are able to sink more current than they can source thorugh an IO pin.  That is not the case with an Arduino which has symmetric IO pins that can sink and source the same amount of current.

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


body:
I've solved the problem,
Thanks to everyone who helped.

I don't need a NOT gate anymore, here's what I added to make it work:

void setup() {

  startup();

}

void  startup() {

  digitalWrite(relay1, HIGH);

  digitalWrite(relay2, HIGH);

}

void loop() {

}

(I removed the rest of the code to keep it simple and easy to understand)


body:
Try This:

    const On  = LOW;    // For non inverted logic swap on and off.
    const Off = HIGH;
    const pump = 5;

    void setup() {
      pinMode(pump, OUTPUT);    // sets the digital pin 13 as output
    }

    digitalWrite(pump, On);
    digitalWrite(pump, Off);


message:
Altering code to run a timer while checking for a data input

I am rather new to the Arduino world and am looking for a way to create my own tipping rain gauge with only one Arduino(micro).

I have had some help from a friend to get a loop that checks for when a switch is closed, which signals that the bucket has tipped and thus "x units" of rain have fallen. The code I have for sensing this is:

    void loop()
    {
      /*
        digitalWrite(4, HIGH);
        delay(500);
        digitalWrite(4, LOW);
        delay(6500);
      */
      int analogValue = digitalRead(8);

      if (analogValue==HIGH)
      {
        Serial.println(count);
        count++;
        delay(250);
      }
    }

Then I developed a code to count up in 0.5 second intervals so that I could essentially time stamp when the switch from the first loop was closed/activated. The code for the timer is as follows:

    void loop()
    {
      while (ssec < 10)
      {
        Serial.print(hour);
        Serial.print(":");
        Serial.print(minute);
        Serial.print(":");
        Serial.print(sec);
        Serial.print(".");
        Serial.print(ssec);
        //Serial.print(" s");
        //Serial.println();
        ssec += 5;
        delay(500);
        Serial.println();
      }
      if (ssec == 10);
      {
        sec++;
        ssec = 0;
        //Serial.print(sec);
        //Serial.print(".");
        //Serial.print(ssec);
      }
      if (sec == 60)
      {
        minute++;
        sec = 0;
      }
      if (minute == 60)
      {
        hour++;
        minute = 0;
      }
      if (hour == 24)
      {
        Serial.println();
        Serial.print("DAY ");
        Serial.print(day);
        Serial.print(" COMPLETED!");
        Serial.print("Data Points: ");
        //Serial.print(count);
        Serial.println();
        Serial.println();
        hour = 0;
        day++;
      }
    }

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

Are there any ways to essentially run these side by side? Or a library I can use that will run the timer while i have the arduino looking for the switch to close, and I can simply call the timer when I need it?

Thank you for any and all help! :)

body:
What's with the double-spacing? It makes it hard to read.

    if(ssec==10);

That is wrong.

[Arduino programming traps, tips and style guide](http://www.gammon.com.au/tips#trap13)

> I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

I know StackExchange doesn't like link-only answers, but it is this or copy-and-paste:

[How to do multiple things at once ... like cook bacon and eggs](http://www.gammon.com.au/blink)


body:
You can find some 3rd party library that does software emulation of threads.
For example: [ArduinoThread][1].
With the use of such library I successfully developed an app that was switching LEDs on and off and at the same time listened to any data coming from Bluetooth (serial port). It is worth a try.

  [1]: https://github.com/ivanseidel/ArduinoThread


body:
If you do not need to know the timing when the event occurs with a high resolution, *and do not have anything else you need to do*, you can simply delay in short intervals and check the condition in between them.  Of course you will not know when the event occurred more precisely than knowing it happened sometime in the interval since the previous check.

Another approach is to not use the delay mechanism, but rather continually check the input in a loop, and also check the elapsed time so that you can accomplish your periodic events when intervals of time have elapsed.  Do be aware of the `millis()` overflow eventuality if taking this approach.

If you had important work to do while waiting, you could accomplish the check with a pin change interrupt, and record a timestamp in the interrupt service routine, but if all you would be doing in the foreground is running a delay, this is inferior to the previous approach.  Using an interrupt service routine (or any more elaborate form of threading) also requires care to ensure consistency of data shared between the main and interrupt or alternate thread context.

Ultimately the best solution for an actual real-world embedded application like this is typical to try to have the processor in a low powered sleep mode most of the time.  Typically you would have a low power real time clock running, but the processor's high speed clock and associated logic stopped.  Your tilt sensor would be wired as an interrupt that the MCU is configured to wake up to normal operation in response to.  On wakeup, it would read the clock to accomplish a timestamp, then go back to sleep.  You can also use various mechanisms in the real time clock or in the MCU to wake up periodically to announce the passing of time intervals.  Wakeup on a small MCU is typically a fairly efficient process - it can be beneficial in terms of net power consumption to go (at least partially) to sleep even for a fraction of a second.


body:
Yes, you can run the two `loop()` function side-by-side with a Multi-tasking Scheduler.

Please see https://github.com/mikaelpatel/Arduino-Scheduler. There are plenty of examples to get you started but basically you call `Scheduler.start()` with `loop()` functions. You will have to give them different names.

The Scheduler will context switch between the `loop()` functions on `yield()` or `delay()`.

Cheers!


message:
Problem assign float to an embed class within the Linked-list libary

I have successfully implemented some code which uses a linked-list.  Everything is working, except assigning a value to a float within the embeded class.  When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect.  However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug.  I am using codebender on Chrome, and I have tried Firefox (both given same results).

Main Sketch https://codebender.cc/sketch:175995

Example of library working https://codebender.cc/sketch:176008

Can anyone help?

    typedef void(*GF)(void);

    #include "LinkedList.h"

    class CsC {
     public:
      float PerS;
      GF FunctionToCall;
    };

    LinkedList<CsC*> TaskList = LinkedList<CsC*>();

    void LEDON()
    {
     digitalWrite(13,HIGH);
    }
    void after(float interval, String intervalDescription, GF func);

    void after(float interval, String intervalDescription, GF func)
    {
     float multi = 1;
     if(intervalDescription == "mins") multi *= 60;
     float delayMS = multi * interval;
     CsC *c;
     //Error if either of these lines uncommented
     //c->PerS=10000;
     //c->PerS=delayMS;
     c->FunctionToCall=func;
     TaskList.add(c);
     Serial.print(".");
    }

    void setup()
    {
     Serial.begin(9600);
     pinMode(13, OUTPUT);
     Serial.println("Start write task list");

     after(35,"secs",LEDON);

     Serial.println("Done");
     Serial.println("Start prog");
    }
    void loop()
    {
     Serial.print("List=");
     Serial.print(TaskList.size());
     while(TaskList.size()>0){
      CsC *c=TaskList.shift();
      long timeout=millis()+10000;
      //long timeout=millis()+((long)(c->PerS*1000.0));
      while(millis()<timeout){
       //To indicate it is running, and to save time, I have used a delay here
       digitalWrite(13,HIGH);
       delay(250);
       digitalWrite(13,LOW);
       delay(250);
      }
      c->FunctionToCall();
     }
     Serial.print(".");
     Serial.println("complete");
     while(1){}
    }

body:
One possible error is a memory leak as you did not allocate the memory to the class
Try

    CsC *c=new CsC();


message:
Formatting and code errors?

Hello I have managed to get both the Adafruit Datalogging shield walk-through and this individual code working http://www.learn.parallax.com/reed-switch-arduino-demo separately, but trying to combine the two together I get these errors. I think I have it all arranged correctly but any help would be greatly appreciated. Board Arduino Uno and Adafruit Datalogger shield.

Errors:

    Temp_and_Reed_Switch_data_logging_shield.ino:55:1: error: 'Serial' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:58:8: error: expected constructor, destructor, or type conversion before '(' token
    Temp_and_Reed_Switch_data_logging_shield.ino:61:1: error: expected unqualified-id before 'if'
    Temp_and_Reed_Switch_data_logging_shield.ino:66:1: error: 'Serial' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:70:1: error: expected unqualified-id before 'for'
    Temp_and_Reed_Switch_data_logging_shield.ino:70:21: error: 'i' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:70:30: error: 'i' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:80:1: error: expected unqualified-id before 'if'
    Temp_and_Reed_Switch_data_logging_shield.ino:84:1: error: 'Serial' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:85:1: error: 'Serial' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:87:1: error: 'Wire' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:88:1: error: expected unqualified-id before 'if'
    Temp_and_Reed_Switch_data_logging_shield.ino:95:1: error: 'logfile' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:97:1: error: 'serial' does not name a type
    Temp_and_Reed_Switch_data_logging_shield.ino:98:1: error: expected unqualified-id before 'if'
    Temp_and_Reed_Switch_data_logging_shield.ino:104:8: error: expected constructor, destructor, or type conversion before '(' token
    Temp_and_Reed_Switch_data_logging_shield.ino:105:8: error: expected constructor, destructor, or type conversion before '(' token
    Temp_and_Reed_Switch_data_logging_shield.ino:107:8: error: expected constructor, destructor, or type conversion before '(' token
    Temp_and_Reed_Switch_data_logging_shield.ino:108:13: error: expected constructor, destructor, or type conversion before '(' token
    Temp_and_Reed_Switch_data_logging_shield.ino:114:1: error: expected declaration before '}' token
    Multiple libraries were found for "SD.h"

     Used: C:\Users\Andrew\Documents\Arduino\libraries\SD

     Not used: C:\Program Files (x86)\Arduino\libraries\SD

    'Serial' does not name a type

Program:

    //  SD card datalogger
    // SD card attached to SPI bus as follows:
    // MOSI - pin 11
    // MISO - pin 12
    // CLK - pin 13
    // CS - pin 10

    #include "SD.h"
    #include <Wire.h>
    #include "RTClib.h"
    #include <SPI.h>

    #define LOG_INTERVAL  1000 // mills between entries
    #define ECHO_TO_SERIAL   1 // echo data to serial port
    #define WAIT_TO_START    0 // Wait for serial input in setup()

    // the digital pins that connect to the LEDs
    #define redLEDpin 4
    #define greenLEDpin 5

    // The analog pins that connect to the sensors

    #define tempPin 1                // analog 1

    RTC_DS1307 RTC; // define the Real Time Clock object
    const int chipSelect = 10;
    const int switchPin = 2;     //     // Reed switch to digital pin 2

    // the logging file
    File logfile;

    void error(char *str)
    {
      Serial.print("error: ");
      Serial.println(str);

      // red LED indicates error
      digitalWrite(redLEDpin, HIGH);

      while (1);
    }
    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial.println();
      //If we set WAIT_TO_START to anything but 0, the Arduino will wait until the user types something in.
    #if WAIT_TO_START
      Serial.println("Type any character to start");
      while (!Serial.available());
    #endif //WAIT_TO_START
    }

    // initialize the SD card
    Serial.print("Initializing SD card...");
    // make sure that the default chip select pin is set to
    // output, even if you don't use it:
    pinMode(10, OUTPUT);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
      Serial.println("Card failed, or not present");
      // don't do anything more:
      return;
    }
    Serial.println("card initialized.");

    // create a new file on SD Card called Logger number
    char filename[] = "LOGGER00.CSV";
    for (uint8_t i = 0; i < 100; i++) {
      filename[6] = i / 10 + '0';
      filename[7] = i % 10 + '0';
      if (! SD.exists(filename)) {
        // only open a new file if it doesn't exist
        logfile = SD.open(filename, FILE_WRITE);
        break;  // leave the loop!
      }
    }

    if (! logfile) {
      error("couldnt create file");
    }

    Serial.print("Logging to: ");
    Serial.println(filename);

    Wire.begin();
    if (!RTC.begin()) {
      logfile.println("RTC failed");
    #if ECHO_TO_SERIAL
      Serial.println("RTC failed");
    #endif  //ECHO_TO_SERIAL
    }

    logfile.println("millis,time,temp,reedswitch");
    #if ECHO_TO_SERIAL // attempt to write out the header to the file
    serial.println("millis,time,temp,reedswitch");
    if (logfile.writeError || !logfile.sync()) {
      error("write header");
    #endif   //ECHO_TO_SERIAL
    }

    pinMode(redLEDpin, OUTPUT);
    pinMode(greenLEDpin, OUTPUT);

    pinMode(switchPin, INPUT);        // switchPin is an input
    digitalWrite(switchPin, HIGH);    // Activate internal pullup resistor
    long lastDebounce1 = 0;
    long debounceDelay = 500;    // Ignore bounces under 1/2 second

    // If you want to set the aref to something other than 5v
    //analogReference(EXTERNAL);
    }

    void loop(void)
    {
      DateTime now;

      // delay for the amount of time we want between readings
      delay((LOG_INTERVAL - 1) - (millis() % LOG_INTERVAL));

      digitalWrite(greenLEDpin, HIGH);

      // log milliseconds since starting
      uint32_t m = millis();
      logfile.print(m);           // milliseconds since start
      logfile.print(", ");
    #if ECHO_TO_SERIAL
      Serial.print(m);         // milliseconds since start
      Serial.print(", ");
    #endif

      // fetch the time
      now = RTC.now();
      // log time
      logfile.print(now.get()); // seconds since 2000
      logfile.print(", ");
      logfile.print(now.year(), DEC);
      logfile.print("/");
      logfile.print(now.month(), DEC);
      logfile.print("/");
      logfile.print(now.day(), DEC);
      logfile.print(" ");
      logfile.print(now.hour(), DEC);
      logfile.print(":");
      logfile.print(now.minute(), DEC);
      logfile.print(":");
      logfile.print(now.second(), DEC);
    #if ECHO_TO_SERIAL
      Serial.print(now.get()); // seconds since 2000
      Serial.print(", ");
      Serial.print(now.year(), DEC);
      Serial.print("/");
      Serial.print(now.month(), DEC);
      Serial.print("/");
      Serial.print(now.day(), DEC);
      Serial.print(" ");
      Serial.print(now.hour(), DEC);
      Serial.print(":");
      Serial.print(now.minute(), DEC);
      Serial.print(":");
      Serial.print(now.second(), DEC);
    #endif //ECHO_TO_SERIAL

      delay(10);
      int tempReading = analogRead(tempPin);

      // converting that reading to voltage, for 3.3v arduino use 3.3
      float voltage = tempReading * 5.0 / 1024;
      float temperatureC = (voltage - 0.5) * 100 ;

      logfile.print(", ");
      logfile.println(temperatureC);
      logfile.print(", ");
      logfile.print(reedswitch);
    #if ECHO_TO_SERIAL

      Serial.print(", ");
      Serial.println(temperatureC);
      Serial.print(", ");
      Serial.print(reedswitch);
    #endif //ECHO_TO_SERIAL

      digitalWrite(greenLEDpin, LOW);
    }

body:
Everything you have written between the end of `setup()` (line 55) to the start of `loop()` (line 117) is not in a function.

If you are struggling to combine two or more programs, start small and work your way to the full code.


body:
Building furhter onto [@CharlieHanson's answer][1], what you should do in order to fix this is probably following changes (*please note that I wrote this in order to try to get rid of the errors, the flow of the program may still not be correct, that depends entirely on how you put together the code from the files*):

**1.** Remove the bracket at line 52, just a few lines down in the `setup()`-method, below this code:

    #endif //WAIT_TO_START

**2. (Maybe not nessecary, but for manageability)** Move this code:

    long lastDebounce1 = 0;
    long debounceDelay = 500;

-from where it currently is (just a few lines above the beginning of the `loop()`-method) to the other variable declarations (above the `error()`-method).

  [1]: https://arduino.stackexchange.com/a/17289/14429


message:
How can I connect more sensors when my lcd is blocking pin access?

So, I have a lcd that takes up the whole board of an arduino mega. I want to connect a temperature sensor and make a really lame weather station, but the lcd screen is totally in the road. It's a shield so this is to be expected.

I've come up with wacky ideas, like soldering to the rear of the board but I think that's a bad idea. Surely there must be a better way? The lcd shield exposes no pins.

body:
What you need is a shield that can go between the Arduino and the LCD shield and break out whatever connections you like.

They are generally available as "screw terminal" shields, such as this one from iTead:

* http://www.itead.cc/mega-proto-screw-shield.html


body: Sandwich an arduino protoshield in between and add the sensors to this board, or add some wires, so the sensor can be places "outside".


message:
How to resolve my Timer Interrupt issue

I am trying to work with arduino timer1 interrupts to make an led blink every bit on an 8 bit number, depending on whether its a 1 or 0. However, im trying to make a basic blinking program, and it does not seem to be working.

    #include “TimerOne.h”
    bool val=0;
    void setup()
    {
        pinMode(13, OUTPUT);
        Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
        Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
    }

    void callback()
    {
        val=1;
    }

    void loop()
    {
        digitalWrite(13,val);
        while(!val);
        val=0;
    }

The LED doesnt blink at all! Any help would be appreceitated!
thanks!

body:
I'm not surprised the LED doesn't blink - the entirety of your logic in the loop() function is so bizarre as to elicit the question:

# WTF?

Let's take a look at it line by line:

    digitalWrite(13,val);

Set the LED to whatever `val` is - `val` starts as 0, so the LED is off.

    while(!val);

While `val` is not anything except 0, so while val is zero, do nothing. (The interrupt would escape you from this if your `val` was `volatile`)

    val=0;

Set `val` to 0.

So how can `val` be anything except 0 when you do the digitalWrite?


body:
Try this instead.

    #include “TimerOne.h”
    bool val=0;
    void setup()
    {
        pinMode(13, OUTPUT);
        Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
        Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
    }

    void callback()
    {
        val=!val;
    }

    void loop()
    {
        digitalWrite(13,val);
    }


message:
Interfacing ADS8319 with Arduino UNO

I am using Arduino UNO and trying to interface 2 16-bit [ADS8319](http://www.ti.com/lit/ds/symlink/ads8319.pdf) ADCs with it via the SPI interface.

I have interfaced the 2 ADCs with the micro-controller using the "4 Wire CS Mode Without Busy Indicator" (data sheet page number 15).

I am using the following code to get the values from the ADCs.

<!-- language: c -->

    #include <SPI.h>
    #define CONVPIN 7
    #define SELPIN 8
    #define SELPIN2 4
    #define MISOPIN 12
    #define SCLKPIN 13

    int adcvalue;
    byte byte1; byte byte2;
    const float aRefVoltage = 5;
    float volts = 0;

    void setup() {

      // put your setup code here, to run once:
      pinMode(SELPIN, OUTPUT); // ADC's selection pin
      pinMode(SELPIN2, OUTPUT); // 2nd ADC's selection pin
      pinMode(CONVPIN, OUTPUT); // ADC's conversion pin
      pinMode(SCLKPIN, OUTPUT); // ADC's clock pin
      pinMode(MISOPIN, INPUT);  // ADC's data out
      SPI.begin();
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(CONVPIN, LOW);
      digitalWrite(SELPIN, HIGH);
      digitalWrite(SELPIN2, HIGH);
      digitalWrite(CONVPIN, HIGH);
      digitalWrite(SELPIN, LOW);

      delay(1000);

      byte1 = SPI.transfer(0x00); //transfer (read) 8 bits from the adc chip D15-8
      byte2 = SPI.transfer(0x00);  //transfer (read) the second 8 bits. D7-0

      adcvalue = (byte1 <<8) | (byte2 & 0xff);  // combine the 2 bytes to make our 16 bit word
      Serial.print("Voltage Value: ");
      Serial.println(adcvalue,BIN);
      volts = (adcvalue*aRefVoltage/65535);
      Serial.print(" Sensor Volts: ");
      Serial.println(volts,5);
      delay(1000);
    }

However i am not getting the right values. The ADC that ive selected by "digitalWrite(SELPIN, LOW);" should output 1V, whereas the values keep on changing in between 0 and 2.2 V .I am not sure if my code is correct or not. Can you please verify the code so that i should know whether the problem is in my hardware, or the code.

Below is the screenshot for my schematic :

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/w9F3v.png
  [2]: https://i.stack.imgur.com/jb2d8.jpg

Your helpful suggestions and comments would be appreciated !
Thankyou.

body: After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.


message:
How is AVR Assembly in Eclipse or at Linux command line done?

I'm trying to learn AVR development in C and Assembly for the Arduino Uno (Atmel 328p microprocessor) in Linux.

I've found many good guides on how to install and setup the AVR plugin for Eclipse, and I've no problem building and uploading C code.
However there doesn't seem to be any menu options for creating an assembler project, nor can I seem to find the correct syntax for using the cli avr-as for assembling my programs into a .hex file.

body:
If you don't mind using make, I'd recommend copying the Makefiles from [ChibiOS][1]. For me it works quite well and it's much more aligned to my daily experience with Linux.

  [1]: http://ChibiOS


body:
The Arduino IDE and the arduino eclipse plugin support assembly.
Taken from the platform.txt

    "{compiler.path}{compiler.c.cmd}" {compiler.S.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

compiler.S.flags is empty and so is compiler.S.extra_flags and builds.extra_flags

leaving us with something like

    avr-gcc -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {includes} "{source_file}" -o "{object_file}"

Which is something I think you can handle.


message:
TMP36 probe reading 0 on analog

I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin.

Here is an image of my circuit:

[![enter image description here][1]][1]

and my code:

    int length = 5;
    float airTemp = 32;

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

    void loop()
    {
      // loads current temperature into array
      int reading;
      float voltage;
      float temp[length];
      for (int i = 0; i < length; i++)
      {
        reading = analogRead(i);
        Serial.print(reading);
        voltage = reading * 5.0;
        voltage /= 1024;
        temp[i] = (voltage - 0.5) * 100;
      }

      // turns on/off fans based on current temperature
      for (int i = 0; i < length; i++)
      {
        pinMode(i, OUTPUT);
        if (temp[i] > airTemp)
        {
          digitalWrite(i + 8, HIGH);
        }
        else if(temp[i] <= airTemp)
        {
          digitalWrite(i + 8, LOW);
        }
      }
      delay(1000);
    }

I learned how to read the temperature from [here][2]. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.

  [1]: https://i.stack.imgur.com/TiksO.jpg
  [2]: https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor

body:
Make sure your breadboard isn't one of the ones with split power rails.  If the coloured lines on the + and GND rails have a break in them you will need to bridge that break with wire.

Solid rail:

[![enter image description here][1]][1]

Split rail:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/9qMjR.jpg
  [2]: https://i.stack.imgur.com/PPDh9.jpg


body:
I figured it out. I had the temperature sensors wired wrong.

Old (Bad):

[![enter image description here][1]][1]

Good:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/ys4yN.jpg
  [2]: https://i.stack.imgur.com/sOWWZ.jpg


body:
The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.

In other words, it is wired wrongly.


message:
Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller

I recently bought this linear actuator and motor controller from Pololu:

 - [Linear actuator][1]

 - [Motor Controller JRK21v3][2]

There are several steps that I have to follow in order to set this thing up before I can test it. These instructions can be found here: [Pololu JRK USB Motor Controller User’s Guide » Setting Up Your System][3]

I would like to program this using PWM method because I would like to keep the Serial RX for other sensors.  From my little experiment, by using a potentiometer, I noticed this pattern:

Position: Voltage

1. Fully extended : 0 V
2. At Rest : 2.35V
3. Fully Retracted  : 4.77V.

For this system, I will be controlling it using a PS2 controller. So, by using only the Y_axis of the analog joystick of a PS2 Controller (Up: 0, Rest: 128 and Down: 255), I program it as follows:

<!-- language: c -->

    //Move Linear Actuator with PS2 on JRK21v3 Controller

    #define pwm 6           //red wire
    #define dir 7           //yellow wire

    //PS2 controller
    #include <SoftwareSerial.h>
    #include <Cytron_PS2Shield.h>

    Cytron_PS2Shield ps2(10, 11); // SoftwareSerial: Rx and Tx pin

    void setup()
    {
      pinMode(pwm,OUTPUT);

      ps2.begin(9600);
      Serial.begin(9600);
    }

    void loop()
    {
      int Y_axis = ps2.readButton(PS2_JOYSTICK_RIGHT_Y_AXIS);  // 0 - 255
      Serial.print("Y_axis:");
      Serial.println(Y_axis);

      analogWrite(pwm, Y_axis);
    }

When I tested it, the linear actuator jitters/vibrates when it is at rest position. What could possibly cause this? Is it the duty cycle due to the PWM? How can I fix this or are there any other better methods?

  [1]: https://www.pololu.com/product/2305
  [2]: https://www.pololu.com/product/1394
  [3]: http://www.pololu.com/docs/0J38/5

body:
The [Pololu jrk 21v3](https://www.pololu.com/product/1394) motor controller supports four input modalities: via USB, via TTL-level serial, via RC / pulse width control, and via the mode you are trying to use, an analog 0-5V input.

It appears you are trying to use a PWM output to produce an analog signal control mode.  A PWM signal is a pulsed digital output rather than an analog signal.  The 21v3 may be jittering its control setpoint back and forth between 0V and 5V at a high frequency, which will make the linear actuator jitter.

Try adding an [RC low-pass filter](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=971&bih=588&q=RC+low-pass+filter&oq=RC+low-pass+filter&gs_l=img.12..0j0i30l6j0i5i30l3.963.963.0.2484.1.1.0.0.0.0.80.80.1.1.0....0...1ac..64.img..0.1.80.SfBLFQdVhSA) to the PWM output, ie between your PWM pin 6 and the input to the 21v3.  (Note, it might make more sense to use a software-serial output to control the 21v3, instead of using a PWM output with a low-pass filter, which may still allow use of hardware serial for your other sensors...)

To verify if an RC filter will work, try at first with large R (eg 5KΩ to 10KΩ) and large C (eg 5μF to 10μF) to see if the jitter goes away.  If so, you then can tune the filter to find how small you can make R or C and still avoid jitter.  A filter with smaller RC will allow higher-frequency control than will one with larger RC, but may be more prone to jitter.  R should be somewhat less than the input impedance of the 21v3's analog input.  To determine that value, look at the data sheet of whatever chip that input goes into.


body:
I got this working using the [Servo library][1].

 - You set the input method to PWM.
 - Connect your RX on the motor controller and hook it up to the servo pin.
 - Connect the ground of the Arduino to the ground of the JRK 21v3.
 - Then use the [knob servo sample][2] by hooking up a pot to a Arduino.
 - The calibrate the JRK 21v3 by selecting learn.

Now you can use the actuator as a servo.

  [1]: https://www.arduino.cc/en/Reference/Servo
  [2]: https://www.arduino.cc/en/Tutorial/Knob


message:
Detect if a chair is occupied using Arduino with some sensors

I want to detect if a seat is occupied by a person. This is [the answer][1] that I found on Stackoverflow.

However, how accurate is the output of 4 suggested sensors? Will the computing of all these 4 sensor values into one boolean recognize a case when, for instance, a box of 40kg is placed on a seat and some person is just slightly "shaking" that seat with a hand? In those cases Arduino should recognize that a seat is not occupied by a person. Will it work with only 4 sensors or is there any better and more accurate solution (maybe some existing library)? I guess that CapSense-Library is not applicable in my case.

  [1]: https://arduino.stackexchange.com/questions/1288/detect-and-stream-if-a-chair-is-occupied/1308#1308

body:
As has been mentioned in the comments there's many ways of sensing, each with its own pros and cons.

Sensing the presence of something is actually twofold.  First you need to know if there is something there, and secondly you need to try and identify *what* it is that's there and if it fits your criteria.

With passive sensors of the type used by Arduinos it all comes down to a matter of *probability*.

If you have force sensors, you know when *something* is there, but you can't work out *what* is there, only that it weighs a certain amount.

Using capacitative sensors you can get an idea about what the *something* is made of - how much does it affect the capacitance, etc.

Using ultrasound and/or infra-red beams etc you can get an idea of the kind of size of the object that is in the chair.

So combining them all together you can work out the likelihood that it is a human if:

* It weighs enough to be a human
* It has a suitable dielectric response to be a human
* It is big enough to be a human

Of course, there's always the chance that it's just a big dog, or a sack of potatoes.

So it's all a case of improving that probability by adding more sensors of different types, until you are *almost* certain that it is a human.  You will never be 100% certain, of course.


body:
I've also been trying to figure out a suitable idea for the same question.

 - Image processing would be so accurate in this but there are some problems with this approach, since there is a lot of code work and in case we want to implement this system in restaurant people might not agree.
 - Pressure sensors would work better for the  idea but there are some issues with this approach also. Just as mentioned in the question if there is some kind of a weight in the chair there will be an issue. also there are several chairs for a table in case of a restaurant so if we need to know whether the table is empty or not we will have to check whether all the seats are empty or not. In this case we need to pair the chair to the table using some method. we can also take this approach assuming that the chairs of the table will never change i.e. the same set of chairs remain for the same table.

The best approach for this particular scenario would be the sensors being in the table, or having a set of sensors such as a pressure sensor, thermal sensor, IR and verifying the seat is occupied.


message:
Gain on a receiver

I'm doing a project on the arduino with simple 433MHz antenna modules. And I was wondering if someone could offer clarifications on how receivers work.

I read that high gain receivers can pick up a very narrow beam of radio power and thus, can transfer data at high rates. Given that this signal is tightly focused to the transmitting end.

And a low gain receiver can pick up a much wider beam of radio power.

My question is the following. When they say "narrower beam" does that represent the amplitude of the signal or the number of different waves that are being transmitted? OR does it refer to the number of DIFFERENT frequencies it can pick up? Sorry, if my question is confusing. Happy to clarify any part of it.

My Source: http://www.qrg.northwestern.edu/projects/vss/docs/communications/2-what-are-high-and-low-gain.html

body:
Think of the receiver as a camera with a telephoto lens.

With the lens zoomed out you can see a large area.  You get visual information from all over.

With the lens zoomed in you can only see a very small area. The visual information you receive is only from a very small *field of vision* and things outside that field never get to you.

It's exactly the same with radio waves except that the shape of the antenna affects the zoom instead of lenses.


message:
GPS coordinates

how do I compare coordinates I receive from the GPS module with the coordinates that I had hardcoded into the arduino, for example:

if (GPS reading <= hardcoded)
   movecarforward();
else
   movecarback();

the coordinates I get keep going up and down which makes it difficult for me to compare and excute the function below.Please help.....

body: You could check out the codes for this reverse geocaching project at https://learn.adafruit.com/reverse-geocache-engagement-box/software or the dog collar project at https://learn.adafruit.com/gps-dog-collar to get some help. For my GPS project I just wanted to display the distance and speed, so all I had to do was save the current location, subtract it from the previous location and add it to distanceTraveled. It'd be helpful if you could share your code here.


message:
Read function in Software Serial

I have a question regarding how the read function works in Software Serial.

recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte.
For instance:
int x = rx.read(); //if the read is supposed to read 60, x prints 111100
int x = rx.read(); //if the read is supposed to read 226, x prints 11100010

How come the first statement doesn't print 00111100?

Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing.

body: For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.


message:
Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python

I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in [my earlier post][1]. I'm trying to find a sketch I could use to plot a continuous real-time graph on either Processing, MatLab or using Python MatPlot.

The accelerometer data is stored in arrays of `xArray[k]` for the x-coordinate values, `yArray[k]` for the y-coordinate values and `zArray[k]` for the z-coordinate values. How can I plot a real-time graph of these values? Thanks in advance.

  [1]: https://arduino.stackexchange.com/questions/17206/pushing-accelerometer-data-in-packets-from-an-arduino-due-to-the-pc-and-unto-pro

body:
I hope this is helpful to you.

First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.

Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20

Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.

This is what I did in Matlab. YPR = Yaw, Pitch, Roll

    data = fscanf(s);              %Read Data from Serial
    [Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');

Then you have to set up the plot and force matlab to update the plot in real time.

    %set() is used to set graphic object properties
           set(plotGraph1,'XData',time,'YData',Y,'color','r');
           set(plotGraph2,'XData',time,'YData',P,'color','g');
           set(plotGraph3,'XData',time,'YData',R,'color','b');
           drawnow;           %force matlab to updata plot instantaneously

The link below is a good place for you to get going. But you need to make some modifications to it though.

[https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/][1]

  [1]: https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/


body:
     import serial #import Serial Library
     import numpy  # Import numpy
     import matplotlib.pyplot as plt #import matplotlib library
     from drawnow import *

     accelX = []
     accelY = []
     accelZ = []

    arduinoData = serial.Serial('COM4', 115200)
    plt.ion()    #Tell matplotlib you want interactive mode to plot live data
    cnt = 0
    def makeFig():         #Create a function that makes our desired plot
    #plt.ylim(0,1000)                #Set the limit on the y axis
    plt.title('Sensor data')         #Set the title
    plt.grid(True)                   #Set The grid
    plt.ylabel('Axis Acceleration')  #Label the y axis
    plt.plot(accelX,'ro-', label='Raw X Acceleration') #Set the line plot
    plt.ylim(0, 1000)
    plt.legend(loc = 'upper left')
    plt2 = plt.twinx()  #Create a new object of plt2
    plt2.plot(accelY, 'b^-', label='Raw Y Acceleration')
    #plt2.ylim(0,1000)
    plt2.legend(loc='center right')
    plt2.ticklabel_format(useOffset=False) #Compel matplotlib not to autoscale
    #plt3 = plt.twinx()
    plt.plot(accelZ, 'go-', label='Raw Z Acceleration')
    plt.legend(loc='upper right')
    plt.ylim(0,1000)

     while True: #While loop that loops forever
       while(arduinoData.inWaiting() == 0):   #Wait here until there is data
        pass #do nothing
    arduinoString = arduinoData.readline() #read the line of text from serial
    dataArray = arduinoString.strip().strip('\n')  #Split into an array
    # Ensure that you are not working on empty line
    if arduinoString:
        dataArray = arduinoString.split(",")
    # Ensure that index is not out of range
    if len(dataArray) > 1:
        xAxis = int(dataArray[0]) #Convert first element to int insert in xAxis
        yAxis = int(dataArray[1]) #Convert second element to int insert in yAxis
        zAxis = int(dataArray[2]) #Convert third element to int insert in zAxis
        print xAxis, ",", yAxis, ",", zAxis
        accelX.append(xAxis)   #Build our x axis array by appending to accelX
        accelY.append(yAxis)   #Build our y axis array by appending to accelY
        accelZ.append(zAxis)   #Build our z axis array by appending to accelZ
        drawnow(makeFig)       #Call drawnow to update our live graph
        plt.pause(.0000001)
        cnt=cnt+1
        if(cnt>50):
            accelX.pop(0)
            accelY.pop(0)
            accelZ.pop(0)


body:
MATLAB has a [free add-on for connecting to Arduino hardware][1].

  [1]: http://www.mathworks.com/hardware-support/arduino-matlab.html


message:
How to extract number from a string?

[![enter image description here][1]][1]Using LabVIEW I am sending string of data through Xbee like,

 - u123
 - r64
 - r89
 - u34
 - r179

And my arduino is receiving this data.
I want my arduino to read this data as a string
and I want to extract numbers from these strings and feed it into two different servos.
For example from u123 I want to extract 123 and feed it to servo1 and from r64 I want to extract 64 and feed it to servo2 and so on.

Arduino IDE Serial Monitor is showing nothing but Arduino's Xbee is receiving and sending data. Don't know why :(

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

body:
First collect all of the characters up to the new-line (`\n' or line-feed) into an array of characters, and put a zero byte after the last one.

Since It looks like all of the strings you need to parse consist of one a single letter followed by the value you want, `value = atoi(inputArray[1];` will return the value as a 16-bit int. If it could be larger than 32767 but less than 65536 (probably not if you're driving a servo with it), then cast the value to unsigned.

If there might be an unknown number of characters (non-digits) preceeding the value, the C function `size_t strcspn(const char *string, const char *cset)` will return the length of the leading sub-string of `string` that does not contain characters in `cset`. So `value = atoi(inputArray[strcspn(inputArray, "0123456789")]);` will do the same thing, but calculating the array index of the first digit in the string.

(For completeness, note there is a companion function, `size_t strspn(const char *str, const char *cset);`, that returns the leading sub-string of 'string' consisting _only_ of characters in `cset`).


message:
Why can't I print this text to LCD?

I've been working on this for 4+ hours, and have gotten nowhere.

I have an array of weather conditions, and a number is sent over serial port to indicate which member of the array to print to the LCD.

I'm guessing the problem is in how I'm defining the array. These are my current 2 guesses for how to define it:

    String weatherConditions[49] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };
or:

    char weatherConditions[49][16] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

I've tried many other ways of defining the array (including "char* weatherConditions"), but I'm sure most of them were just ignorant guesses.

Later in the code I have this to display a member of the array:

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(weatherTodayHigh);lcd.print("/");lcd.print(weatherTodayLow);lcd.print(" ");lcd.print(weatherConditions[weatherCurrentConditionsCode]);
    lcd.setCursor(0, 1);
    lcd.print(weatherTomorrowHigh);lcd.print("/");lcd.print(weatherTomorrowLow);lcd.print(" ");lcd.print(weatherConditions[weatherTomorrowConditionsCode);
    break;

Everything I try ends up causing nothing to be printed on the 1602 LCD display (I have 15 other scrollable "screens" that are displaying just fine on the LCD). The earlier text on this screen (the highs and lows for today and tomorrow) is displaying fine, but after that, where the weather condition text is supposed to be shown, there is nothing.

I'm able to easily display the same weather condition text on the serial monitor (for that I was using "String weatherConditions[49] = {..." and then "Serial.println(weatherConditions[currentValue]);").

How can I get members of a text array to be printed on the LCD?

body: Ignacio hit the nail on the head. Once I moved the weatherConditions array to EEPROM, the sketch worked perfectly. Also the IDE stopped giving me errors about low RAM.


message:
How much voltage/current do I need for multiple chips?

I have a Huzzah ESP826 Wifi breakout chip which requires 3.3V power voltage and peaks at 500mA of current, and an LED strip which requires 12V and 1A.  How can I power both with one dc jack (I have a 12V 5A power supply) on one breadboard?

body:
You need a voltage regulator for the esp. Preferably a dc-dc step down, which will neither waste power nor heat up. Other, passive solutions are possible but not desirable. The regulator can be found on ebay amazon etc.

EDIT:

One more thing about the LEDs: depending on the model you have, they might or might not work with 3.3V input (I'm assuming you want to drive the LEDs from the esp).

In case they take only 12V input, you will need some interface solution, like [this one][1], for example.

  [1]: http://tobiscorner.floery.net/powerrgb/


message:
Synchronization and Implementing hamming code on Software Serial

I want to learn and use Hamming Code. Would it be wise to
alter the Software serial library to do this or just change the data being
transmitted in the actual Arduino sketch?

Also, for means of better synchronization, what would be the best method with regards to [these][1] tx/rx modules working with the Arduino using Software Serial. Am I constrained to using the built in synchronization from the library or may I also implement other forms of synchronization, like manchester and NRZ coding? If so, any guidance here?

**EDIT**

For implementing Hamming code, what if the interference occurs on the parity bit? Is there a way around this problem?

  [1]: http://rayshobby.net/cart/image/cache/data/acc/rf_pair-500x500.JPG

body:
The SoftwareSerial can only transmit and receive EIA-232 formatted packets.  That is what it is written to do, and that is what it does.

It cannot transfer any other format.

If you want to use other encoding techniques you will have to use a different method than SoftwareSerial.

That might involve writing your own bit-banging routines in your sketch or in your own library, or using SoftwareSerial as a basis to adapt into your own library.

Note that the SoftwareSerial library is written in such a way that EIA-232 packets are a requirement - the falling edge of the start bit triggers reception of one packet - any other encoding that doesn't have that kind of start bit arrangement would require some completely different method of arranging the reception.


body:
You can use this info and code: [Hamming(8,4) with Arduino][1].

There's a PDF with documentation about the process of creating a class that implements hamming(8,4) and a link to the source code.

You can use any class that derives from Stream (like Serial or SoftwareSerial).

  [1]: http://hykrion.com/arduino/hamming-8-4.html

**Edit:** If you want to implement a Hamming ECC in a Arduino it would be useful to precompute all the possible message values (you'll find more info at the link above). In a Hamming(8,4) your message is 1byte = 4bits + parity 4 bits; so you must divide your bytes in nibbles. It would be better to put all that stuff (code, decode, manage the upper/lower part of the byte, etc...) in a class. An example using the Hamming class from the link above:

Tx:

    #include <hamming.h>

    Hamming hamming(&Serial);
    char message[] = "Hello World!!";

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

    void loop()
    {
      hamming.write(message);
      delay(1000);
    }

Rx:

    #include <hamming.h>

    Hamming hamming(&Serial);
    char message[Hamming::SIZE];

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

    void loop()
    {
      if(hamming.isMessageReady())
      {
        hamming.read(message);
        Serial.println(message);
      }
    }

If you need to send other kind of info: a float, integer... you can do it, but I think it's a better idea to tokenize/detokenize your information and handle it like a "string".

P.S. You can use any kind of physical layer insofar as it's a child of Stream: Serial, SoftwareSerial...But I've only tested over Serial.


body:
Could look something like this:

    class HammingStream : public Stream {
    public:
      HammingStream(Stream& ios) : m_ios(ios) {}
      virtual size_t write(uint8_t byte);
      virtual int read();
      virtual int available();
      virtual void flush();
    protected:
      Stream& m_ios;
      uint8_t encode4(uint8_t nibble);
      uint8_t decode8(uint8_t code);
    };

    size_t HammingStream::write(uint8_t byte)
    {
       m_ios.write(encode4(byte >> 4));
       m_ios.write(encode4(byte & 0xf));
       return (1);
    }

    int HammingStream::read()
    {
      if (available() == 0) return (-1);
      uint8_t nibble = decode8(m_ios.read());
      return ((nibble << 4) | decode8(m_ios.read());
    }

    int HammingStream::available()
    {
      return (m_ios.available() / 2);
    }

    void HammingStream::flush()
    {
      m_ios.flush();
    }

Then you could:

    HammingStream HammingSerial(SoftwareSerial);
    HammingSerial.println(F("hello world"));

The above leaves out the encoding/decoding but also error detection. Hamming decoding can capture up to two bit errors and do one bit correction (on 4-bit data).

An example of implementation of the [coder][1] may be found in Cosa. Here Hamming(8, 4) is used to improve VirtualWire performance. Please note that the coder table is adjusted for RF and avoiding DC signal (i.e. long periods of zero or one).

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/HammingCodec_8_4/HammingCodec_8_4.hh


message:
Please explain this OneWire communication with Arduino Uno and DS2502-E48

The goal is to read the MAC address from a [DS2502-E48 ](http://pdfserv.maximintegrated.com/en/ds/DS2502-E48.pdf)chip.

I think I accomplished this goal too with the following code, but I can't get behind at how this works.
I had a similar program with a PIC chip as reference.

I checked several references about OneWire and the DS2502 but not the info I needed to hop to the right memory addresses.
Where'd I normally attain the information so that I know I have to write: **cc ,f0 , 0, 10** , read a *random* byte, and then I'm at the right position for MAC.

    #include <OneWire.h>

    OneWire ds(2);
    void setup()
    {
      Serial.begin(9600);

      byte i;
      byte dataLength;
      byte present = 0;
      byte data[12];
      byte addr[8];

      if ( !ds.search(addr)) {
        Serial.print("No more addresses.\n");
        ds.reset_search();
        delay(250);
        return;
      }

      ds.reset();
      ds.select(addr);

      delay(1000);     // maybe 750ms is enough, maybe not

      present = ds.reset();
      if (present != 1 )
      {
        Serial.println("No device present, exiting...");
        return;
      }

        ds.write(0xCC);//SKIP_ROM
        ds.write(0xF0);//READ_MEMORY
        ds.write(0);  // ?
        ds.write(10); // ?
        ds.read();    // ?
        dataLength = ds.read();

        for ( i = 0; i < dataLength; i++) {
        data[i] = ds.read();
        if ( i>3){
          Serial.print(data[i], HEX);
          Serial.print(" ");
        }
      }
    }

    void loop()
    {

    }

body:
I found a nice writeup on this on a [blog][1].  To quote his experimental findings:

> Comparing to the OneWire spec, we can tell it’s writing 0xCC, which
> should be SKIP_ROM. Following that is 0xF0 (ReadMem), and two bytes
> starting address: 0x08, 0x00.

Based on this, the zero and 10 that you are writing are apparently an address value.

  [1]: https://hclxing.wordpress.com/2014/02/09/hacking-a-dell-power-adapter-part-iii/


body:
From the DS2502 datasheet:

> **Skip ROM [CCh]**
>
> This command can save time in a single-drop bus system by allowing the bus master to access the
memory functions without providing the 64-bit ROM code. If more than one slave is present on the bus
and a read command is issued following the Skip ROM command, data collision will occur on the bus as
multiple slaves transmit simultaneously (open drain pulldowns will produce a wired-AND result).

> **READ MEMORY [F0h]**

> The Read Memory command is used to read data from the 1024-bit EPROM data field. The bus master
follows the command byte with a 2-byte address (TA1=(T7:T0), TA2=(T15:T8)) that indicates a starting
byte location within the data field. An 8-bit CRC of the command byte and address bytes is computed by
the DS2502 and read back by the bus master to confirm that the correct command word and starting
address were received. If the CRC read by the bus master is incorrect, a reset pulse must be issued and the
entire sequence must be repeated. If the CRC received by the bus master is correct, the bus master issues
read time slots and receives data from the DS2502 starting at the initial address and continuing until the
end of the 1024-bit data field is reached or until a reset pulse is issued. If reading occurs through the end
of memory space, the bus master may issue eight additional read time slots and the DS2502 will respond
with a 8-bit CRC of all data bytes read from the initial starting byte through the last byte of memory.
After the CRC is received by the bus master, any subsequent read time slots will appear as logical 1s until
a reset pulse is issued. Any reads ended by a reset pulse prior to reaching the end of memory will not have
the 8-bit CRC available.

So you are telling it that you want to read the memory from whatever device is on the bus, not any one specific one (since you are not needing to provide the ROM ID to identify the exat item on the bus), starting from address ((0 << 8) |10) = 10.

From the DS2502-E48 datasheet you can see the layout of the memory:

> The data record starts with a length byte (0Ah) and the 4-byte UniqueWare Project ID 00001129h. The
next 6 bytes contain the 48-bit node address which consists of an incrementing 24-bit extension identifier
and the IEEE-assigned 24-bit company ID value 006035h. An inverted 16-bit CRC ends the data record.
The remaining bytes of the 32-byte memory page remain unprogrammed. Neither the 24-bit extension
identifier nor the 24-bit company ID are related to the 64-bit ROM registration number. The ROM
registration number is used to provide a unique address to access the DS2502-E48 when multidropped on
a 1-Wire bus.

So translating that into something more pictorial:

    // Length byte
    0x00: 0x0A

    // UniqueWare PID
    0x01: 0x00
    0x02: 0x00
    0x03: 0x11
    0x04: 0x29

    // Serialization ("extension") number
    0x05: 0x??
    0x06: 0x??
    0x07: 0x??

    // Company ID Value
    0x08: 0x??
    0x09: 0x??
    0x0A: 0x??

    // 16-bit CRC
    0x0B: 0x??
    0x0C: 0x??

    // All the rest is EEPROM data
    0x0D - 0x7F: 0x??

So by starting at address 10 (0x0A) you are reading the last byte of the company ID, the CRC, and then whatever else is in the memory after that.

To read the entire MAC address (least significant byte first) you should be starting to read at address 5.


message:
Using L298N to control DC Motor

I am developing a system where I want to control the direction of the DC motor (12V) from Arduino Mega/Uno. For that, I am using L298N H-bridge chip without the board as shown below. [![L298N][1]][1]

My question is, do I need to add extra hardware or is it enough on its own?

Thanks in advance!

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

body:
In theory, this particular device should work on its own.  However you should search for and read the datasheet for it. (I'll leave you to do that yourself, just to make sure you really do read it.)

You should consider a heatsink too by the way, and provision for things like a fuse on the power, and whether you will be using a separate 5V for the logic (again you need the datasheet for that).


message:
C++ Namespace/scope problem when trying to attach arduino interrupt

I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:

 error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (*)()'

This is the cpp file:

    #include "RpmDriver.h"
    #include <Arduino.h>
    int currentRpm;
    long lastMillis;
    int pin;

    RpmDriver::RpmDriver(int Pins[])
    {
     pin=Pins[0];
     currentRpm=0;
     pinMode(pin,INPUT);
     lastMillis = millis();
     attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
    }
    RpmDriver::~RpmDriver(void)
    {}

    bool RpmDriver::GetData(char* dest,char* format)
    {
     sprintf(dest,format,currentRpm);
    }

    void RpmDriver::RPMInt()
    {
     double RPMConstant=40000;
     unsigned long newMillis=millis();
     unsigned long t = newMillis-lastMillis;
     t=100;//temp
     currentRpm=(t==0)?0:(int)RPMConstant/t;
     lastMillis=newMillis;
    }

and the header file is

    #pragma once
    class RpmDriver
    {
    public:
     RpmDriver(int pins[]);
     ~RpmDriver(void);
     bool GetData(char*,char*);
    private:
     void RPMInt(void);
    };

Any help much appreciated!

body:
You can't.

Simply because a class member is not the right format of function for attachInterrupt.

You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class.  How you arrange it so that it knows where your objects are is up to you.

* If you have only one object then assign it to a global pointer in your library using the constructor
* If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.


body:
You should qualify `RpmDriver::RPMInt()` as `static`.
Static member functions are very much like plain functions, only using
their class as a sort of namespace. Obviously, you will not be able to
access any member data, but this should not be a problem as it seems
your class is not storing any data anyway.


message:
Particle-like wifi configuration

Can anybody tell me how the [Particle (Photon/Core)](https://docs.particle.io/guide/getting-started/start/core/) WiFi *setup* works?

I am looking to mimic this WiFi configuration format for my own device.

The basic steps are as follows:

 1. Power device on; put in "listening mode" if not already active;
 2. Connect smartphone to the wireless network that you want to connect your device to;
 3. Open the Tinker/Spark/whatever-it's-called App on your smartphone; choose "Add New Device";
 4. Enter wireless password;
 5. Wait for device to be discovered by the App; device is now connected to WiFi.

How is the information (SSID, password) transferred from the smartphone to the device?

Thanks in advance.

body:
The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : [SimpleLink][1].

The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.

I've found on the George Howkins [Depletion Region blog][2]  multiple articles that explain how the CC3000 SimpleLink works.

 - [CC3000 Smart Config - transmitting SSID and keyphrase][3]
 - [CC3000 advertises presence on network via DNS-SD][4]

All the posts : http://depletionregion.blogspot.fr/search?q=smart+config

  [1]: http://www.ti.com/ww/en/simplelink_embedded_wi-fi/tools_software.html
  [2]: http://depletionregion.blogspot.fr/
  [3]: http://depletionregion.blogspot.fr/2013/10/cc3000-smart-config-transmitting-ssid.html
  [4]: http://depletionregion.blogspot.fr/2013/10/cc3000-advertises-presence-on-network.html


message:
Can I access individual pixels on my 16x2 LCD display

I have a generic 16x2 LCD display connected to my Arduino.  I can use the standard LCD library to display characters, but are there way to turn on and of individual pixels?

body:
It's possible to define custom characters for “generic 16x2 LCD displays” [ie, displays based on HD44780 or equivalent controllers], but only up to eight such characters at the same time.  See [LiquidCrystal.CreateChar](https://www.arduino.cc/en/Reference/LiquidCrystalCreateChar) for details.  See page 2 and part of page 1 of the [Print degree symbol ° on LCD](http://forum.arduino.cc/index.php?topic=19002.0) arduino.cc thread for create-character examples that don't use the library.  Page 1 of that thread also shows a table of all the characters built into typical HD44780 controllers, some of which may perhaps meet your needs.

For pixel-by-pixel LCD control, look at graphics LCDs, eg the [KS0108](http://playground.arduino.cc/Code/GLCDks0108) or [LCD12864](http://playground.arduino.cc/Code/LCD12864) and similar.


message:
Connecting two arduinos using WiFi

I have two arduinos (An UNO R3 and a Mega 2560), and I need to communicate them via two ESP8266 modules to exchange some values.

In one arduino I'll use a SW-420 vibrarion module, and I need to send a value wirelessly to the other board, which it'll have an LCD screen that will display a message when a value is recieved.

How can I do that with that specific WiFi modules? Thanks in advance

body:
Step 1: I would load NodeMCU on you ESP8266: https://github.com/nodemcu/nodemcu-firmware

Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en over serial connection

Step 3: write a TCP server:

    srv=net.createServer(net.TCP)
    srv:listen(80,function(conn)
      conn:on("receive",function(conn,payload)
        print(payload) //This payload will be send to your arduino over soft serial
        conn:send("<h1> Hello, NodeMCU!!! </h1>")
      end)
      conn:on("sent",function(conn) conn:close() end)
    end)

Step 4: write a TCP client:

    suc = false;
    function sendData( host, pathData )
     suc = false;
     print("GoSending!");
     -- A simple http client
        conn=net.createConnection(net.TCP, 0)
        conn:on("receive", function(conn, payload)
         if(string.find(payload, "200 OK")~=nil) then
          suc = true;
          print("AllDone")
         else
          suc = false;
         end
        end)
        conn:on("connection", function(c)
         print("connected");
            conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n"
                .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
            end)
        conn:on("disconnection", function()
         if(suc==false) then
          print("ErrorSending")
         end
        end)
        conn:on("reconnection", function() print("reconnection") end )
        conn:connect(80,host)
    end

Step 5: Connect your esp boards with software serial to the arduino

Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData)

Step: 7 Parse the Data on sofserial read on the second arduino

Step 8: DONE!

**EDIT:**

Ok more infos on step 6.
If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection.
So, this is some example code for your ardoino if you got the script from above:

    SoftwareSerial wifi(3, 2); // RX, TX

    //at some time in your programm
    //Build up your string that will be send over serial
    String i1 = "sendData(\"ipFromTheServer\", \"send.php?d=";
    String i2 = i1+dataToSend;
    String i3 = i2 +"\");";
    wifi.println(i3);

This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)

More infos on step 7.
the script on top will always print all incoming data. So you just have to read serial data on wifi:

    if (wifi.available())
        Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data!

Info: I've build this on my own... dont know if this is best practice :)


message:
Arduino Mega, Ubuntu, Time.h: No such file or directory

I'm using an Arduino Mega with Ubuntu 15.10.

Sadly I've got an error during compilation, that the Time.h library cannot be found. The verbose compile output shows:
<pre>
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall
-fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega2560
-DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105
-D__PROG_TYPES_COMPAT__
-I/usr/share/arduino/hardware/arduino/cores/arduino
-I/usr/share/arduino/hardware/arduino/variants/mega
-I/usr/share/arduino/libraries/LiquidCrystal
-I/usr/share/arduino/libraries/SPI
/tmp/build6998056390288565759.tmp/Home_Guard.cpp -o /tmp/build6998056390288565759.tmp/Home_Guard.cpp.o
**Home_Guard.ino:2:20: fatal error: Time.h: No such file or directory**
compilation terminated.
</pre>
I've already tried to use "time.h" instead of "Time.h" but it doesn't help.

body: ok. It seems that the Ubuntu arduino package does not contain this library. The file Time.zip has to be downloaded from the authors website: http://www.pjrc.com/teensy/td_libs_Time.html and added in the Arduino GUI menue bar: Sketch -> Import Library -> Add Library


message:
What is the best arduino board for a robotic arm?

In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).

So, what's the most **suitable** arduino board to build this arm?
I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.

My regards.

body:
If you are hoping to drive the arm straight from the Arduino, that's not going to work.

What you should do is:

 - Define the maximum weight and size of the load your arm will carry.
 - Define expected precision and speed of the movements.
 - Count the Degrees of Freedom (DoF) your arm will need (1 DoF = 1 simple joint)
 - Figure out size and materials of each part of the arm
 - Calculate the torque required at each joint (yes, you need some basic physics calculation)
 - Identify the motors you want to drive (DC are inexpensive but not very well suited for this, without lots of additional control logic & HW - stepper motors are better, but they still do require some additional effort - servos are the easier way but they are a bit more expensive)
 - Define the requirements for both the micro controller and the power supply, based on the previous choice.

If you can refine your question, based on the few points I sketched, you will get ahead much faster and with less risk later on to have to backtrack and re-design something.

You might have already answered some of those steps, then I suggest you list here your choices.

Similarly, if you are referring to some link you found (instructables, etc.) please post it.

As reference, hobbyking has an extensive catalog of motors and power supplies. You can find the same items also on ebay, but hobbyking can be used at least as reference for various specs (power, torque, weight, etc.).


body:
Best answer is Arduino Uno because it is enough for your application.

But all Arduino are works on 5 volt or 3.3 volt.

For operating 12 volt devices use transistors or MOSFETs.


message:
Playing Melody with Tone() without using delay()

Is there a method to play a Melody with Tone() without using the delay() function?

    tone(8, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration;
    **delay(pauseBetweenNotes);**

body:
As others have noted, this can be done using the same method as used in the standard 'BlinkWithoutDelay' example sketch, and combining that with a state-machine type approach. In a simple state machine you'd assume you can be in one of two states: outputting a tone, and not outputting a tone.

Applying these ideas to your code snippet above:

    // BEFORE SETUP
    const int tonePin = 8;
    unsigned long previousMillis = 0;
    const long interval = pauseBetweenNotes;
    const long interval = noteDuration;
    boolean outputTone = false;                // Records current state

    // IN LOOP
    unsigned long currentMillis = millis();

    if (outputTone) {
    // We are currently outputting a tone
    // Check if it's been long enough and turn off if so
        if (currentMillis - previousMillis >= noteDuration) {
            previousMillis = currentMillis;
            noTone(tonePin);
            outputTone = false;
        }
    } else {
    // We are currently in a pause
    // Check if it's been long enough and turn on if so
        if (currentMillis - previousMillis >= pauseBetweenNotes) {
            previousMillis = currentMillis;
            tone(tonePin, melody[thisNote]);
            outputTone = true;
        }
    }


body:
Adding a bit to kabdulla's great example, to be able to use a MelodyArray

    // declaring variables
    const int tonePin = 10;
    unsigned long previousMillis = 0;
    const long pauseBetweenNotes = 250;   // interval between notes (ms)
    const long noteDuration = 400;        // (ms)
    boolean outputTone = false;                // Records current state
    const int MelodyLength = 2;
    const int Melody[MelodyLength] = {880, 698};
    int MelodyIndex = 0;
    unsigned long currentMillis;

    void setup() {
    }

    void loop() {
      currentMillis = millis();
      PlayMelody();
    }

    void PlayMelody() {
      if (outputTone) {
        // We are currently outputting a tone
        // Check if it's been long enough and turn off if so
        if (currentMillis - previousMillis >= noteDuration) {
          previousMillis = currentMillis;
          noTone(tonePin);
          outputTone = false;
        }
      } else {
        // We are currently in a pause
        // Check if it's been long enough and turn on if so
        if (currentMillis - previousMillis >= pauseBetweenNotes) {
          previousMillis = currentMillis;
          tone(tonePin, Melody[MelodyIndex]);
          outputTone = true;
          //Update to play the next tone, next time
          MelodyIndex = MelodyIndex + 1;
          if (MelodyIndex >= MelodyLength) {
            MelodyIndex = 0;
          }
        }
      }
    }


body:
this is a minimal modification of the basic Arduino toneMelody example to a non-blocking version

```
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

unsigned long previousMillis = 0;
unsigned long pauseBetweenNotes;
int thisNote;

void setup() {
}

void loop() {

  // iterate over the notes of the melody:
  unsigned long currentMillis = millis();
  if (thisNote < 8 && currentMillis - previousMillis >= pauseBetweenNotes) {
    previousMillis = currentMillis;

    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    pauseBetweenNotes = noteDuration * 1.30;

    thisNote++;
  }
}
```


message:
Any way to pass EthernetClient to function outside of loop automatically?

I have an Arduino webserver that displays many buttons over a webpage (73 at the moment) that toggle different switches. I shortened up the button-drawing code with this function:

    void displayButton(String toggleName, byte toggle, byte link1, EthernetClient & client, boolean last) {
      if (toggle == 0) client.print("<a href=\"/?");
      else client.print("");
      client.print(toggleName);
      client.print("");
      if (last) client.print("

");
    }

And this is a shortened version of my loop function:

    void loop() {
      EthernetClient client = server.available();
      if (client) {
        boolean done = false;
        while (client.connected() && !done)
        {
          while (client.available () > 0 && !done)
            done = processIncomingByte (client.read ());
        }  // end of while client connected
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.print("");
          displayButton("F8", f8Toggle, 57, client, 0);
          displayButton("F9", f9Toggle, 58, client, 0);
          displayButton("F10", f10Toggle, 59, client, 1);
          client.println("");
          delay(5); client.stop();
      } // end of "if client"
    } // end of loop

I'm wondering if there's any way to have the displayButton function use the EthernetClient instance without it having to be passed every time. I'm interested in this in order to clean up my code a little (since I would be able to remove 73 instances of the word "client"), and also as a learning experience.

body: As Majenko has noted in the comments, the solution was to declare "EthernetClient client;" as a global variable, outside of the loop. Normally I would've tried something like this on my own, but was hesitant to do so because I had never seen anything like that in other code.


message:
Create a device to detect object state

Here is what I want to do or get it done (since I am not a embedded guy)...

 - create a prototype with Arduino to detect open window/door of my room using camera(image processing/object state detection)?
 - that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open or not and will sound an alarm if it is open.
 - prototype should work in dark as well
 - No false alarms
 - Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

My questions are..

 - Is it possible? :)
 - What all things I need to create a prototype?
 - Which camera should I use? Camera should be really small.
 - Are algorithms available to detect it?

body:
Your answers :-)

 - yes, it's possible and should not be too complex
 - for a simple prototype, you do not need an embedded device, just a PC with a webcam
 - a webcam with few megapixels should be enough
 - try [OpenCV][1]

After your prototype is ready, you can use a small PC-like platform.
Examples: [Minnowboard][2], [Edison][3], [BeagleBone][4], [RaspBerry PI 2][5], [Arduino Yun][6], [Galileo 2][7]

A word of warning: depending on the expectations you have, you will have to pick more powerful models. Computer Vision is computationally intensive.
The examples I gave are roughly sorted by performance and, unsurprisingly, cost. OpenCV is available for many architectures, but afaik, it is particularly optimized for x86, since it's mostly sponsored by Intel.

Disclosure: I work for Intel, so I am more informed on Intel products, but by no means I'm trying to do advertisement, this answer is simply given to the best of my knowledge.

  [1]: http://docs.opencv.org/2.4/doc/tutorials/tutorials.html
  [2]: https://www.google.com/aclk?sa=l&ai=CsNmY_dM0VuiRFuKBzAOcxJDgDdGgyKIH8efl4LMC_cvtnrYCCAAQAWD3AaAB3equ_gPIAQGqBCdP0M5kw2YT3Obbzfo8B3d9qayKUzbCXrPpIufHz_uQFQPIWMXZfWaAB4uV0QGIBwGQBwKoB6a-G9gHAQ&sig=AOD64_3sTdZzbZkDAbC22hPrSwlSylgCpQ&clui=0&q=&ved=0CBsQ0QxqFQoTCL3Vz7357MgCFYGocgodxggEyw&adurl=http://netgate.com/turbot/
  [3]: http://www.intel.com/content/www/us/en/do-it-yourself/edison.html
  [4]: http://beagleboard.org/bone
  [5]: https://www.raspberrypi.org/products/raspberry-pi-2-model-b/
  [6]: https://www.arduino.cc/en/Main/ArduinoBoardYun
  [7]: http://www.intel.com/content/www/us/en/embedded/products/galileo/galileo-overview.html


body:
I wonder if you haven't overspecified the device? Is there a reason that it must be photo-interpretive? Because if you only need to know whether a door or window is open, a couple of switches and some simple wired logic, or the very most basic of micro-controllers, if you choose to go that way, will be more than adequate, less expensive, more reliable in the long term (Ok, I know you won't be in a dorm room for long), less prone to false or missed alarms, totally unaffected by the ambient lighting or the lack of it, unobtrusive (no cameras - plural - in the middle of the room).

But I get that it might not be as much fun to make, if that is one of your top criteria!


body:
I doubt you could make such a thing, especially with no embedded experience.

* You want to use a camera, but it should "work in the dark" - problem there. You would need to somehow "light" the room with (say) infra-red, but then technically it wouldn't be dark any more.

* It should be really small, but has to have the power of image capture and image processing. Maybe a dedicated board designed by people with a lot of experience, and using surface-mounted devices, could do that. I strongly doubt you could do it on an Arduino of any type.

* No false alarms? Without knowing your windows that might be hard to say, but considering windows are usually made of glass, detecting the difference between a closed window, and a wide-open one, might be marginal as you would still see the scene outside through the glass.

* As the sun rises and falls the image captured would change considerably, quite probably leading to false alarms. Imagine a sudden thunderstorm, where the next image is much darker than the previous one. The image comparison would register a "difference".

* Imagine a picture taken during a storm with lightning flashes corrupting the image.

* What is someone enters the room and walks in front of the window? That would register as a difference, but doesn't mean the window is open.

---

What seems much more practical to me would be variants of existing technologies, eg.

* Magnets and reed switches

* Shine a laser on the window and detect if it moves (the angle would probably change).

* Use distance-detection, such as pinging devices. An open window would change the distance (a bit).

* Use passive infra-red to detect the movement when the window opens.

* Vibration detection mounted on the window glass, or possibly the window frame.

* Temperature measurement to detect a difference in temperature as the window opens.

---

The camera sounds to me the least practical.


body:
> Here is what I want to do or get it done (since I am not a embedded
> guy)...

Welcome to the world of embedded... things. I highly appreciate your interest in the embedded world, after all it's more interesting as just PC things :)

> - create a prototype with Arduino to detect open window/door of my room

You've come to the right place, Arduino (embedded stuff) is very good at input/output. And that seems like a fun project!

> using camera(image processing/object state detection)?

Wait, where did this come from? Humans are good at observing, their main sense would be vision (I guess?) to do so. Microcontrollers are somewhat better at logic signals. They are good at taking sensor signals and turning them into whatever you like.
*There is a possibility you'd just like to do something with image processing/detection. If so, please mention that :)*

> - that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open
> or not and will sound an alarm if it is open.

Arduino can read out a simple ["Door sensor"][1] and check if the door is, or is not closed. This will both shrink your project and make it easier.
Arduino can sound an alarm. You can even add a keypad (for a disable code).

>  - prototype should work in dark as well

The drawback of human vision. Is that it does not work so well in the dark. Sensor's based on the touch of the door or a magnetic contact on the door are not affected by darkness.

>  - No false alarms

If your sensor won't fail, the alarm won't go off by accident :)

>  - Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

Use an arduino nano or micro.

> My questions are..
> - Is it possible? :)

Yup! You can check for [existing projects][2] on the web. You can put in your own implementation though.

> - What all things I need to create a prototype?

Whatever you need is what you will need.
An sensor as input, an arduino to process it and an "alarm".
There are a trillion configurations for this, you can choose to just go by one or check what fits your needs best.

>  - Which camera should I use? Camera should be really small.

Unless you really want to get going with camera detection/object tracking, you shouldn't use one. (Especially with arduino it can be quite frustrating.) You should use a PC or raspberry Pi or Android phone.

Or use arduino with said sensor.

 - Are algorithms available to detect it?

Yes. For this, it's again application specific. You should check out some resources, check what others use and determine what would work best for you. Try it out and if it won't work you can ask it :) (probably on normal stack-overflow since it's not really arduino related, maybe robotics stackexchange).

  [1]: https://www.adafruit.com/products/375
  [2]: http://www.instructables.com/id/Getting-the-required-components/


message:
PC <-> Xbee <-> Another Xbee Communication

I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.

The hardware configuration I'm using to achieve that is the following:

    PC <--> Arduino with an Xbee <--> Another Arduino with another Xbee

It's just half-duplex communication. Everything seems easy, but there is a problem.

Each Arduino has an Xbee Shield with an Xbee module connected to it.
Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:

*"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of 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**.*

*With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), 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, 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**."*

That means I will not be able to build what I want with this configuration?
I already tried, but didn't work.

body:
Basically with your shield you have two options:

1. Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.
2. Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.

Neither of which are particularly ideal.  The first option is completely out since that rules out all PC communication.  The second option turns the Arduino into just a USB->TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).

What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee.  That will leave the Arduino's TX and RX pins free for communicating with the PC.

Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.


message:
How can i change "+" sign into spaces?

I'm working with esp8266.i am able to send text from webserver to arduino which is displayed on my 16*2 lcd display.but the problem is that when i send text including space i.e:john smith, the text show on my serial monitor and also in lcd  like that (john+smith)..the spaces i gave is converted into "+" sign..Can anyone suggest me how to overcome from that problem??
my code is given below:

      #include <SoftwareSerial.h>
      #include <LiquidCrystal.h>

     SoftwareSerial espSerial(2,3);

      LiquidCrystal lcd(12,11, 7, 6, 5, 4);

    const bool printReply = true;
    const char line[] = "-----\n\r";
    int loopCount=0;

    char html[50];
    char command[20];
    char reply[500];

    char ipAddress [20];
    char name[30];
    int lenHtml = 0;
    char temp[5];

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

          Serial.println("Start\r\n\r\n");

          lcd.print("WELCOME ");

          espSerial.begin(9600);

          Serial.println("reset the module");
          espSerial.print("AT+RST\r\n");

          getReply( 2000 );

          Serial.println("Change to station mode");
          lcd.clear();
          lcd.print("station mode");
          espSerial.print("AT+CWMODE=1\r\n");
          getReply( 1500 );

          Serial.println("Connect to a network ");
          lcd.clear();
         lcd.print("connecting...");

          espSerial.print("AT+CWJAP=\"ESP_E61A83\"\r\n");
          getReply( 6000 );

          Serial.println("Get the ip address assigned by the router");
          espSerial.print("AT+CIFSR\r\n");
          getReply( 1000 );

          int len = strlen( reply );
          bool done=false;
          bool error = false;
          int pos = 0;
          while (!done)
          {
               if ( reply[pos] == 10) { done = true;}
               pos++;
               if (pos > len) { done = true;  error = true;}
          }

          if (!error)
          {
                int buffpos = 0;
                done = false;
                while (!done)
                {
                   if ( reply[pos] == 13 ) { done = true; }
                   else { ipAddress[buffpos] = reply[pos];    buffpos++; pos++;   }
                }
                ipAddress[buffpos] = 0;
          }
          else { strcpy(ipAddress,"ERROR"); }

          Serial.println("Set for multiple connections");
          espSerial.print("AT+CIPMUX=1\r\n");
          getReply( 1500 );

          Serial.println("Start the server");
            lcd.clear();
          lcd.print("Server starts");
          espSerial.print("AT+CIPSERVER=1,80\r\n");
          getReply( 1500 );

          Serial.println("");

       lcd.clear();
          Serial.println("Waiting for page request");
          Serial.print("Connect to "); Serial.println(ipAddress);
          Serial.println("");
    lcd.print("feed me more");
    delay(1500);
            lcd.clear();

    }

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

              bool foundIPD = false;
              for (int i=0; i<strlen(reply); i++)
              {
                   if (  (reply[i]=='I') && (reply[i+1]=='P') && (reply[i+2]=='D')   ) { foundIPD = true;    }
              }

              if ( foundIPD  )
              {

                  loopCount++;

                  int nameStartPos = 0;
                  for (int i=0; i<strlen(reply); i++)
                  {
                       if (!haveName)
                       {
                             if (  (reply[i]=='n') && (reply[i+1]=='a') && (reply[i+2]=='m') && (reply[i+3]=='e')  && (reply[i+4]=='=') )
                             {
                                 haveName = true;
                                 nameStartPos = i+5;
                             }
                       }
                  }

                  if (haveName)
                  {
                        int tempPos = 0;
                        bool finishedCopying = false;
                        for (int i=nameStartPos; i<strlen(reply); i++)
                        {
                             if ( (reply[i]==' ') && !finishedCopying )  { finishedCopying = true;   }
                             if ( !finishedCopying )                     { name[tempPos] = reply[i];   tempPos++; }
                        }
                        name[tempPos] = 0;
                  }

                  if (haveName) { lcd.clear(); lcd.print("TEACHERS INFO..");Serial.print( "name = ");lcd.setCursor(0,1);Serial.println(name);lcd.print(name);Serial.println("");lcd.print(""); }

                  else          { Serial.println( "no name entered");   Serial.println("");lcd.print(""); }

                  strcpy(html,"");
                  strcpy(command,"AT+CIPSEND=0,25\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  strcpy(html,"
TEACHERS INFORMATION WEBSERVER
");
                  strcpy(command,"AT+CIPSEND=0,40\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  strcpy(html,"
CREATED by jack
");
                  strcpy(command,"AT+CIPSEND=0,31\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  strcpy(html,"
 Teachers Request number ");
                  itoa( loopCount, temp, 10);
                  strcat(html,temp);
                  strcat(html,"
");

                  // need the length of html
                  int lenHtml = strlen( html );

                  strcpy(command,"AT+CIPSEND=0,");
                  itoa( lenHtml, temp, 10);
                  strcat(command, temp);
                  strcat(command, "\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                 if (haveName)
                 {

                      strcpy(html,"
TEACHER name is "); strcat(html, name ); strcat(html,"
");

                      lenHtml = strlen( html );
                      strcpy(command,"AT+CIPSEND=0,"); itoa( lenHtml, temp, 10); strcat(command, temp); strcat(command, "\r\n");
                      espSerial.print(command);
                      getReply( 2000 );
                      espSerial.print(html);
                      getReply( 2000 );
                 }

                  strcpy(html,"<form action=\""); strcat(html, ipAddress); strcat(html, "\" method=\"GET\">"); strcat(command, "\r\n");

                  lenHtml = strlen( html );
                  itoa( lenHtml, temp, 10);
                  strcpy(command,"AT+CIPSEND=0,");
                  itoa( lenHtml, temp, 10);
                  strcat(command, temp);
                  strcat(command, "\r\n");

                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  strcpy(html,"Name:
<input type=\"text\" name=\"name\">");
                  strcpy(command,"AT+CIPSEND=0,40\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  strcpy(html,"<input type=\"submit\" value=\"Submit\"></form>");
                  strcpy(command,"AT+CIPSEND=0,43\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  strcpy(html,"");
                  strcpy(command,"AT+CIPSEND=0,14\r\n");
                  espSerial.print(command);
                  getReply( 2000 );
                  espSerial.print(html);
                  getReply( 2000 );

                  espSerial.print( "AT+CIPCLOSE=0\r\n" );
                  getReply( 1500 );

                  Serial.println("last getReply 1 ");
                  getReply( 2500 );

                  Serial.println("last getReply 2 ");
                  getReply( 2500 );

              }
          }

          delay (100);

    }

    void getReply(int wait)
    {
        int tempPos = 0;
        long int time = millis();
        while( (time + wait) > millis())
        {
            while(espSerial.available())
            {
                char c = espSerial.read();
                if (tempPos < 500) { reply[tempPos] = c; tempPos++;   }
            }
            reply[tempPos] = 0;
        }

        if (printReply) { Serial.println( reply );  Serial.println(line);     }
    }

body:
If you have your text in a character array, which it seems you have, then it is simple enough to iterate through that array changing whatever characters you want.

For instance, if the text is in `reply` then:

    for (char *p = reply; *p; p++) {
        if (*p == '+') *p = ' ';
    }

That is, starting at the beginning of reply, by creating a pointer `p` and pointing it at the start of reply, check to see if there is anything except the `NULL` character, run the code inside the brackets, and move to the next character (p++).

The code inside the brackets looks to see if the current character is a + and if so then set the current character to be a space.

Another way is to use an integer counter:

    for (int i = 0; reply[i] != 0; i++) {
        if (reply[i] == '+') reply[i] = ' ';
    }


body:
Two things:
+If you are using strings, try using the String built in object, it is very handy and useful
+when using String, you can use replace function