message:
Cheap LCD with Few Pins

I am working on a project with an Arduino Nano that includes a keypad, screen, and the NRF4001 transceiver. The keypad requires 7 digital pins to operate, the wireless transceiver uses pins D9 - D13 with the RF24 library I am using. Now, that leaves me with 1 Digital Pin left for a screen unless there is an I2C screen I could use.

That would be easy enough to find except that I have some limitations. If at all possible I would like the screen to be under 5 dollars and about the size of a Nokia 5110. The Nokia uses to many pins and does not tolerate 5v logic levels I've heard. An OLED 0.96 inch is only a 4 bucks and is I2C, but it is too small. I could make a board for the keypad that used different values of resistors and one analog pin to detect different buttons but would rather not go that route if there is any easier way to get around this.

Are there any options out there that would suffice my pin, cost and size conditions or am I being too picky?

body:
You can use a single analog pin to read an entire keypad.

First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.

A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.

Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F->G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.

You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: http://www.calculator.net/resistor-calculator.html and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.

DO NOT use any resistors under 1kOhm.

Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out ` * (5.0 / 1023.0)` , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.

Then find the numbers exactly in between.

For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.


sender: user

message:
How to do a software reset on MAX7456?

I messed around with the [MAX7456][1] chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.

The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like [this][2])

  [1]: https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf
  [2]: http://www.ebay.co.uk/itm/On-Screen-Ardupilot-Mega-Display-MinimOSD-Rev-1-1-OSD-diy-drones-APM2-2-5-2-6-/321843140980

sender: assistant

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

The datasheet says:

> The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...

Thus, you need to write address / data after selecting the chip.

    digitalWrite (SS, LOW);  // select the chip
    SPI.transfer (0x00);     // select address 0x00 (Video Mode 0)
    SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
    digitalWrite (SS, HIGH); // done

According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.

      byte result;

      do
        {
        digitalWrite (SS, LOW);      // select the chip
        SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
        result = SPI.transfer (0);   // read it
        digitalWrite (SS, HIGH);     // done
        } while (result & bit (1));  // loop while not reset yet

---

> Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?

I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.

      // reset chip
      digitalWrite (SS, LOW);  // select the chip
      SPI.transfer (0x00);     // select address 0x00 (Video Mode 0) - write mode
      SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
      digitalWrite (SS, HIGH); // done

      byte result;
      unsigned int counter = 0;

      // wait for it to become ready, or time-out
      do
        {
        digitalWrite (SS, LOW);      // select the chip
        SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
        result = SPI.transfer (0);   // read it
        digitalWrite (SS, HIGH);     // done
        if ((result & bit (1)) == 0)
          counter++;     // count times not ready
        } while ((result & bit (1)) && (counter < 1000) );  // loop while not reset yet

      if (counter == 0 || counter >= 1000)
        {
        // chip does not seem to be responding
        }
      else
        {
        // all OK!
        }


message:
Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display

I just got my Arduino Pro Mini and GDEW0154T1 ePaper display ([GDEW0154T1 display)][1] and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.

I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?

Thank you for any advice!

  [1]: http://www.good-display.com/products_detail/&productId=305.html

body:
You need to build a special driver board.  Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.

The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).

There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.

Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task.  You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it *is* the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.


message:
Hall Effect Current Sensor Wiring

I need help with wiring this current sensor so that I can read the output voltage as an analogue input. - http://www.tamuracorp.com/clientuploads/pdfs/engineeringdocs/L03SXXXD15.pdf

This is how I have it wired right now -
1 - +15v
2 - 15v ground
3 - output to arduino
4 - arduino ground

This seemed simple but reviewing the wiring diagram again I have a hunch that this is not at all how I should be wiring this up.

Thanks

body:
Looking at the datasheet the output is +/- 4 volts, so this is not suitable to connect directly to the Arduino, because the input pin will not tolerate -4 V.

I am no Hall Effect sensor expert, but a quick search on Google showed another potential problem: If you are planning to measure AC current, and you try to sample the output on the Arduino, the reading will average out to zero (half of the time positive, half of the time negative).

What may help - and this is a bit of a guess - is to put a diode in series with the sensor output, oriented so that you only get the positive pulses. That is, the anode connected to the Hall Effect sensor, and the cathode (with the black line) on the Arduino side.

Then you probably want to smooth the voltage so you can read the average voltage with the ADC converter, rather than what it is at a particular millisecond. A low-pass filter will take an average, which you can then read with `analogRead`.

Something like this:

[![Hall effect sensor wiring][1]][1]

---

I made up that circuit driven by a signal generator (8 V peak to peak, i.e. +/- 4 V) and found a 400 mV drop over the diode using a 1N4148 normal diode, and a 160 mV drop using a BAT85 Schottky diode.

With a 3 V peak-to-peak signal the voltage drop with the Schottky diode reduced to 120 mV, so it wasn't totally linear.

---

As Majenko pointed out, there is a voltage drop over the diode. You can make a [Precision Rectifier](https://en.wikipedia.org/wiki/Precision_rectifier) out of an op-amp and a few other parts, like this:

[![Precision Rectifier][2]][2]

This avoids the problem of the voltage drop (put this in place of the diode in the earlier circuit).

If the signal is AC then the smoothing circuit I described above will only give you an average voltage, not a peak one. You may want to sample rapidly in order to find the peak values.

  [1]: https://i.stack.imgur.com/3P4pr.png
  [2]: https://i.stack.imgur.com/dn3JC.png


body:
To read the sensor properly you have to convert the output signal into something the Arduino can work with.

At full current the output will swing between +4V and -4V, and over-current will cause that to be nearer +6V to -6V.  The frequency of that swing will be the frequency of the input voltage - so typically 50 or 60Hz.

The Arduino can only read between 0V and 5V, so you will need to convert the provided voltage to fit.

You need to first reduce the voltage by about a half, so it fits into +/- 2V, and then you need to add a 2.5V offset voltage to it so that it swings between 0.5V and 4.5V.

Once you have done that you then need to sample the incoming signal fast enough that you can get the peak values, from which you can then calculate the incoming current.

Often for this kind of thing you would use a simple voltage divider with an offset voltage applied to it, but the output impedance of the sensor (set by RL) is 10KΩ which is around the upper limit for the input impedance of the Arduino's input.  A voltage divider that wouldn't adversely affect the output accuracy would be using resistors in the order of 1MΩ, which would be way too high for the ADC on the Arduino to be able to sample accurately.

So you need to buffer the signal with a high impedance buffer.  That can be achieved most simply with an inverting op-amp circuit with a gain of 0.5.  You want a rail-to-rail op-amp which is capable of running from a single supply voltage.

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

In this circuit the output current is converted into a voltage by the 10KΩ resistor RL.  It is then *AC coupled* to the rest of the circuit through C1 which has to be high enough in value as to not reject the frequency you are working with (it acts like a high-pass filter).  R1 and R2 set the gain of 50/100, or 1/2, so the voltage is halved.  R3 and R4 form a voltage divider to provide a VCC/2 offset voltage into the non-inverting input of the op-amp.  This is known as the *virtual ground* voltage and is the voltage the output of the op-amp will swing around.

The result is the input voltage inverted, halved and off-set by 2.5V, which can be read directly by the Arduino's ADC.

Note the magic word *inverted* there, though.  The values you read will be upside down.  Anything read above 512 from the ADC will equate to a negative voltage.  Anything read below 512 will be a positive voltage.  So it is necessary to first "invert" the reading, which can simply be done by subtracting it from 1023.

Then it's just a matter of sampling often enough and recording the peak (and negative peak) values over a short period.  The faster you can sample the better your results will be.

From those peak values you can then do all sorts of calculations and things.  You can use them "as is" to directly give you the "peak-to-peak" current, or calculate the RMS voltage to then give you the RMS current.

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


message:
Arduino code of making a LED digit display not functioning properly

I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code

    int a = 2;
    int b = 3;
    int c = 4;
    int d = 5;
    int e = 6;
    int f = 7;
    int g = 8;

    void setup()
    {
       for(int i = 2; i++ ; i<9)
       {
          pinMode (i, OUTPUT);
       }
    }
    void _1()
    {
       digitalWrite ( b, HIGH);
       digitalWrite ( f, HIGH);
       delay(1000);
    }
    void _2()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _3()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _4()
    {
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( b, HIGH);
       delay(1000);
    }
    void _5()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _6()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       digitalWrite ( d, HIGH);
       delay(1000);
    }
    void _7()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( f, HIGH);
       delay(1000);
    }
    void _8()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _9()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       delay(1000);
    }
    void _0()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void wait()
    {
       digitalWrite ( a, LOW);
       digitalWrite ( b, LOW);
       digitalWrite ( c, LOW);
       digitalWrite ( d, LOW);
       digitalWrite ( e, LOW);
       digitalWrite ( f, LOW);
       digitalWrite ( g, LOW);
       delay(100);
    }
    void loop()
    {
       _0();
       wait();
       _1();
       wait();
       _2();
       wait();
       _3();
       wait();
       _4();
       wait();
       _5();
       wait();
       _6();
       wait();
       _7();
       wait();
       _8();
       wait();
       _9();
       wait();
    }

The problem is that it stays at _0 and then never changes. Any suggestions?

body:
The `for` loop in your `setup()` function isn't quite right. The condition (`i<9`) and the iterator (`i++`) need to be the other way round, like this:

    for (int i = 2; i<9; i++)
    {
      pinMode (i, OUTPUT);
    }


message:
How can I detect a disconnected pin?

I'm trying to build a system where if a cable gets disconnected from a pin (any pin), an action is executed.

I am wondering how to set this up. Can I simply wire the 5V to a pin and read its status or will this mess up the Arduino? Should I use any resistors? How should I connect this to the GND?

Please bear in mind that I'm pretty new to all of this.

body:
You can connect all pins through a 1M resistor to a rail. Once in a while you set all your outputs to inputs and toggle the rail HIGH and LOW, if the inputs are HIGH and LOW in the sequence you toggled the rail, there is no wire. The same question was asked at Arduino Forums so read [this][1] thread.

This question's answer was provided by johnwasser@forum.arduino.cc.

  [1]: http://forum.arduino.cc/index.php?topic=183977.0


body:
The way to do this, since there is no digital value in between HIGH and LOW, is to actively create a signal on the pin you can recognise.  Note that if the signal coming in to the pin is a datastream (a sequence of HIGH and LOW) that runs all the time this may not work reliably, but it's good for things like buttons and other simple sensors.

Any signal on a wire has a *drive strength*.  This is basically how powerful the signal is and how good it is at overriding other things happening on the same wire.  It is closely related to the output impedance of the source (what is sending the signal).  For things like buttons and switches that is basically the value of the pullup resistor used.

To actively sense if a pin is disconnected or not you need to temporarily connect it to a known signal level *at the same time* as it's connected to the wire (or not connected if it happens to be not connected).  This known signal level has to be of a *weaker* drive than the source signal by several orders of magnitude.  This ensures that if you try superimposing your test signal over the incoming signal the incoming signal swamps out the test signal and you don't see it at all.  For instance, if your source has 10KΩ impedance (say a button with 10KΩ pullup resistor) then a test signal with source impedance of 1MΩ would be suitable.

Each pin to be tested can be connected to its own 1MΩ (in this example) resistor, and those resistors are all connected to the same extra IO pin:

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

In this example pin D2 is the test pin, and pins D4-D7 are your inputs.

So under normal circumstances pin D2 is set as an input and completely ignored.  When you come to test the pins, though, you set it as an output.

You then set D2 to be HIGH and read each of D4 through D7.  Any that read as HIGH are candidates for being not connected.

You then set D2 to be LOW and read the pins that read HIGH before.  Any that now read as LOW are disconnected.

You then set D2 back to being an input again so it doesn't interfere with normal operations.

----

If you just want to know if current is flowing in a wire you can use what is called a *shunt resistor*.  This is a small resistor (maybe 1Ω) that is placed in-line with the wire and you measure the voltage (using Arduino analog inputs) at both sides of the resistor.  The voltage dropped across the resistor is directly proportional to the current flowing through it thanks to Ohm's Law:

> I=V/R

For instance:

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

If the voltage read by A1 should be 5V (the voltage the wire is connected to) and the voltage read by A0 should be 4.93V, the voltage *dropped* by the resistor would be 5-4.93 = 0.07v.  With the 1Ω resistor the current would be 0.07/1 = 0.07A, or 70mA.

With the wire at OUT disconnected there will be zero current flowing since there is no circuit.  So re-arranging the formula above we can prove that we can tell it's disconnected.

If I=V/R then V = RI.  Therefore V = 1Ω × 0A = 0V.  So the voltage dropped across the resistor would be 0V, so A0 and A1 would be equal (discounting any noise). A0 and A1 would both read 5V.  Similarly, if the wire IN was disconnected instead then A0 and A1 would both read 0V.

For sensing higher currents you use a smaller resistance, and for sensing smaller currents you use a larger resistance - this allows for a voltage drop to be generated that is within a suitable range for the sensitivity of the ADC doing the reading.  For the Arduino that's a 10-bit ADC, so it can sense (with a 5V VREF) 5/1024=4.882813mV per LSB.

Note that if you are working with voltages above that at which the Arduino operates you will need to separate or otherwise scale those voltages.  There are special devices designed especially for this task called *high side current shunt amplifiers*.  They also allow you to use a smaller resistance than you would otherwise need which is less intrusive to your circuit (less voltage drop).

  [1]: https://i.stack.imgur.com/soUQi.png
  [2]: https://i.stack.imgur.com/MKALi.png


body:
Alternatively, if this is a digital input, you can just use a pull-up or pull-down resistor to give the input pin a default value. Let's say you use a pull-up resistor to make the default high. Then you connect a low cable to this input so that the input reads low. Now, if the cable goes high or if it is disconnected, you get a high value in the input pin.

I know this was not quite what you were asking but maybe such a solution could help with your original problem. In my case, I have a flame detection module that gives low output by default and turns high when there is a flame. I don't want to miss the flame because of my cable disconnecting, so I use a pull-up resistor that will make the input high not only when there is a flame, but also when there is a disconnection. This way I make sure that I don't miss a fire because of the sensor cable disconnecting.


message:
Replacing Atmega8a pu 1440 arduino Ic with 1337

I have one Arduino uno, and one atmega8a 1337 ic. Can i replace the Arduino uno ic with 1337 to program the 1337 one?

body: If you have a bootloader installed on the 8A then yes, you can.  The two chips are pin and electrically compatible.


message:
Help Connecting MicroSD Module with Arduino Uno

I am Trying to make a MicroSD .wav file player using Arduino Uno. I have ordered a MicroSD Card Module from ebay today.

Product Link : http://www.ebay.in/itm/Micro-SD-Card-Module-SD-Storage-Board-TF-Card-Memory-Shield-SPI-For-Arduino-/161696480012?

As You can See in the Product Image, there is **not mentioned on the PCB that which Pin Is ground** or VCC Or any other SPI pin.
1. How will I identify the correct pins of the MicroSD Module ?
2. How can I connect a speaker to arduino to play .wav files. Is Amplifier neccessary? I am weak when it comes to electronics.

I have listened that when I connect a Capacitor in series with speaker, it will boost the output volume. There will not be music but only voice recordings in .wav files. I want to listen it clearly only.

body:
OMG, what a vile listing!

Anyway, I think you'll probably find they are in the order listed in the description when the connector is facing south. It's probably printed on the rear of the board which they don't show.

That is, from left to right, GND, VCC, MISO, MOSI, SCK, CS.

As for connecting a speaker, that depends if you want low quality (PWM) audio, or high quality (DAC) audio.  The latter requires the addition of an audio shield, most of which have an SD card slot on them already thus alleviating the need for this SD card breakout board.

For the former there is a library and instructions here: http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio


body: I got my MicroSD Module today. The labels were printed At the bottom side. Dont confuse, CLK = SCK. The VCC goes to arduino 5v.


message:
How would i capture and split serial data?

How would i capture the following serial data, and split it into parts?
`<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>`

the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z

What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD.

i.e.
X: 0.000  Y:0.000
Z: 0.000  Idle

I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.

body:
This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.

Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function `strtok()` to split the string up into parts.

So you have the string:

    char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

The function `strtok()` takes, on its first call, the string you want to split and the delimiter that you want to split on.  It returns a pointer to the chunk:

    char *alarm = strtok(string, ",");

`alarm` now contains `<Alarm` and `strtok()` moves its internal pointer to point at the next character, so it sees the string as `MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>`

With the next and subsequent calls to `strtok()` you don't give it the string, or it will reset its internal pointer.  You just pass it `NULL` and it gives you the next block:

    char *mposX = strtok(NULL, ",");
    char *mposY = strtok(NULL, ",");
    char *mposZ = strtok(NULL, ",");
    char *wposX = strtok(NULL, ",");
    char *wposY = strtok(NULL, ",");
    char *wposZ = strtok(NULL, ">");

Note that I changed the delimiter on the last one to `>` so it chops off that extra character that we don't want (and there is no `,` after the last part).

So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:

    *alarm = "<Alarm";
    *mposX = "MPos:0.000";
    *mposY = "0.000";
    *mposZ = "0.000";
    *wposX = "WPos:0.000";
    *wposY = "0.000";
    *wposZ = "0.000";

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:

    alarm += 1;
    mposX += 5;
    wposX += 5;

Our list of pointers now looks like this:

    *alarm = "Alarm";
    *mposX = "0.000";
    *mposY = "0.000";
    *mposZ = "0.000";
    *wposX = "0.000";
    *wposY = "0.000";
    *wposZ = "0.000";

The position variables can now be passed through strtod() to convert them to float values:

    float mx = strtod(mposX, NULL);
    float my = strtod(mposY, NULL);
    float mz = strtod(mposZ, NULL);
    float wx = strtod(wposX, NULL);
    float wy = strtod(wposY, NULL);
    float wz = strtod(wposZ, NULL);

You can do different things depending on the content of the `*alarm` string by using `strcmp()`:

    if (strcmp(alarm, "Busy") == 0) {
        // Something to do when Busy
    }

etc.

Or you can just use it to print the content to the LCD.


message:
Remote Wireless Tripwire

I've had an idea for an Arduino project, but I'm not sure where to start. My idea is this: have an Arduino Nano connected to an HC-SR04 ultrasonic sensor, as well as an nRF24L01+ radio. This will be the tripwire module, which will send an alert to a second Arduino (connected to another nRF24L01+ of course) whenever something passes by.

This wouldn't be a stationary unit, it would need to be able to be placed and sense in a variety of locations so the distance would need to be set on power up.

Another issue I'm running into is getting the nRF24L01+ units to work for this purpose. I want to know that the units are wirelessly connected, so having a packet sent every second or so lets the receiving unit know that they're connected, and an additional packet for the tripwire trigger sets off an indicator led.

Is this even possible?

body:
This sounds very doable. The first point, tuning the distance threshold at startup, could be done with a bank of DIP switches or a potentiometer on an analog pin to set the value. You might include some startup code continuously pings the transducer and displays the result on an LED, until you press a button to tell it "use this".

The second, is a very typical communication technique - sending "hello" packets periodically to confirm that communication is up. In your case, the same packet could carry a hit/no-hit bit within it.


message:
Cannot upload sketch to Atmega328p TQFP soldered on PCB

After creating a working prototype with DIP ATMega328 chip/ Arduino UNO I recently got PCBs assembled with SMD components and ATMega328P TQFP soldered onto them, but now I'm having a hard time trying to upload the Arduino program.

**This is the schematic of the PCB with ATMega328P TQFP with ISP headers for programming:**
[![enter image description here][1]][1]

I'm using USBasp programmer with upgraded firmware to upload the code. The chip gets detected and also I can upload sketches to it but the problem is the code runs slow, which I found out is due to the default 8MHz internal clock.(the blink program makes LED blink every 16 seconds instead of 1 second,i.e. with delay(1000))

 Now to switch to the external 16MHz clock which I want to use I found out [here][2] that I have to change the fuse values from the default

> **lfuse: 0x62   hfuse: 0xD9   efuse: 0x3F**

to

> **lfuse: 0xFF   hfuse: 0xDE   efuse: 0x05**

I tried it two times and both the times it screwed up the ATMega328P chip

    C:\Users\p>avrdude -p m328p -c usbasp -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efu
    se:w:0x05:m

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.03s

    avrdude: Device signature = 0x1e950f
    avrdude: reading input file "0xFF"
    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xFF:
    avrdude: load data lfuse data from input file 0xFF:
    avrdude: input file 0xFF contains 1 bytes
    avrdude: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of lfuse verified
    avrdude: reading input file "0xDE"
    avrdude: writing hfuse (1 bytes):

    Writing | ################################################## | 100% 0.03s

    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xDE:
    avrdude: load data hfuse data from input file 0xDE:
    avrdude: input file 0xDE contains 1 bytes
    avrdude: reading on-chip hfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of hfuse verified
    avrdude: reading input file "0x05"
    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.03s

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0x05:
    avrdude: load data efuse data from input file 0x05:
    avrdude: input file 0x05 contains 1 bytes
    avrdude: reading on-chip efuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of efuse verified

    avrdude: safemode: Fuses OK

    avrdude done.  Thank you.

    C:\Users\p>avrdude -p m328p -c usbasp

    avrdude: error: programm enable: target doesn't answer. 1
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

Both of the PCBs are not responding to the USBasp programmer and now I have only got one PCB left. I desperately want to get the final one working.

This is my first time using the SMD ATMega328P chips and any help would be appreciated.

  [1]: https://i.stack.imgur.com/agw3N.png
  [2]: http://forum.arduino.cc/index.php?topic=71580.0

body:
It looks like the capacitors on your crystal are considerably bigger than they should be.

You are switching the clock to the external crystal, and because you have such massive capacitors on it it's failing to oscillate.  Without that oscillation the chip can't run, and so it can't respond to the programming.

The crystal capacitors should be roughly 2x the "load capacitance" of the crystal you are using.

> CX1 = CX2 = 2(CL - CSTRAY)


message:
Handling serial streams biggers than the available ram

I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.

I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds.

Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?

body:
You can parse indefinitely large amounts of data with a state machine parser.

General description: [State machines](http://www.gammon.com.au/statemachine)

As an example, I wrote recently an [HTTP server](http://www.gammon.com.au/forum/?id=12942) which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.

You need enough RAM for **one** item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

---

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.


message:
Including libraries from header files sometimes doesn't work

I, once again have difficulties including libraries from code files other than my .ino file.

I have several .cpp and .h files in my project to keep it sorted and clean.
However one of my header files starting like this:

    #ifndef DPLANDEF
    #define DPLANDEF
    #include <Arduino.h>
    #include <EEPROM.h>
    #include "syssettings.h"

yields the following errors:

> In file included from
> /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.cpp:2:0:
> /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.h:5:20:
> fatal error: EEPROM.h: No such file or directory  #include <EEPROM.h>
>                     ^ compilation terminated. Fehler beim Kompilieren.

EEPROM.h should be known to the IDE, because I can find it in the libraries menu, too. If it was a custom library, I might have botched something during installation, but this is a standard library. It should work out of the box. What's the problem here?

body:
The problem here is that it's a header file.  The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.

In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.


message:
run two motors in turns without using delay()

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

I googled solutions and tried, but I still cannot get it working.

I've tried BlinkwithoutDelay.

I feel it is very confusing to track timing of two motors (i.e., step, direction, speed) for the following routine loop:

* step 1: run motorA_forward() for 10 seconds;
* step 2: run motorAB_stop() for 1 seconds;
* step 3: run motorB_backward() for 3 seconds
* step 4: run motorAB_stop() for 1 seconds
* step 5: run motorA_backward() for 10 seconds
* step 6: run motorAB_stop() for 1 seconds

Please help me on this!! I really appreciate your time and comments.

Thank you.

The following is my working code.

    // ----------LIBRARIES--------------

    #include <Wire.h>
    #include <LIDARLite.h>
    LIDARLite myLidarLite;

    // ----------CONSTANTS--------------

    const int motorA_pin_1 = 8;           // the pin numbers for the motors
    const int motorA_pin_2 = 11;
    const int motorA_pin_speed = 9;
    const int motorB_pin_1 = 12;
    const int motorB_pin_2 = 13;
    const int motorB_pin_speed = 10;

    //------------VARIABLES--------------

    byte motorA_state_1 = LOW;             // used to record whether the motots are on or off
    byte motorA_state_2 = LOW;             // LOW = off
    byte motorB_state_1 = LOW;
    byte motorB_state_2 = LOW;

    int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
    int motorA_Forward_Interval     = 5000;  // will store last time the motor was moved
    int motorA_Backward_Interval    = 5000; // will store last time the motor was moved
    int motorA_Stop_Interval        = 2000;  // will store last time the motor was moved
    int motorB_Stop_Interval        = 2000;  // will store last time the motor was moved
    int motorAB_BreakTime_Interval  = 2000;

    unsigned long motorA_Forward_Timer      = 0;     // will store last time motorA start was updated
    unsigned long motorA_Backward_Timer     = 0;     // will store last time motorA start was updated
    unsigned long motorB_Forward_Timer      = 0;     // will store last time motorA start was updated
    unsigned long motorB_Backward_Timer     = 0;     // will store last time motorA start was updated
    unsigned long BreakTime_timer   = 0;     // will store last time motorA/B break time was updated

    //------------INITIALIZATION--------------

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

      pinMode(motorA_pin_1,OUTPUT);         // set the motor pins as output:
      pinMode(motorA_pin_2,OUTPUT);
      pinMode(motorA_pin_speed,OUTPUT);
      pinMode(motorB_pin_1,OUTPUT);
      pinMode(motorB_pin_2,OUTPUT);
      pinMode(motorB_pin_speed,OUTPUT);

    }

    //------------LOOPING----------------------
    // Notice that none of the action happens in loop() apart from reading millis()
    // It just calls the functions that have the action code

    void loop()
    {
        Serial.println(myLidarLite.distance());

        unsigned long currentMillis = millis();

        motorA_forward();  // for 10 seconds
        motorAB_stop();    // for 1 seconds
        motorB_backward(); // for 3 seconds
        motorAB_stop();    // for 1 seconds
        motorA_backward(); // for 10 seconds
        motorAB_stop();    // for 1 seconds

    }

    //------------SUBROUTINE----------------------

    void motorA_forward()
    {
      if(currentMillis - motorA_Forward_Timer <= motorA_Forward_Interval)
      {
        motorA_state_1 = HIGH;   // Turn motor A on - backward
        motorA_state_2 = LOW;  //
        motorB_state_1 = LOW;   // Turn motor B off
        motorB_state_2 = LOW;   //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorA_Forward_Timer = currentMillis;
      }
    }

    void motorA_backward()
    {
        if(currentMillis - motorA_Backward_Timer <= motorA_Backward_Interval)
      {
        motorA_state_1 = LOW;   // Turn motor A on - backward
        motorA_state_2 = HIGH;  //
        motorB_state_1 = LOW;   // Turn motor B off
        motorB_state_2 = LOW;   //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorA_Backward_Timer += currentMillis;
      }
    }

    void motorB_forward()
    {
        motorA_state_1 = LOW;   // Turn motor A off
        motorA_state_2 = LOW;   //
        motorB_state_1 = HIGH;  // Turn motor B on - forward
        motorB_state_2 = LOW;   //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorB_Forward_Timer = currentMillis;
    }

    void motorB_backward()
    {
        motorA_state_1 = LOW;   // Turn motor A off
        motorA_state_2 = LOW;   //
        motorB_state_1 = LOW;   // Turn motor B on - backward
        motorB_state_2 = HIGH;  //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorB_Backward_Timer = currentMillis;
    }

    void motorAB_stop()
    {
        motorA_state_1 = LOW;   // Turn motor A off
        motorA_state_2 = LOW;   //
        motorB_state_1 = LOW;   // Turn motor B off
        motorB_state_2 = LOW;  //

        analogWrite(motorA_pin_speed,0);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,0);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        BreakTime_timer = currentMillis;
    }

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

    int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
    ...

    void loop()
    {
        Serial.println(myLidarLite.distance());
        unsigned long currentMillis = millis();

You have **two** `currentMillis` variables. The global one never changes. You change a **different** one inside `loop`.

---

Remove the data definition. eg.

    void loop()
    {
        Serial.println(myLidarLite.distance());
        currentMillis = millis();  // change the global variable

---

Also make the **global** one unsigned long:

    unsigned long currentMillis               = 0;     // stores the value of millis() in each iteration of loop()


body:
This is a classic example where Object Oriented Programming (OOP) can make your life so much easier.

The principle behind OOP is to define a *Class* which contains all the actions you want to perform on something - in this case a motor.  The *Class* contains all the instructions on how to do things like set the motor speed, the direction, start it, stop it, etc.

From that *Class* you then create *Objects*.  The beauty is there is only one *Class* which has the abstract concept of "Motor Control", but that *Class* is used to create one *Object* for each motor you want to control.

A *Class*, and hence the *Objects* derived from it, are all completely self contained, which makes it so much easier to manage.  All the variables associated with a single motor are wrapped up inside the *Class* and you don't need to worry about unique names for them all on a per-motor basis.

For example, you might define a class like this:

    class Motor {
        private:
            int _speedPin;
            int _directionPin1;
            int _directionPin2;

        public:
            Motor(int sp, int dp1, int dp2) {
                _speedPin = sp;
                _directionPin1 = dp1;
                _directionPin2 = dp2;
            }
            void begin() {
                analogWrite(_speedPin, 0);
                pinMode(_directionPin1, OUTPUT);
                pinMode(_directionPin2, OUTPUT);
                digitalWrite(_directionPin1, LOW);
                digitalWrite(_directionPin2, LOW);
            }
            void forward() {
                digitalWrite(_directionPin1, HIGH);
                digitalWrite(_directionPin2, LOW);
            }
            void reverse() {
                digitalWrite(_directionPin1, LOW);
                digitalWrite(_directionPin2, HIGH);
            }
            void speed(int speed) {
                analogWrite(_speedPin, speed);
            }
            void stop() {
                analogWrite(_speedPin, 0);
                digitalWrite(_directionPin1, LOW);
                digitalWrite(_directionPin2, LOW);
            }
    };

Everything you need to control a motor is in there.  Then you could use that to create two motor objects:

    Motor leftMotor(3, 4, 5);
    Motor rightMotor(6, 7, 8);

You provide the pins that control the motor to the *constructor* of the object - that is pin 3 is the speed pin of the first motor, and pins 4 and 5 are the direction control pins, etc.

You can now control the motors very simply.  Configure the pins by calling the begin function defined in the class above:

    void setup() {
        leftMotor.begin();
        rightMotor.begin();
    }

And now you can use similar decision making as normal to decide when to do what.  The main difference is that your motor control code now looks as simple as:

    leftMotor.forward();
    rightMotor.reverse();

or

    leftMotor.stop();
    rightMotor.forward();
    rightMotor.speed(30);

You then end up with a program that is much cleaner and easier to follow.  And adding a third or forth motor is as simple as defining more Motor objects with their pins.

This video is a good introduction to what OOP is and how it differs from the "traditional" approach:

* https://www.youtube.com/watch?v=MTfWr7o7Q4U


message:
How do I use 3 Hc-sr04 ultrasonic sensors to control 3 vibration dc motor?

This code we are using only one motor and one hc-sr04 ultrasonic sensor, the code is shown below:

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

    #define trigPin 7
    #define echoPin 6
    #define motorPin 5

    void setup()
    {
      Serial.begin(9600);// to use the serial monitor
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(motorPin, OUTPUT);
    }

    void loop()
    {
      int duration,distance;
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2)/29.1;
      Serial.print(distance);//to print the distance on the serial monitor
      Serial.println("cm");

      // to make the motor vibrate depending on the distance
      // if the ultrasonic sensor is too far from the obstacle it will vibrate slowly
      // if the ultrasonic sensor is very close to the obstacle it will vibrate very fast

        if(distance <= 60 && distance >= 45)
        {
          // to make the motor vibrate
        digitalWrite(motorPin, HIGH); // making the motor on

        delay(200);
        digitalWrite(motorPin, LOW);// making the motor off
        delay(200);
        }

        else if(distance < 45 && distance >= 30)
        {
        digitalWrite(motorPin, HIGH);
        delay(100);
        digitalWrite(motorPin, LOW);
        delay(100);
       }
        else if(distance < 30){

        digitalWrite(motorPin, HIGH);
        delay(50);
        digitalWrite(motorPin, LOW);
        delay(50);
      }
      else
      {
        digitalWrite(motorPin, LOW);
      }
    }

We want you to tell us your comment about the code.

And we want to add two more motors and two ultrasonic sensors, one of them in the left and the other in the right.

We want you to help us in the code, because we don't know how we can change it for two other motors.

body:
There's a few things you need to consider when making multiple things happen at the same time.

Firstly is timing. You can't make two things happen concurrently with different timings if you have `delay()` in there, since nothing else can happen while `delay()` is executing.  So you have to get rid of all `delay()` calls and replace them with examining the difference between successive calls to `millis()`.

For instance, imagine you're in the kitchen and you want to boil and egg and make a cup of tea at the same time.  You fill the kettle and turn it on.  You put a pan of water on the stove with an egg in it to boil.

Now you could sit and stare at the egg until it's boiled enough for you to eat, but what happens to the kettle while you're doing that?  It's boiled, turned itself off, and started to go cold.

So instead you put the egg in the pan and look at the clock.  Then you think "in 5 minutes I will take the egg out of the boiling water".  You might set an alarm for 5 minutes time if you have one, or you may keep glancing at the clock periodically to see if the 5 minutes have past yet.  Meanwhile the kettle has boiled and you've made your cup of tea.

Then the 5 minutes have passed.  You know that because *you remembered what time you put the egg on to boil* and *you know what the time is now*, so you can subtract one from the other to find that 5 minutes have passed.

Now let's make it a little more complex.  Imagine you want two eggs - one soft boiled and one hard boiled.  The hard boiled one may want 8 minutes, the soft boiled one 5 minutes.

So you put one egg on to boil and remember the time.  Roughly three minutes later you put the other egg in and also remember that time.

Once enough time has passed that the first egg has been in 8 minutes you take it out.

Once enough time has passed that the second egg has been in 5 minutes you take it out.

You have had to remember two start times which you then compare separately to decide what to do with each egg when.

To translate that to your program - you have to remember a start time for each action for your motors, along with the state of the motors - and when the right time has elapsed you change the state of the motor (motor on -> motor off - egg in pan -> egg on plate) and remember the time at which you changed the state so you can know when to change the state again.

That's exactly what the BlinkWithoutDelay example does to make an LED change state (on -> off -> on) at certain times by remembering *when* it last changed state so you know *when* to change the state next.


message:
Varying motor speed with the L293D

Im using a potentiometer to control the speed of two generic 6-8V DC motors. The potentiometer input is scaled from 0-1023 to 0-255, I then use the analogWrite() function to write this value to the enable pins on my L293D motor controller.

Im sure this should control the speed but it doesn't, I have the code printing the value it sends to the enable pins and this is correct, but no speed increase, the motors either move at one speed or don't move at all. My enable pins are 12 and 13 on my Arduino Uno, previously 5 and 6 but I moved them to see if that was the problem.

Is there a problem with the PWM frequency maybe? I don't understand why it won't go faster and slower after days of troubleshooting.. The inputs are all set correctly, allowing both motors to move in the forward direction..

    int Speed = analogRead(speedChange);
    int SpeedMap = map(Speed,0,1023,0,255);
    analogWrite(enable1, SpeedMap);
    analogWrite(enable2, SpeedMap);

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

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

Its a long shot but does anyone know enough about PWM control on DC motors to think of any things I may be missing while trying to do this? Ill provide any info ASAP, thanks

body:
Although I am still figuring things out, but i hope the following things help:

http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf

The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.

Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).


body: I guess you're not using the designated PWM pins provided on the Arduino Board, anyhow I suggest you read this instructible: http://www.instructables.com/id/Arduino-DC-motor-speed-and-direction-L293D/step2/L293D-Pin-Layout/ ,Perhaps this can help you in making proper connections and also help you with the code :)


message:
How can i read serial data into a string until a certain character is recieved?

This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.

What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data.

The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.

What I'm hoping to do, is read the data from serial and if the character '<' is received, place it, and everything after it into the buffer until the character ">" is received.  After the last character is received, and placed into the buffer, continue on with the script.

Unless of coarse someone has a better idea on how to approach this.
i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.

The string i'm expecting as a response would be similar to this:

    <Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

Here is the code i have so far:

    float mx;
    float my;
    float mz;
    float wx;
    float wy;
    float wz;
    String dAlarm;
    char buffer;
    void gPos() {
      Serial1.print("?\n");
      buffer = Serial1.read();
      char string[80];
      string[buffer];
      char *alarm = strtok(string, ",");
      char *mposX = strtok(NULL, ",");
      char *mposY = strtok(NULL, ",");
      char *mposZ = strtok(NULL, ",");
      char *wposX = strtok(NULL, ",");
      char *wposY = strtok(NULL, ",");
      char *wposZ = strtok(NULL, ">");
      alarm += 1;
      mposX += 5;
      wposX += 5;
      mx = strtod(mposX, NULL);
      my = strtod(mposY, NULL);
      mz = strtod(mposZ, NULL);
      wx = strtod(wposX, NULL);
      wy = strtod(wposY, NULL);
      wz = strtod(wposZ, NULL);

      if (strcmp(alarm, "Idle") == 0) {
        dAlarm = "Idle";
      } else if (strcmp(alarm, "Run") == 0) {
        // Something to do when Busy
        dAlarm = "Run";
      } else if (strcmp(alarm, "Hold") == 0) {
        // Something to do when Busy
        dAlarm = "Hold";
      } else if (strcmp(alarm, "Door") == 0) {
        // Something to do when Busy
        dAlarm = "Door";
      } else if (strcmp(alarm, "Home") == 0) {
        // Something to do when Busy
        dAlarm = "Home";
      } else if (strcmp(alarm, "Alarm") == 0) {
        // Something to do when Busy
        dAlarm = "ALARM!";
      } else if (strcmp(alarm, "Check") == 0) {
        // Something to do when Busy
        dAlarm = "Check";
      }
      dispPos();
    }

    void dispPos() {
      int state = 0;
      int x = analogRead (0);
      if (x < 800) {
        state = 1;
      }
      if (state == 1) {
        dPos = false;
      }

      if (dPos == true) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("X");
        lcd.print(mx);
        lcd.setCursor(8, 0);
        lcd.print("Y");
        lcd.print(my);
        lcd.setCursor(0, 1);
        lcd.print("Z");
        lcd.print(mz);
        lcd.setCursor(8, 1);
        //lcd.print(" ");
        lcd.print(dAlarm);
        delay(3000);
      } else {
        mainMenu();
      }
    }

body:
What you need to do here is implement a small *finite state machine*.

Basically you need to look at each character as it comes in and make a decision what to do with it *depending on what state you're in at the moment*.

Basically the operational decisions you need to make are:

* Is the character a < and am I currently not reading a string?
  * Yes, start reading the string.
* Is the character a > and am I currently reading a string?
  * Yes, finish reading the string and process it
* Is it any other character and I am currently reading the string?
  * Yes, add it to the buffer.

So you can see there some common questions:

* What is the character?
* What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.

    boolean readingString = false;

A simple true/false will suffice to depict if we're reading the string or not.  Start off not reading the string.

    char buffer[80] = "";

A buffer to store the text - maximum of 80 characters (*including the NULL terminating character*)

    int charPointer = 0;

Something to know where in the buffer are currently.

Now to read the characters:

First get the next character from the serial port:

    loop() {
        if (Serial.available()) {
            int incoming = Serial.read();

Now decide what to do with it.  We have a number of possible situations, some of which can be combined into single options.  For instance, if we get a "<" while reading a string it's an error condition - but do we really care?  It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in.  Let's use a `switch` for this since it's nice and tidy:

            switch (incoming) {
                case '<':
                    readingString = true; // Start reading string
                    charPointer = 0; // Set the buffer pointer to the start
                    buffer[0] = 0; // Make the string empty
                    break;

                case '>':
                    if (readingString) {
                        processBufferData(); // Do something with the buffer
                    }
                    readingString = false; // Finish reading
                    break;

                default: // Anything that's not > or <
                    // If we are reading the string and the buffer isn't full
                    if (readingString && charPointer < 78) {
                        // Add the character to the buffer and increment the pointer
                        buffer[charPointer++] = incoming;
                        buffer[charPointer] = 0; // Don't forget to terminate the string
                    }
            }
        }
    }

So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.


message:
Arduino IDE not handling library code correctly?

The author of the PinChangeInt library and the EnableInterrupt library states at [github][1]:

> When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried
> to compile it twice. I have a technique that you can use- #define
> LIBCALL_ENABLEINTERRUPT - that if you put it ahead of your #include in
> all files but the sketch, then you should be able to use the library
> without conflicts. If you know how to make it work in another way-
> remember, this is a library and will not compile in the same directory
> as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.

So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?

  [1]: https://github.com/GreyGnome/EnableInterrupt/issues/13

body:
Header files are parsed by the preprocessor and the compiler wherever they are included.

There's nothing weird about that.
One can avoid multiple inclusions by using header guards.
That's pretty standard too.

I have not looked at the library, but, for example,  a typical error is to _not_ declare variables as extern in the header and instead leave the real declaration in the header, which will lead to multiple instances, possibly clashing at link time.
Variables that are part of the library API should be declared as extern in the header and the real declaration should be done only in the .C/.CPP file.

Interrupts are an even more special case: the AVR gcc relies on very specific names to identify interrupt handlers and each of them can be present at most once.
So there are even more chances for having linker problems, if not declared correctly.


body:
To elaborate on your comment ~

An easy way to prevent multiple definitions from re-inclusion of the same header file is to ensure it's only defining things once.

e.g. my_header.h

    #ifndef __MY_HEADER_H__
    #define __MY_HEADER_H__

    // some header code.

    #endif //#ifndef __MY_HEADER_H__

When the header is *first* compiled, the definition of `__MY_HEADER_H__` gets created by the compiler due to the 2nd line of the file.  On subsequent compiles, which are caused by including the same header in more files, the 1st line '#ifndef' conditional skips everything down to the '#endif'.

When you write (or split) C / C++ code, it's common to wrap the class and function definitions (which go in the .h header file) in these compilation control blocks, and then the .c/.cpp file only gets the function bodies.

e.g.: my_rgb.h ~

    #ifndef __MY_RGB_H__
    #define __MY_RGB_H__

    #include <stdint.h>

    uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b);

    class RGB
    {
    public:
        RGB(uint8_t r, uint8_t g, uint8_t b);

        void toGreyscale();

    private:
        uint8_t red;
        uint8_t green;
        uint8_t blue;
    };

    #endif //#ifndef __MY_RGB_H__

and my_rgb.cpp

    #include "my_rgb.h"

    // Note: this would typically be a member function
    // but is separate to show a standalone function definition.
    uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b)
    {
        uint32_t packed;

        packed = (r << 24) | (r << 16) | b;

        return packed;
    }

    RGB:RGB(uint8_t r, uint8_t g, uint8_t b)
    {
        red = r;
        green = g;
        blue = b;
    }

    void RGB::toGreyscale()
    {
        uint8_t grey = 0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b;
        r = g = b = grey;
    }

Including the header file multiple times will give "redefinition" errors at __compile time__.  Including the same function multiple times will give double definitions at __link time__.

If you stick to this method of laying out .h and .c/.cpp files you will never have a problem with multiple definitions on your own files.  (Unless you re-define a library function by accident, etc.)

Of course it's ok (and quite common) to define short little functions in the header/.h file too. (The compiler typically generates these as inline code though.)  I'm not trying to explain the complete workings of headers & .C files, just presenting you a method which will *always* prevent multiple definition problems.


message:
Which sensor is best for obstacle detecting with retroreflector?

Distance is about 3m. IR or visible light - does not matter.

 It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.

Maybe for this task better to use specific retroreflector?

**UPDATE:**

there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.

The scheme of this sensor should be this:
[![Scheme of sensor][1]][1]

But the use will be this:

[![scheme of use][2]][2]

  [1]: https://i.stack.imgur.com/TXiTh.png
  [2]: https://i.stack.imgur.com/WYjFY.png

body:
I think the question is worded to get a specific answer; I do not know if this is the answer you want. I'll give you that answer first:

I'd say an infrared LED, and an infrared detector.

Strobe the LED, then measure the difference between when it's (known to be) on, and when it's (known to be) off, to compensate for ambient light.

However, if I was doing this, I'd consider an ultrasound sensor - no retroreflector needed; instead you get the distance to the (obstacle or reflector).


body:
I think you're better off with a set-up like this.

*A shiny object might bounce the laser as if it were a mirror.
But we wan't to know if the laser was interrupted.*

So. If we place the sensor on the other side, we can accurately say if the light reaches the sensor. Thus if there is an object between (shiny or not).

*But what if another light-source shines into my sensor? It'll think that there is no object.*

We can encapsulate the sensor, so that only light from the direction of the laser can shine into it. And we can filter out other light "colors".
Also the strength of the laser should be bigger as any other ambien light (not too strong also). You could even choose to make the laser pulse a specific pattern and let the sensor check if it's right.

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

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


message:
Error AT% With GSM/GPRS Shield

I've been trying to control a relay with a GSM shield for an Arduino project. I haven't had any success with either the Software Serial or the GSM library. I've declared the GSM variable in debug mode and it gives me the error AT%.
Using Software Serial, it hangs at SIM900.read().
The SIM card connects to the network, I can see that on the board - the LED flashes every 3 seconds and gives me signals for incoming calls and SMSs.

I can't tell if the error is with the SIM card, the connections to the Arduino board, the power supply (12V) or something completely different. Here are the two code examples I'm using with the different libraries.

Anyone else getting this error? What is the best way to make it go away?

Thanks in advance for any help!

**SoftwareSerial.h**

    #include <SoftwareSerial.h>
    char inchar; // Will hold the incoming character from the GSM shield
    SoftwareSerial SIM900(7, 8);

    int Relay1 = A2;
    int Relay2 = A3;

    void setup()
    {
      Serial.begin(19200);
      //Set up relay control pins
      pinMode(Relay1, OUTPUT);
      digitalWrite(Relay1, HIGH);
      // wake up the GSM shield
      SIM900.begin(19200);
      delay(10000);  // give time to log on to network.
      SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
      delay(100);
      SIM900.print("AT+CNMI=2,2,0,0,0\r");
      // output contents of new SMS upon receipt to the GSM shield's serial out
      delay(100);
      Serial.println("Ready...");
      }

    void loop()
    {

      //If a character comes in from the cellular module...
      if(SIM900.available() >0)
      {
        inchar=SIM900.read();
        Serial.println(inchar);
        if (inchar=='#')
        {...}
        SIM900.println("AT+CMGD=1,20"); // delete all SMS
      }
    }

**GSM.h** - in this case I haven't even gotten past the .begin() command. This code is from the example at http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER ""

    // initialize the library instances
    GSM gsmAccess(true);
    GSM_SMS sms;
    GSM3_NetworkStatus_t   gsmStatus;
    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

    void setup()
    {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("SMS Messages Receiver");
      char code = 'X';
      Serial.flush();
      gsmStatus = gsmAccess.begin(PINNUMBER,false,false);

      int retrycount = 60;
      while (gsmStatus != GSM_READY && retrycount-- > 0) {
        delay(1000);  // lower delay value could lead to unstable state
        theGSM3ShieldV1ModemCore.manageReceivedData();
        gsmStatus = gsmAccess.getStatus();
      }

      if (gsmStatus != GSM_READY) {
        Serial.println("\n[ERR]: GSM connection failed\n");
        Serial.flush();
        gsmAccess.shutdown();
        delay(250);
        digitalWrite(3,LOW);
      }

      Serial.println(" [DONE]");

      // connection state
      boolean notConnected = true;
      // Start GSM connection
      while (notConnected)
      {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      {
          notConnected = false;
      }
        else
        {
          Serial.println("\nNot connected");
          delay(1000);
        }
      }
      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

body: Check your baud rates. They appear to be different. That will cause problems.


body:
I used Mega 2560 connected to GSM shield as following:

- GSM TX --- pin 10 on Mega
- GSM RX --- pin 3 on Mega

- GND to GND


message:
How to program a CLK signal and its inverse with Arduino/AVR

Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)?

I'm using the following code in arduino to output a 1MHz signal on OC1A:

    //Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
    //J.Christensen 27Apr2012

    void setup(void)
    {
        DDRB = _BV(DDB1);                  //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
        TCCR1A = _BV(COM1A0);              //toggle OC1A on compare match
        OCR1A = 7;                         //top value for counter
        TCCR1B = _BV(WGM12) | _BV(CS10);   //CTC mode, prescaler clock/1
    }

    void loop(void)
    {
    }

body:
What about also setting COM1B0 and then setting the initial values of OC1A and OC1B to opposites by writing to PORTB?

Also, I presume you mean 1 MHz and not 1 mHz?


body:
Various AVRs have the capability to output both the normal and inverted timer waveform from a single output compare register simultaneously on two pins. These devices include, but are not limited to, ATtinyX5/V, ATtiny26/L, ATtinyX61A, and ATmegaXXU4.

The ATmega328P does not have this capability, therefore the smallest primary source Arduino that does is the Leonardo (ATmega32U4) and comparable devices. The Adafruit Trinket and the Digispark (both ATtiny85-based) also offer this.


body:
Another option is to do this in hardware - it's trivial to invert a signal.

For example, see the selected answer for https://electronics.stackexchange.com/questions/30238/how-to-invert-a-digital-signal - the second diagram - connect Vs to your clock, and Vo will be your inverted clock. For the two resistors, anything over 1k should be fine. Or use an inverter (which is the same thing, in one component, but is much less likely to be in your random-part box).

Note: There will be a very short delay going through this circuit - one place I saw suggested 1.5ns, but see the spec sheet of your transistor. A 1mhz clock "ticks" at 1,000ns (I guess, 500ns on, 500ns off), so this delay shouldn't be significant.


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

How about this?

    void setup()
      {
      // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
      // Setting DDB1 and DDB2
      DDRB |= bit (DDB1) | bit (DDB2);

      // stop timer 1
      TCCR1A = 0;
      TCCR1B = 0;

      TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                            // OC1B at BOTTOM (inverting mode)
             | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                            // OC1A at BOTTOM (non-inverting mode)
             | bit (WGM11);                 // Fast PWM, top at ICR1
      TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
             | bit (CS11);                  // Start timer, prescaler of 8

      // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
      ICR1 = 0xFFFF;
      OCR1B = 299;
      OCR1A = ICR1 - OCR1B;

      }  // end of setup

    void loop()
      {
      }

Results on a Uno:

[![Normal and inverted timer output][1]][1]

Output on Uno pins 9 and 10.

Change the prescalers and counters to your desired frequency.

---

The screenshot doesn't show one signal exactly the inverse of the other. The *pattern* is inverted. If you had a 50% duty cycle, it would be an exact inverse.

---

> It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical

OK, make OCR1A and OCR1B both 7:

      ICR1 = 15;
      OCR1B = 7;
      OCR1A = 7;

*Why 7? And why 15?*

The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:

* Period: 16 ticks of the 16 MHz clock
* Duty cycle: 8 ticks of the 16 MHz clock

---

Now, one cycle:

[![Scope shot 1][2]][2]

They change over at the same instant - pulse width exactly 500 ns.

[![Scope shot 2][3]][3]

And they change back at the same moment - pulse width also 500 ns.

  [1]: https://i.stack.imgur.com/mc8Sk.png
  [2]: https://i.stack.imgur.com/YefHP.png
  [3]: https://i.stack.imgur.com/dNPMd.png


message:
Linear acceleration from MPU 6050

When reading the MPU 6050 has accelerometer and gyro, I assumed it was linear acceleration, but now I second guess that.  From this video https://www.youtube.com/watch?v=qmd6CVrlHOM it seems like they are using acceleration and gyro to make one rotation direction.  I need to know what direction the mpu is moving, not just a rotational value.  Is there a way to extract this information?

body:
The MPU6050 has an accelerometer and a rate gyro (which tells you how fast it is rotating). The accelerometer will tell you which direction is down and in a motionless situation, that is all the information you have.

You'll probably want something like the MPU9150, it has a compass, which will give you the directional information you're asking for.


body:
The MPU6050 has accelerometers in the x, y, and z axis. When placed on flat surface with no acceleration, you should get 0g (or whatever unit it uses, I cannot remember off the top of my head) in the x and Y directions, and 1g in the z axis. By continuously polling these values, you can find out the linear  acceleration of each axis at a given moment in time.

What you saw is probably because the chip also has three Gyroscopes, for measuring rotational acceleration and speed. The chip can do both.


message:
avr-g++ (or avr-gcc) and LiquidCrystal library

I'm trying to run a simple Hello World program from [Arduino 1.6.5][1] from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by `avr-g++` I have hard way to figure out how to include all libraries - so far I got this script:

    avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
    -I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
    -I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
    avr-g++ -mmcu=atmega328p main.o -o main
    avr-objcopy -O ihex -R .eeprom main main.hex
    sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

First line (with both `-I` flags) compiles, but after running second line, I get:

    main.o: In function `main':
    main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
    main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
    main.o: In function `_GLOBAL__sub_I_lcd':
    main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
    collect2: error: ld returned 1 exit status

How can I also include some libraries? I need the exact bash script.

  [1]: https://www.arduino.cc/en/Main/Software

body:
I made a Makefile to compile the Blink program a little while back. It wasn't trivial.

    #
    # Simple Arduino Makefile
    #
    # Author: Nick Gammon
    # Date: 18th March 2015

    # where you installed the Arduino app
    ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

    # various programs
    CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
    CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
    AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
    OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

    MAIN_SKETCH = Blink.cpp

    # compile flags for g++ and gcc

    # may need to change these
    F_CPU = 16000000
    MCU = atmega328p

    # compile flags
    GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
    CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
    CC_FLAGS  = $(GENERAL_FLAGS)

    # location of include files
    INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

    # library sources
    LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

    build:

     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
     rm core.a
     $(AR) rcs core.a malloc.c.o
     $(AR) rcs core.a realloc.c.o
     $(AR) rcs core.a WInterrupts.c.o
     $(AR) rcs core.a wiring.c.o
     $(AR) rcs core.a wiring_analog.c.o
     $(AR) rcs core.a wiring_digital.c.o
     $(AR) rcs core.a wiring_pulse.c.o
     $(AR) rcs core.a wiring_shift.c.o
     $(AR) rcs core.a CDC.cpp.o
     $(AR) rcs core.a HardwareSerial.cpp.o
     $(AR) rcs core.a HID.cpp.o
     $(AR) rcs core.a IPAddress.cpp.o
     $(AR) rcs core.a main.cpp.o
     $(AR) rcs core.a new.cpp.o
     $(AR) rcs core.a Print.cpp.o
     $(AR) rcs core.a Stream.cpp.o
     $(AR) rcs core.a Tone.cpp.o
     $(AR) rcs core.a USBCore.cpp.o
     $(AR) rcs core.a WMath.cpp.o
     $(AR) rcs core.a WString.cpp.o
     $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
     $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
     $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

---

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.


message:
Issue with CD74HC4067 MUX on high values

I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.

Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).

My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.

I hope I've been clear enough and that someone can point me the right way!

EDIT:

Here is the schematic
[![Schematic][1]][1]
<!-- source: https://s27.postimg.org/yyb1s82f7/illu_arduino_UNO.png -->

(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)

And my code:

    #define MUX A0
    #define S0 A2
    #define S1 A3

    void setup() {
      Serial.begin(9600);
      pinMode(S0, OUTPUT);
      pinMode(S1, OUTPUT);

      selectMux(1);
    }

    void loop() {

      //selectMux(0);
      //Serial.println(analogRead(MUX));
      //selectMux(1);
      Serial.println(analogRead(MUX));

    }

    void selectMux(byte port) {
    //  pinMode(MUX, mode);
      int r0 = bitRead(port, 0);
      int r1 = bitRead(port, 1);

      digitalWrite(S0, r0);
      digitalWrite(S1, r1);
      analogRead(MUX);
    }

the `analogRead(MUX)` in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:

    Output:
    76
    41
    77
    76
    76
    75
    36
    75
    74
    76
    77
    106
    76
    76
    76
    76

but it goes crazy when the input is higher, close to 5V:

    Output:
    948
    780
    340
    948
    948
    635
    437
    949
    948
    499
    551
    949
    950
    396
    684
    950

If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.

I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.

[Sound Sensor](http://www.dx.com/p/157205),
[Light Sensor](http://www.dx.com/p/152409)

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

body:
I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.

Connect them both to ground.


message:
How can I make motor vibrate using arduino depending on the ultrasonic distance?

I want to make the vibration motor vibrate depending on the distance to an obstacle, for example if the distance is too short it should vibrate quickly and vice versa.

How can i make motor vibrate using arduino depending on the distance?
Can you explain for me how can I use the delay in the vibration code?
I found this code in the internet for vibration:

    digitalWrite(y, HIGH);
    delay(50);
    digitalWrite(y, LOW);
    delay(50);

I know that I can change the delay, but how can we do it depending on our purpose?
Please help me .. I don't know the use of the delay :(

body:
You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.

Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:

    [...]
    val = analogRead(A0);
    digitalWrite(5, HIGH);
    delay(val);
    digitalWrite(5, LOW);
    [...]

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.

For example:

    if(variable > 50){
      // if the variable named variable is over 50 this code is going to be executed
    } else {
      // If the variable is below 50 this is executed
    }

If you are unfamiliar with if conditions then I suggest reading [this too][1].

  [1]: https://www.arduino.cc/en/Reference/if


body:
I want to show you my thinking, and tell me please if it is right or wrong:

I build an relationship between the distance and the speed.

I know that (speed = distance/time) and if the obstacle is too close to the ultrasonic sensor the speed of the motor should be maximum, so I have decrease the time which is the delay, right?

I make the code according what i said above and it is shown below:

        if(distance <= 60 && distance >= 45)// the distance is too large
        {
        digitalWrite(motorPin, HIGH);

        delay(200);// I increase the delay to make the motor vibrate slowly

        digitalWrite(motorPin, LOW);

        delay(200);

        }

        else if(distance < 45 && distance >= 30)
        {
        digitalWrite(motorPin, HIGH);

        delay(100);

        digitalWrite(motorPin, LOW);

        delay(100);

       }
        else if(distance < 30){

        digitalWrite(motorPin, HIGH);

        delay(50);

        digitalWrite(motorPin, LOW);

        delay(50);

      }
      else
      {
        digitalWrite(motorPin, LOW);// If the distance is too large the motor will be off
      }


body:
> I know that I can change the delay, but how can we do it depending on our purpose?

Are you asking how to use a *variable*? An example:

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

    const int LED = 13;

    void setup()
      {
      pinMode (LED, OUTPUT);
      }

    void loop()
      {
      int amount = analogRead (A0);   // get a reading
      digitalWrite(LED, HIGH);
      delay(amount);
      digitalWrite(LED, LOW);
      delay(amount);
      }

That code reads some analog device, and adjusts the delay based on the figure it read.


message:
Protocol options for data exchange between Arduino and ESP8266

I have a device built with an Arduino uno:

- Arduino software installed on an Arduino uno

- can be controlled via serial commands

- can be controlled via physical buttons and sensors

- on any button/sensor state change it writes the current state to serial

- if no message has been sent within 5 seconds, it sends a no-change serial message

---

What is needed:

- Use an ESP8266 to provide a bridge between current Arduino software and MQTT / web

- I can program the ESP8266 as a web server, MQTT client, etc with the Arduino IDE or Lua (but I prefer the Arduino IDE since I can reuse parts of the code to generate / interpret communication).

- the ESP8266 will handle everything that is required for wifi / web / MQTT; without the MQTT module the Arduino part will work stand-alone, only the remote control will be missing.

- I would like to make minimal changes to the Arduino code (or none, if possible). Any changes would involve extensive re-testing, which I try to avoid.

- the ESP8266 can be missing in some installs.

---

What options I found:

1. Serial

ESP8266 can read the serial output and be a bridge between web/MQTT and serial, will store the current state in memory to be sent when requested to avoid polling the device every time.

One of the benefits is no code changes / testing required for the Arduino part.

2. I2C

Make the Arduino the I2C master and the ESP8266 the slave (or the other way around) and implement bi-directional communication. Got the idea by reading [this thread][1].

---

Some other information about the serial commands:

A data packet (command or state description) consists of 1 to 20 characters, with a possible peak of 20 packets in 5 seconds, and an average of one packet every 3 seconds. If needed, I can make this send 5 unsigned integers instead of alphanumeric characters.

If more than the I2C / serial pins are needed I can upgrade to an Arduino Mega (so the number of free pins is not an issue).

Are there any other options for this? (protocols, pre-made libraries for serial communication, etc). I'm trying not to reinvent the wheel..

Thank you for your time!

  [1]: https://arduino.stackexchange.com/questions/3042/i2c-2-way-communication-between-arduino-uno-and-arduino-mega

body:
Most I2C tutorials made each Arduino a slave and master, but [this][1] approach is better, because each Arduino is either a master or a slave (not both) and no switching is needed. That makes things easier.

I2C is better than serial, because you can add more Arduinos in the same bus.

I have implemented I2C between two Arduinos and it's not more complicated that reading/writing to the serial port (which you have already done). And I bet you can generalize your serial port code to work with both serial and I2C comms.

This is my example (just a proof of concept). The slave Arduino controls a some pins, a temp. sensor and a watchdog under orders from the master Arduino. If slave doesn't receive a beat in time, it reset the master Arduino.

**Master code**

    #include <Wire.h>

    #define CMD_SENSOR    1
    #define CMD_PIN_ON    2
    #define CMD_PIN_OFF   3
    #define CMD_LUMEN     4
    #define CMD_BEAT      5

    const byte SLAVE_ADDRESS = 42;
    const byte LED = 13;

    char buffer[32];

    void setup ()
    {
      Serial.begin(9600);
      Serial.println("Master");

      Wire.begin ();

      pinMode (LED, OUTPUT);
      digitalWrite(LED, HIGH);
      delay(1000);
      digitalWrite(LED, LOW);

      Wire.beginTransmission (SLAVE_ADDRESS);
      Serial.println("Send LED on");
      Wire.write (CMD_PIN_ON);
      Wire.write (2);
      Wire.write (10);
      Wire.endTransmission();
      int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
      Serial.print("status=");
      Serial.println(x);
    }  // end of setup

    void loop ()
    {
      Serial.println(".");
      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write (CMD_SENSOR);
      Wire.endTransmission();
      int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
      Serial.print("Disponibles = ");
      Serial.println(x);
      int temp = (int) Wire.read();
      Serial.println(temp);

      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write (CMD_LUMEN);
      Wire.endTransmission();
      Wire.requestFrom(SLAVE_ADDRESS, 2);
      int light = Wire.read() << 8 | Wire.read();
      Serial.print("Light=");
      Serial.println(light);

      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write (CMD_BEAT);
      Wire.endTransmission();
      Wire.requestFrom(SLAVE_ADDRESS, 1);

      delay (5000);
    }  // end of loop

**Slave code**

    /*
       Esclavo I2C

       Recibe los siguientes comandos
       <- 1° byte -> <- 2° byte -> <- 3° byte ->
       CMD_SENSOR
       CMD_PIN_ON    n° de pin     duracion en segundos
       CMD_PIN_OFF   n° de pin
       CMD_LUMEN
       CMD_BEAT

       Cada comando recibe una respuesta, ya sea el valor pedido
       o un status.
    */
    #include <max6675.h>
    #include <Wire.h>

    typedef struct {
      int pin;
      unsigned long off;
    } PIN_PGMA;

    /*
       Lista de pines que se pueden activar via CMD_PIN_ON.
    */
    #define PIN_LUMEN   A0
    #define PIN_LED      2
    #define PIN_RESET    3
    PIN_PGMA pgma[] = {
      {PIN_LED, 0},
      {PIN_RESET, 0}
    };
    const int pgmaSize = sizeof(pgma) / sizeof(PIN_PGMA);

    #define CMD_SENSOR    1
    #define CMD_PIN_ON    2
    #define CMD_PIN_OFF   3
    #define CMD_LUMEN     4
    #define CMD_BEAT      5

    #define ST_OK         0
    #define ST_BAD_PIN    1
    #define ST_TIME_0     2
    #define ST_BAD_LEN    3

    #define MY_ADDRESS  42

    //  Maximo tiempo de espera entre comandos CMD_BEAT. Pasado
    //  ese tiempo, se activa el PIN_RESET.
    //  En milisegundos.
    #define BEAT_INTERVAL 10000
    unsigned long lastBeat;
    //  Largo del reset en milisegundos.
    #define RESET_LENGTH  250
    byte cmd = 0;
    byte status = 0;

    int thermoDO = 11;
    int thermoCS = 12;
    int thermoCLK = 13;

    MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

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

      pinMode(PIN_LUMEN, INPUT);
      analogRead(PIN_LUMEN);

      for (int i = 0; i < pgmaSize; i++) {
        pinMode(pgma[i].pin, OUTPUT);
        digitalWrite(pgma[i].pin, LOW);
      }
      lastBeat = millis();

      Wire.begin (MY_ADDRESS);
      Wire.onReceive (receiveCommand);
      Wire.onRequest (sendAnswer);
    }

    void loop()
    {
      unsigned long now = millis();

      //  Baja la linea de RESET si no ha recibido un beat ultimamente.
      unsigned long diff = now - lastBeat;
      if (diff > BEAT_INTERVAL) {
        resetPin();
      }

      //  Recorre la lista de pines y apaga aquellos cuyo tiempo termino.
      for (int i = 0; i < pgmaSize; i++) {
        if (pgma[i].off > 0 && pgma[i].off <= now) {
          Serial.print("off pin="); Serial.println(pgma[i].pin);
          pgma[i].off = 0;
          digitalWrite(pgma[i].pin, LOW);
        }
      }
    }

    // called by interrupt service routine when outgoing data is requested
    void sendAnswer() {
      byte temp;
      int  lightReading;

      switch (cmd) {
        case CMD_SENSOR:
          temp = thermocouple.readCelsius();
          Wire.write(temp);
          break;
        case CMD_LUMEN:
          lightReading  = analogRead(PIN_LUMEN);
          Wire.write(lightReading >> 8);
          Wire.write(lightReading % 0xFF);
          break;
        case CMD_PIN_ON:
        case CMD_PIN_OFF:
        case CMD_BEAT:
          Wire.write(status);
          status = ST_OK;
          break;
      }
      cmd = 0;
    }

    // called by interrupt service routine when incoming data arrives
    void receiveCommand (int howMany) {
      cmd = Wire.read ();
      status = ST_OK;
      switch (cmd) {
        case CMD_PIN_ON:
          cmdPinOn();;
          break;
        case CMD_PIN_OFF:
          cmdPinOff();
          break;
        case CMD_BEAT:
          lastBeat = millis();
          break;
      }
    }  // end of receiveEvent

    void cmdPinOff() {
      if (Wire.available() != 1) {
        status = ST_BAD_LEN;
      } else {
        int pin = Wire.read();
        int i = searchPin(pin);
        if (i < 0) {
          status = ST_BAD_PIN;
        }
        else {
          pgma[i].off = 0;
          digitalWrite(pin, LOW);
        }
      }
    }

    int searchPin(int pin) {
      int i = pgmaSize - 1;
      while (i >= 0 && pgma[i].pin != pin) {
        i--;
      }
      return i;
    }

    /*
     * Programa el encendido y duracion del RESET.
     */
    void resetPin() {
      if (digitalRead(PIN_RESET) == LOW) {
        unsigned long now = millis();

        int i = searchPin(PIN_RESET);

        pgma[i].off = now + RESET_LENGTH;
        lastBeat = now;
        digitalWrite(PIN_RESET, HIGH);
      }
    }

    void cmdPinOn() {
      if (Wire.available() != 2) {
        status = ST_BAD_LEN;
      } else {
        int pin = Wire.read();
        int len = Wire.read();

        int i = searchPin(pin);
        Serial.print("pin="); Serial.print(pin); Serial.print(",index="); Serial.println(i);
        if (i < 0) {
          status = ST_BAD_PIN;
          Serial.println("bad pin");
        } else {
          if (len == 0) {
            status = ST_TIME_0;
            Serial.println("ban len");
          }
          else {
            pgma[i].off = millis() + len * 1000;
            digitalWrite(pin, HIGH);
            Serial.println("ok");
          }
        }
      }
    }

  [1]: http://www.berryjam.eu/2014/07/advanced-arduino-i2c-communication/


body:
Using I2C (which i recommend over serial), you may not use a NodeMCU ESP8266 as a slave.  It can only function as master.  An Arduino, on the other hand, may be either.  Therefore, the Arduino will always be passive and the NodeMCU will be the master.

What you can do, is implement a semaphore ([as described by Majenko here][1]), where the Arduino signals that it has something to "say" to the master, causing the master to request from the Arduino.  It could, under these circumstances, be labeled an "obliging master" (neologism).

NEVER print to serial from inside `requestEvent` or `receiveEvent`.

  [1]: https://arduino.stackexchange.com/a/67462/30341