message:
Arduino Simon Says with Midi Controller

I altered code for the Simple Simon says to work with a Midi controller instead of push buttons. i am having trouble with the input of the song sequence with the Midi Controller. during the time where the code is waiting for input from the Midi controller **waitForButton(int delay)** the notes being inputted should sound but it dose not . i need help in figuring this out. any advice would be appreciated. Here's my code :https://pastebin.com/dV73eF9U

    const int PLAY = 1;
    const int TRYAGIN = 2;
    long currentMillis = 0;
    long previousMillis = 0;
    int state;
    void songlearn(int tune);
    void showsequence();
    void readsequnce();
    void incorrect();
    int tune;

    void loop() {
      if (state == PLAY) {
        showsequence();
        readsequnce();
      }
      else if (state == TRYAGIN) {
        incorrect();
        state = PLAY;
      }
    }

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
      data1 = MIDI.getData1();
      if (data1 == 48) { //C3
        Status[0][0] = 1;
        noteOn(0, data1, 100);
        input[0] = data1;
      }
      if (data1 == 49) { //C3#
        Status[0][1] = 1;
        noteOn(0, data1, 100);
        input[1] = data1;
      }
      if (data1 == 50) { //D3
        Status[0][2] = 1;
        noteOn(0, data1, 100);
        input[2] = data1;
      }
      if (data1 == 51) { //D3#
        Status[0][3] = 1;
        noteOn(0, data1, 100);
        input[3] = data1;
      }
      if (data1 == 52) { //E3
        Status[0][4] = 1;
        noteOn(0, data1, 100);
        input[4] = data1;
      }
      if (data1 == 53) { //F3
        Status[1][0] = 1;
        noteOn(0, data1, 100);
        input[5] = data1;
      }
      if (data1 == 54) { //F3#
        Status[1][1] = 1;
        noteOn(0, data1, 100);
        input[6] = data1;
      }
      if (data1 == 55) { //G3
        Status[1][2] = 1;
        noteOn(0, data1, 100);
        input[7] = data1;
      }
      if (data1 == 56) { //G3#
        Status[1][3] = 1;
        noteOn(0, data1, 100);
        input[8] = data1;
      }
      if (data1 == 57) { //A3
        Status[1][4] = 1;
        noteOn(0, data1, 100);
        input[9] = data1;
      }
      if (data1 == 58) { //A3#
        Status[2][0] = 1;
        noteOn(0, data1, 100);
        input[10] = data1;
      }
      if (data1 == 59) { //B3
        Status[2][1] = 1;
        noteOn(0, data1, 100);
        input[11] = data1;
      }
      if (data1 == 60) { //C4
        Status[2][2] = 1;
        noteOn(0, data1, 100);
        input[12] = data1;
      }
      if (data1 == 61) { //C4#
        Status[2][3] = 1;
        noteOn(0, data1, 100);
        input[13] = data1;
      }
      if (data1 == 62) { //D4
        Status[2][4] = 1;
        noteOn(0, data1, 100);
        input[14] = data1;
      }
      if (data1 == 63) { //D4#
        Status[3][0] = 1;
        noteOn(0, data1, 100);
        input[15] = data1;
      }
      if (data1 == 64) { //E4
        Status[3][1] = 1;
        noteOn(0, data1, 100);
        input[16] = data1;
      }
      if (data1 == 65) { //F4
        Status[3][2] = 1;
        noteOn(0, data1, 100);
        input[17] = data1;
      }
      if (data1 == 66) { //F4#
        Status[3][3] = 1;
        noteOn(0, data1, 100);
        input[18] = data1;
      }
      if (data1 == 67) { //G4
        Status[3][4] = 1;
        noteOn(0, data1, 100);
        input[19] = data1;
      }
      if (data1 == 68) { //G4#
        Status[4][0] = 1;
        noteOn(0, data1, 100);
        input[20] = data1;
      }
      if (data1 == 69) { //A4
        Status[4][1] = 1;
        noteOn(0, data1, 100);
        input[21] = data1;
      }
      if (data1 == 70) { //A4#
        Status[4][2] = 1;
        noteOn(0, data1, 100);
        input[22] = data1;
      }
      if (data1 == 71) { //B4
        Status[4][3] = 1;
        noteOn(0, data1, 100);
        input[23] = data1;
      }
      if (data1 == 72) { //C5
        Status[4][4] = 1;
        noteOn(0, data1, 100);
        input[24] = data1;
      }
    }

    void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
      data1 = MIDI.getData1();
      if (data1 == 48) { //C3
        Status[0][0] = 0;
        noteOff(0, data1, 100);
        input[0] = 0;
      }
      if (data1 == 49) { //C3#
        Status[0][1] = 0;
        noteOff(0, data1, 100);
        input[1] = 0;
      }
      if (data1 == 50) { //D3
        Status[0][2] = 0;
        noteOff(0, data1, 100);
        input[2] = 0;
      }
      if (data1 == 51) { //D3#
        Status[0][3] = 0;
        noteOff(0, data1, 100);
        input[3] = 0;
      }
      if (data1 == 52) { //E3
        Status[0][4] = 0;
        noteOff(0, data1, 100);
        input[4] = 0;
      }
      if (data1 == 53) { //F3
        Status[1][0] = 0;
        noteOff(0, data1, 100);
        input[5] = 0;
      }
      if (data1 == 54) { //F3#
        Status[1][1] = 0;
        noteOff(0, data1, 100);
        input[6] = 0;
      }
      if (data1 == 55) { //G3
        Status[1][2] = 0;
        noteOff(0, data1, 100);
        input[7] = 0;
      }
      if (data1 == 56) { //G3#
        Status[1][3] = 0;
        noteOff(0, data1, 100);
        input[8] = 0;
      }
      if (data1 == 57) { //A3
        Status[1][4] = 0;
        noteOff(0, data1, 100);
        input[9] = 0;
      }
      if (data1 == 58) { //A3#
        Status[2][0] = 0;
        noteOff(0, data1, 100);
        input[10] = 0;
      }
      if (data1 == 59) { //B3
        Status[2][1] = 0;
        noteOff(0, data1, 100);
        input[11] = 0;
      }
      if (data1 == 60) { //C4
        Status[2][2] = 0;
        noteOff(0, data1, 100);
        input[12] = 0;
      }
      if (data1 == 61) { //C4#
        Status[2][3] = 0;
        noteOff(0, data1, 100);
        input[13] = 0;
      }
      if (data1 == 62) { //D4
        Status[2][4] = 0;
        noteOff(0, data1, 100);
        input[14] = 0;
      }
      if (data1 == 63) { //D4#
        Status[3][0] = 0;
        noteOff(0, data1, 100);
        input[15] = 0;
      }
      if (data1 == 64) { //E4
        Status[3][1] = 0;
        noteOff(0, data1, 100);
        input[16] = 0;
      }
      if (data1 == 65) { //F4
        Status[3][2] = 0;
        noteOff(0, data1, 100);
        input[17] = 0;
      }
      if (data1 == 66) { //F4#
        Status[3][3] = 0;
        noteOff(0, data1, 100);
        input[18] = 0;
      }
      if (data1 == 67) { //G4
        Status[3][4] = 0;
        noteOff(0, data1, 100);
        input[19] = 0;
      }
      if (data1 == 68) { //G4#
        Status[4][0] = 0;
        noteOff(0, data1, 100);
        input[20] = 0;
      }
      if (data1 == 69) { //A4
        Status[4][1] = 0;
        noteOff(0, data1, 100);
        input[21] = 0;
      }
      if (data1 == 70) { //A4#
        Status[4][2] = 0;
        noteOff(0, data1, 100);
        input[22] = 0;
      }
      if (data1 == 71) { //B4
        Status[4][3] = 0;
        noteOff(0, data1, 100);
        input[23] = 0;
      }
      if (data1 == 72) { //C5
        Status[4][4] = 0;
        noteOff(0, data1, 100);
        input[24] = 0;
      }
    }

    //Send a MIDI note-on message.  Like Pressing a piano key
    void noteOn(byte channel, byte note, byte attack_velocity) {
      talkMIDI( (0x90 | channel), note, attack_velocity);
    }

    //Send a MIDI note-off message.  Like releasing a piano key
    void noteOff(byte channel, byte note, byte release_velocity) {
      talkMIDI( (0x80 | channel), note, release_velocity);
    }

    //Plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that data values are less than 127
    void talkMIDI(byte cmd, byte data1, byte data2) {
      mySerial.write(cmd);
      mySerial.write(data1);
      //Some commands only have one data byte. All cmds less than 0xBn have 2 data bytes
      //(sort of: http://253.ccarh.org/handout/midiprotocol/)
      if ( (cmd & 0xF0) <= 0xB0)
        mySerial.write(data2);
    }

    void playNote(int midi, int row, int col, int len, bool short_led = false)
    {
      int len1, len2;
      if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
      } else {
        len1 = len;
        len2 = 0;
      }
      noteOn(0x90, midi, 100);
      digitalWrite(LedR[row], HIGH);
      digitalWrite(LedC[col], LOW);
      delay(len1);
      digitalWrite(LedR[row], LOW);
      digitalWrite(LedC[col], HIGH);
      delay(len2);
      noteOff(0x90, midi, 0);
    }

    void songlearn (int tune) {
      if (tune == 1) {

        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("Learning Song :");// Print a message to the LCD.
        lcd.setCursor(1, 1);
        lcd.print(menuP1);

        //Plays Mary Had a Little Lamb on a loop at 145 BPM

        //Bar 1
        note[0] = 0x40;
        note[1] = 0x3e;
        note[2] = 0x3c;
        note[3] = 0x3e;
        //Bar 2
        note[4] = 0x40;
        note[5] = 0x40;
        note[6] = 0x40;
        //Bar 3
        note[7] = 0x3e;
        note[8] = 0x3e;
        note[9] = 0x3e;
        //Bar 4
        note[10] = 0x40;
        note[11] = 0x43;
        note[12] = 0x43;
        //Bar 5
        note[13] = 0x40;
        note[14] = 0x3e;
        note[15] = 0x3c;
        note[16] = 0x3e;
        //Bar 6
        note[17] = 0x40;
        note[18] = 0x40;
        note[19] = 0x40;
        note[20] = 0x40;
        //Bar 7
        note[21] = 0x3e;
        note[22] = 0x3e;
        note[23] = 0x40;
        note[24] = 0x3e;
        //Bar 8
        note[25] = 0x3c;
        //End song
      }
    }

    void (*SongSeq[x])() =
    { //Bar 1
      [] { playNote(0x40, 3, 1, 414); } ,//Quarter note: E
      [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
      [] { playNote(0x3c, 2, 2, 414); } ,//Quarter note: C
      [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
      //Bar 2
      [] {playNote(0x40, 3, 1, 414, 1);} , //Quarter note: E
      [] {playNote(0x40, 3, 1, 414, 1); }, //Quarter note: E
      [] {playNote(0x40, 3, 1, 828, 1); }, //Half note: E
      //Bar 3
      []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
      []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
      []{playNote(0x3e, 2, 4, 828, 1);}, //Half note: D
      //Bar 4
      []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
      []{playNote(0x43, 3, 4, 414, 1);}, //Quarter note: G
      []{playNote(0x43, 3, 4, 828, 1);}, //Half note: G
      //Bar 5
      []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
      []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
      []{playNote(0x3c, 2, 2, 414);}, //Quarter note: C
      []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
      //Bar 6
      []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
      []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
      []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
      []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
      //Bar 7
      []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
      []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
      []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
      []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
      //Bar 8
      []{playNote(0x3c, 2, 2, 1656);}, //Whole note: C
      //End song

    };

    void showsequence() {
      //Add a new index to the end of the songseq
      SongSeq[largestindex];
      largestindex++;
      //loop through the songseq
      for (int index = 0; index < largestindex; index++) {
        SongSeq[index]();
      }
    }

    void readsequnce() {
      bool mademistake = false;
      int key;
      for (int index = 0; index < largestindex & mademistake == false; index++) {
        key = waitForButton(5000);
        if (key == -1 | key != note[index]) {
          mademistake = true;
          SongSeq[index]();
          SongSeq[index]();
          state = 2;
        }
      }
    }

    int waitForButton(int delay)
    {
      int keyPressed = -1;
      int check;
      boolean keyBackUp = false;

      currentMillis = millis();      // The number of ms since the program started running
      previousMillis = currentMillis;   // Records the point when we start spinning the loop.

      // Keep spinning the loop until "delay" seconds have passed.
      while (currentMillis - previousMillis < delay & keyBackUp == false)
      {
        // Read the button and record when it has been pushed down.
        for (int i = 0; i < 25 & keyBackUp == false; i++)
        {
          if (input[i] != 0)
          {
            keyPressed = input[i];

            // Show the LED pushed.
            noteOn(0, keyPressed, 100);
            //  digitalWrite(leds[pin], HIGH);

            // It is possible the button is still being pushed.
            // This loop spins until the button is let up.
            while (currentMillis - previousMillis < delay & keyBackUp == false)
            {
              check = input[i];
              if (check == 0)
              {
                keyBackUp = true;
              }
              currentMillis = millis();
            }

            // Turn the LED pushed off.
            noteOff(0, keyPressed, 0);
            // digitalWrite(leds[pin], LOW);

            // See if they took to long.
            if (currentMillis - previousMillis > delay)
            {
              keyPressed = -1; // They took to long to let the button up so they lose.
            }
          }
        }

        currentMillis = millis();

      }

      return keyPressed;
    }

body:
I notice that nothing in the code you posted calls the `MyHandleNoteOn()` function, which is the only thing that reads MIDI data in the code you posted.

The `waitForButton()` function where you say you're having the problem never does any input or output, it simply checks to see if something else has changed the `input` array. `MyHandleNoteOn()` above does change it.

This leads me to believe that code you haven't posted sets up an interrupt handler that calls `MyHandleNoteOn()` (and probably `MyHandleNodeOff()`). If that doesn't mean anything to you, the main problem here is that the program is a bit beyond your abilities and you need to start learning on something simpler. If it does mean something to you, the problem here is that the program is rather badly written and you need to write something simpler to practice using interrupts and shared memory communication.

Have you written simpler programs before that read MIDI events, do a bit of processing, and play back things based on that? Building a Simon Says game on top of that would be a good learning project.


sender: user

message:
Molex power with USB serial Communication from the same PSU

Before I begin I just want to apologize for my mediocre understanding of things electrical and arduino. I know there are a lot of topics similar to this but I'm confused by the term external PSU

**Question**

Do I need to worry about any sort of issues (loops/grounding) if I use the molex connector to supply power to my arduino uno ***and*** continue to use the USB for serial communication at the same time? The source of both would be from the same PSU in my PC.

From what I understand the Uno when powered by DC should not exceed 7.5V for maximum efficiency. So it looks like the 5V from the molex would be more suitable than the 12V and sufficient for my needs of roughly 3.6A (60mA per LED * 60). Since USB can only supply a maximum of 2.0A and Molex appears to supply up to 5.0A from what I've read.

And I would connect it like so [5V molex powered Uno][1]?

**Background**

Currently I'm using the arduino uno to power a single 5V strip of 30 rgb WS2812B leds, which works great when powered through the USB port, but since I need an additional strip of 30 leds and USB alone cannot supply enough amperage to power both I need a better source of current. I also needed the cleanest solution possible as it's for a PC tower and I don't want to use an external power source.

Edit - **Alternative solution**

If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino

  [1]: https://i.stack.imgur.com/6v7Kp.jpg "5V powered Uno"

sender: assistant

body:
Two important things first:

1. **The Uno 5 V pin and power bus must never be supplied more than 5.5 V** or the MCU may die. The DC power input jack (the barrel jack) and the `Vin` pin, which are connected together, are not directly connected this bus, which is why you can supply higher voltages to that (see below).

2. **You can not simultaneously supply power via both the USB cable and a power supply to the `5V` pin/5 V bus** because that would directly connect the two power supplies. That's a very bad thing, and probably not just for the Uno. (But there is a trick you can use here to still connect USB data when you are supplying power to `5V`; see below.)

Now on to the details.

You can safely connect `Vin` (the pin or the barrel jack; they are directly connected) and USB at the same time because there's a switch (`T1` on [the schematic](https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf)) on the board that will disconnect the USB power line from the Arduino 5V bus if more than 3.3 V is being supplied to `Vin`.

However, `Vin` goes through a regulator which, while it has the advantage of safely handling voltages much higher than 5 V, also causes some voltage drop, so you need to supply it with a minimum of 7 V. (6 V might work if there's very little power draw; 5 V almost certainly will not.) The maximum voltage you should supply is 20 V, but it's recommended that you stick to 12 V or less, since higher voltages mean that the regulator can get rather hot.

Unfortunately for you, this doesn't really help with your problem. While you could take the 12 V power off the molex connector, supply it to `Vin` and run the Arduino itself quite happily with the USB cable also connected, the regulator on `Vin` is rated for only 1 A, which is considerably less than you need for the entire system.

There are ways to have some parts of the system powered by one power supply and other parts powered by a separate power supply, but they're not trivial (and also beyond my expertise at the moment :-)).

Probably the easiest solution is to connect the 5 V output from the molex connector to your system power bus, which would be supplying both the `5V` pin on the Arduino and your external components, and then build a custom USB cable with only the `D+` and `D-` pins connected, dropping the power and ground pins. (You don't need the ground pin because the USB data signal is actually a differential signal: the difference or similarity in the voltage between D+ and D- pins is what determines whether the signal is a `1` or a `0`.)

By the way, just to make sure, you do have some separate switching for all those LEDs, right? You're not trying to provide all their power via the Arduino digital outputs? Because, as per section 32.1 of the [ATmega328P datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf), while you are allowed to sink up to 40 mA from any individual data pin, you cannot sink more than 200 mA in total from the chip.


body: If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino


message:
Powering an USB to Serial from USB

I am creating a PCB which is a modification of the [Arduino on a breadboard][1]. I am intending to buy an [USB to Serial][2] breakout from Adafruit so that I can upload my sketches to the atmega 328 I'll be using.

However, in order to reduce power consumption (later I want to run my circuit by using some AA batteries), I would like to turn off the USB to Serial breakout. I thought originally about adding a SPST switch to disconnect it when not using it, but I wonder if it is possible to power it from the USB (whenever I connect something) instead of having to connect its VCC header to the circuit's 5v power.

Is it possible to do that? Or is there any other way I to accomplish this that I'm not thinking of?

**UPDATE:** *For clarity sake, I will explain my design choices: I want this circuit to power some peristaltic pumps that work on 12V. Thus, I'm providing 12V for the pumps and using a regulator to lower the voltage to the circuit. I don't see this is a huge problem for power consumption because the circuit will be in low-power 98% of the time, only waking up one minute per hour. Sometimes, it will run on batteries, which is the reason I wanna eliminate the USB-to-Serial. However, when connected to a power adaptor, I want the USB to be available.*

All the best,

Francis

  [1]: https://www.arduino.cc/en/Main/Standalone
  [2]: https://www.adafruit.com/product/3309

body:
That is not easy to do. You could try diodes and mosfets as switches, but one way or the other, there will probably some leakage current. The 6N137 requires power for the receiving signal.
Other common optocouplers might have leakage current in the nA range for the transistor output. That might be possible. Connect the GNDs. The RX and TX via optocouplers. DTR to RESET with 100nF as usual. Maybe you don't need extra inverters when the transistor outputs are used as emitter followers.

Could you make your project with the ATmega328P without the usb-to-serial module ? The Arduino Pro Mini does not have a usb-to-serial either.
Now that I mention the Arduino Pro Mini: Instead of making an Arduino compatible circuit with a ATmega328P, you could also buy a Arduino Pro Mini 8MHz, and remove the voltage regulator and the power led. Then you have the same thing.

That breadboard Arduino tutorial has +5V connected to AREF. Please don't do that. Keep AREF open, or connect a capacitor of 100nF to it to reduce some noise for analogRead.

In the deepest sleep mode, the ATmega328P can run more than a year on three AA batteries. The timer of the WatchDog can be used to wake up.
The voltage of the three AA batteries is directly connected to the VCC of the ATmega328P, without voltage regulator.

A very good tutorial about power saving is this: [Nick Gammon about power saving][1]

  [1]: https://www.gammon.com.au/power


body:
You might be overthinking this. As Gerben points out in the comments, you might want to consider pluging in the USB to Serial breakout board only when required, instead of making it a permanent part of your prototype.

I do this myself in two ways, depending of what I need.

Option 1:
---------

When I foresee a lot of debbuging through the Serial Monitor, I use a permanent pin header so I can attach and dettach the breakout board easily.

In this case I use a right angle pin header so as to keep a low profile. Like in this Arduino Pro Mini:

[![90-deg pin header][1]][1]

Option 2:
---------

When I just need to upload the sketch to the Arduino and I know that I won't be using the breakout board from that moment on, I don't solder the pin header in place.

Instead, I've modified another breakout board using pogo pins (spring test probes):

[![USB to Serial board with pogo pins][2]][2]

This modified board is what I use to upload the code to the Arduino without any pin header whatsoever. Something like this (I've taken the picture just for illustrative purposes):

[![Code upload via pogo pins][3]][3]

  [1]: https://i.stack.imgur.com/MyCsMl.jpg
  [2]: https://i.stack.imgur.com/hBWBrl.jpg
  [3]: https://i.stack.imgur.com/VH5oel.jpg


body:
Using separate power supplies at the same time for different parts of your system is a bad, bad idea; you never want two separate power supplies potentially pushing current at each other. Using separate +5V power sources for different chips but sharing a common ground across the device and connecting just data lines is problematic, too; as far as I know it's not trivial to do safely. Unless you really know what you're doing, full isolation between separately powered components is the way to go.

The two parts of the system we're talking about here, the USB-Serial converter and the rest of the system, exchange digital data only, and that at only three points, all of which are unidirectional: serial TX, serial RX and DTR. (DTR, when pulled low by the PC, resets the Arduino). Therefore if we can isolate these links not to exchange current when they communicate, we can separately power the devices on each side of this isolation barrier.

This is actually a common problem in things like power supplies (where we want data from the high-voltage side sent to the low-voltage side but don't want the risk that someone touching the low-voltage side could get electrocuted) and motor control boards (where the motors often use a separate power supply from the controller logic to reduce noise passed into the controller logic). One common solution is to use [opto-isolators](https://en.wikipedia.org/wiki/Opto-isolator) (also called optocouplers). Typically these use an LED and a sensor looking at it from across a gap; when the LED is lit up by one side, the other side sees it and generates a current.

The [6N137](http://datasheet.octopart.com/6N137.-Fairchild-Semiconductor-datasheet-10074984.pdf) (as used in [this answer](https://electronics.stackexchange.com/q/160699/15390)) or similar chip should work for this: 10 MHz is plenty of bandwith to run a 115,200 baud serial link. Each opto-coupler would be powered by the receiving side (Arduino for its RX and DTR, USB-serial for Arduino's TX) and on the other side you'd connect data to the VF+ pin and ground to the VF- pin. As per note 1 on page 4, you'll need caps at the power supply inputs, and you'll have to add inverters as well if you use this particular opto-isolator, since it inverts the signal; a [74HC04](http://assets.nexperia.com/documents/data-sheet/74HC_HCT04.pdf) will give you six of those. If you want to save a dollar, you could not bother to connect the DTR line and just reset the Arduino manually when you want to upload a program, if that's not too inconvenient.

Consumer warning here: I've not actually built this circuit (though I'd like to give it a try one day), so there could be something I'm missing here. (Hopefully someone more expert than me will speak up if that's the case.)

If you're going to be spending any significant amount of time connected to USB power and your whole system can run on less than 500 mA (the limit of the USB supply from many PCs), you may want to consider powering the entire system from USB while it's connected. This can be done in a way similar to how the Arduino Uno board disconnects USB power when receiving power on `Vin`: switch it with a comparator and a MOSFET.


message:
how to move my robot to the assigned coordinates

I am working on an ground surveillance robot using an Arduino mega for programming, am using components like the HMC5883L compass, Adafruit GPS for assigning of coordinates (latitude and longitude) which are the way points, I have written up the code for both the compass and the GPS and am able to get information from them, but now what I want for my robot to move to those specified coordinates (latitude and longitude waypoints) which I don't know how to do please do pardon me for asking such question cause I am new to coding GPS and compass and I would appreciate it if anyone could help me out or explain a bit in details what I need to do please find my code here http://textuploader.com/drqwv

body:
Due to my robot I have been thinking about this problem quite a few times but I never got to coding.  So this is a purely my thinking no experience.

The problem is not only calculating where you are and where to go. The robot needs to move so it needs to know whether it needs to turn (left or right; slow or fast) to drive into the correct direction.
So basically you want a method that takes the compass direction the 2 gps locations and returns a speed and turn value.
The speed and turn value will be different for a waypoint and the final destination. I thought to do so by switching to the next waypoint before coming in the "slow down area". This should make that only one algorithm can handle both situations.
I think the algorithm is likely to look like this.
Given the 2 gps locations calculate the expected compass reading.
Given the 2 gps locations calculate the distance
Based on the distance and the difference between the expected and actual compass reading decide on the speed and turn.

As to the last step there is no "one size fits all" for instance a skid driven robot may opt to turn on the spot until it hits the expected compass reading.
If you have a slow turning robot and you are close to the waypoint you may opt to drive backwards first (like parking a car)

I hope this helps


message:
reverse 12v motor

I am working on an RC car, and I need to be able to reverse a 12v circuit that powers my main drive motor.

I have a TIP102 transistor and a 5-30v relay for each motor terminal. I assumed that I could open up ground via the transistor on one side, and the power relay on the other, and then switch these to reverse.

My motor runs each direction when hooked directly to the battery, and my relays are definitely outputting the full 12v, but I seem to have a problem with the grounding circuit. Whichever side has the relay switched on, that transistor gets very hot, and my motor doesn't spin. I tested the transistor and can get it to ground when on a single directional circuit with just the relay on one side and the TIP102 on the other.

Here is my wiring. Can anyone tell me where I screwed up?

Ignore the 9v, I just couldnt find a 12v in fritzing
[![enter image description here][1]][1]

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

body:
If the diagram correctly represents what you have, it isn't obvious to me what the problem might be.  One possibility is that the base resistors to the TIP102's are too large.  Too little current into a transistor base keeps a transistor out of saturation, ie operating in a linear mode instead of switching mode, leading to high power loss and high heat.  Slightly more likely is that the fairly high voltage drop across the Darlington in the TIP102 is just heating it up a lot.

If, as suggested in a comment, you were to use an H-bridge motor driver, it might include heat sinks or might use MOSFETs with lower voltage drops; thus avoiding so much lost heat, one way or the other.

As it happens, you probably don't need the transistors in the circuit anyway.  Label the relays as A and B.  Hook one of the motor leads to the common terminal of A, and the other motor lead to the common terminal of B.  Hook the NO lead of each relay to V+, and the NC lead of each to ground.  To run one direction, switch A on and B off.  To run the other direction, switch A off and B on.  To stop, switch both off.


message:
ATtiny85 Timer 1 comparator A interrupt problem

I'm writing a program on attiny85 using interrupts. It is a simple program:
- when rising edge is detected on PCINT0, drive `DEBUG_PIN` to `HIGH`
- when TIMER1 counts up to OCR1A, drive DEBUG_PIN to LOW

Problem is that when program detects rising edge on PCINT0, it starts Timer1 comparator A and then immediately calls `ISR(TIMER1_COMPA_vect)`. As an effect, on `DEBUG_PIN` there is only a little narrow spike instead of a nice square wave of length 50ms (checked it with oscilloscope).

Im using ARDUINO IDE. Here is the code:

    /*
     * Movement detection using interrupts instead of linear approach
     *
     * POS_TIMEOUT will be checked using COMPA on TIM0
     * IMP_TIMEOUT will be checked using COMPB on TIM0
     * LOOP_TIME will be chcecked using TIMER1 overflow
     *
     * INT0_PIN_IN  (PB2) is the pin that receives the signal
     * INT0_PIN_OUT (PB4) is the pin used for external interrupt debugging
     * DEBUG_PIN    (PB3) is the pin used for debugging
     * STATUS_PIN   (PB1) - high when awake, low when asleep
    */

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <avr/wdt.h>
    #include <avr/interrupt.h>
    //#include "timers_init.h"

    //Watch out! do not use the reset pin (PB5)!

    #define INT0_PIN_IN     0
    #define INT0_PIN_OUT    4
    #define STATUS_PIN      1
    #define DEBUG_PIN       3
    #define POS_TIMEOUT     50

    #define PRE_1     0
    #define PRE_2     1
    #define PRE_4     2
    #define PRE_8     3
    #define PRE_16    4
    #define PRE_32    5
    #define PRE_64    6
    #define PRE_128   7
    #define PRE_256   8
    #define PRE_512   9
    #define PRE_1024  10
    #define PRE_2048  11
    #define PRE_4096  12
    #define PRE_8192  13
    #define PRE_16384 14

    /*******MONITORING*VARIABLES*VOLATILES**************/
    /* variable keeping last state of INT0 input */
    volatile bool lastState = false;

    /*************STATUS FLAGS**************************/
    /* flags used for movement detection */
    /* all flags are initiated as false */

    volatile bool positiveFlag  = false;
    volatile bool fallingEdge   = false;
    volatile bool risingEdge    = false;
    volatile bool positiveTimeoutCheck  = false;
    volatile bool impulseTimeoutCheck = false;
    /*************UTILS*********************************/
    void timerOneCompADisable( void ){
      bitClear(TIMSK, OCIE1A);
    }

    void timerOneCompAInit( uint8_t compValue  ){
      //set comparatorA value
      OCR1A = compValue;
      //enable compA interrupts
      bitSet(TIMSK, OCIE1A);
    }

    /******************
     * INTERRUPTS!!!
    ******************/

    /*
     * This interrupt is called every time PCINT0 input state changes
    */
    ISR(PCINT0_vect){
      bool readPin = digitalRead( INT0_PIN_IN );

      //falling edge
      if( lastState && lastState != readPin ){
        fallingEdge = true;
        lastState = false;
      }
      //rising edge
      else if( !lastState && lastState != readPin ){
        risingEdge = true;
        lastState = true;
      }
    }

    //TIMER 1 COMPARE match A
    ISR(TIMER1_COMPA_vect){
      positiveTimeoutCheck = false;
      digitalWrite( DEBUG_PIN, LOW );
      timerOneCompADisable();
    }

    /**********************
     * MAIN CODE!!!!!!!
    **********************/

    void setup(){

      /* Pin config */
      pinMode( INT0_PIN_IN, INPUT );
      pinMode( DEBUG_PIN, OUTPUT);

      /* Pin initialization */
      digitalWrite( DEBUG_PIN, LOW );

      /* Timers configuration */
      //prescaler is 8192 so one tick is ~1 ms
      TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

      /* Interrupts initialization */
      bitSet( GIMSK, PCIE );
      bitSet( PCMSK, PCINT0 );
    }

    /* function resetting flags */
    void resetFlags( void ){
       positiveFlag  = false;
       fallingEdge   = false;
       risingEdge    = false;
       positiveTimeoutCheck  = false;
    }

    int main(){
      cli();
      setup();

      /* Variables initialization */
      lastState = digitalRead( INT0_PIN_IN );
      resetFlags();
      sei();

      while(1){
          /* State machine */

          //if nothing is going on and rising edge is detected
          //reset everything and ignite positive flag
          if( risingEdge ){
            cli();
            resetFlags();
            positiveFlag = true;
            sei();
          } // if

          //INT0 is high, initiate positive timeout check
          else if( positiveFlag && !positiveTimeoutCheck ){
            cli();
            resetFlags();
            timerOneCompAInit( POS_TIMEOUT );
            positiveTimeoutCheck = true;
            digitalWrite( DEBUG_PIN, HIGH );
            TCNT1 = 0;
            sei();
          } //else if

      } //while

      return 0;
    }

body:
You should move the line `TCNT1 = 0;` from `loop()` into `timerOneCompAInit()` function:

    void timerOneCompAInit( uint8_t compValue  ){
      TCNT1 = 0;
      //set comparatorA value
      OCR1A = compValue;
      //enable compA interrupts
      bitSet(TIMSK, OCIE1A);
    }

Otherwise, during the timelapse between  `OCR1A = compValue;` and `TCNT1 = 0;`, it is **highly possible** that `TCNT1` reaches `OCR1A` and thus sets the `OCF1A` flag in `TIFR`, which will generate an interrupt and call `ISR(TIMER1_COMPA_vect)` immediately after `sei()` is called in `loop()`.

The fact is Timer1 is always running since it has been enabled at `setup()`, hence `TCNT1` is continuously changing from 0 to 255 and back to 0.

Hence in your current code, at the time you execute `OCR1A = compValue;`, `TCNT1` may have any value between `0` and `255`, if its value is `>50` (`POS_TIMEOUT`), then an interrupt will be generated.

Roughly the probability for this interrupt to happen is at least 80% (i.e. `(255-50)/255`).


body:
the code is a little too long for me to go through but sounds like this is a one-shot compare.

With that, you should turn off the timer1, clear the timer1 compa flag, set the compare match point forward (COMPA = target count if TCNT1 is reset, or COMPA = TCNT1 + target if TCNT1 is NOT reset), enable the timer1 compa interrupt, and start the timer1. All of that in the PCNT1 interrupt (where timer1 is armed).

Some of the actions can be structured in the timer1 initialization routine, or even after timer1 compa isr if you want to improve the code responsiveness.

Otherwise, your timer1 keeps running and once the counter passes COMPA, the flag is set, regardless of if the interrupt is set or not.


body:
Thank you guys! All I had to do is disable TIMER1, reset it, set COMPA, reset OCF1A ("bitSet(TIFR,OCF1A)") and set prescaler before `sei();`.

Here is my final, working code:

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <avr/wdt.h>
    #include <avr/interrupt.h>
    //#include "timers_init.h"

    //Watch out! do not use the reset pin (PB5)!

    #define INT0_PIN_IN     0
    #define INT0_PIN_OUT    4
    #define STATUS_PIN      1
    #define DEBUG_PIN       3
    #define POS_TIMEOUT     70

    #define PRE_1     0
    #define PRE_2     1
    #define PRE_4     2
    #define PRE_8     3
    #define PRE_16    4
    #define PRE_32    5
    #define PRE_64    6
    #define PRE_128   7
    #define PRE_256   8
    #define PRE_512   9
    #define PRE_1024  10
    #define PRE_2048  11
    #define PRE_4096  12
    #define PRE_8192  13
    #define PRE_16384 14

    /*******MONITORING*VARIABLES*VOLATILES**************/
    /* variable keeping last state of INT0 input */
    volatile bool lastState = false;

    /*************STATUS FLAGS**************************/
    /* flags used for movement detection */
    /* all flags are initiated as false */

    volatile bool positiveFlag  = false;
    volatile bool fallingEdge   = false;
    volatile bool risingEdge    = false;
    volatile bool positiveTimeoutCheck  = false;
    volatile bool impulseTimeoutCheck = false;
    /*************UTILS*********************************/
    void timerOneCompADisable( void ){
      bitClear(TIMSK, OCIE1A);
    }

    void timerOneCompAInit( uint8_t compValue  ){
      //set comparatorA value
      OCR1A = compValue;
      //enable compA interrupts
      bitSet(TIMSK, OCIE1A);
    }

    void timerOneDisable(){
      TCCR1 |= (0<<CS13)|(0<<CS12)|(0<<CS11)|(0<<CS10);
    }

    /******************
     * INTERRUPTS!!!
    ******************/

    /*
     * This interrupt is called every time PCINT0 input state changes
    */
    ISR(PCINT0_vect){
      bool readPin = digitalRead( INT0_PIN_IN );

      //falling edge
      if( lastState && lastState != readPin ){
        fallingEdge = true;
        lastState = false;
      }
      //rising edge
      else if( !lastState && lastState != readPin ){
        risingEdge = true;
        lastState = true;
      }
    }

    //TIMER 1 COMPARE match A
    ISR(TIMER1_COMPA_vect){
      positiveTimeoutCheck = false;
      digitalWrite( DEBUG_PIN, LOW );
      TCNT1=0;
      timerOneCompADisable();
    }

    /**********************
     * MAIN CODE!!!!!!!
    **********************/

    void setup(){

      /* Pin config */
      pinMode( INT0_PIN_IN, INPUT );
      pinMode( DEBUG_PIN, OUTPUT);

      /* Pin initialization */
      digitalWrite( DEBUG_PIN, LOW );

      /* Timers configuration */
      //prescaler is 8192 so one tick is ~1 ms
      TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

      /* Interrupts initialization */
      bitSet( GIMSK, PCIE );
      bitSet( PCMSK, PCINT0 );
    }

    /* function resetting flags */
    void resetFlags( void ){
       positiveFlag  = false;
       fallingEdge   = false;
       risingEdge    = false;
       positiveTimeoutCheck  = false;
    }

    int main(){
      cli();
      setup();

      /* Variables initialization */
      lastState = digitalRead( INT0_PIN_IN );
      resetFlags();
      sei();

      while(1){
          /* State machine */

          //if nothing is going on and rising edge is detected
          //reset everything and ignite positive flag
          if( risingEdge ){
            cli();
            resetFlags();
            positiveFlag = true;
            sei();
          } // if

          //INT0 is high, initiate positive timeout check
          else if( positiveFlag && !positiveTimeoutCheck ){
            cli();
            resetFlags();
            timerOneDisable();
            timerOneCompAInit( POS_TIMEOUT );
            positiveTimeoutCheck = true;
            digitalWrite( DEBUG_PIN, HIGH );
            bitSet(TIFR,OCF1A);
            TCNT1 = 0;
            TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
            sei();
          } //else if

      } //while

      return 0;
    }


message:
Write to serial only if the state of a light sensor changes

I need to know the times when an LED strip turns on and turns off.  The LED switch is driven by light dependent resistor.  When the sun goes down the LED strip turns on. This is all happening on a circuit that I did not create nor is it Arduino driven.  I need to know the times (in local time) that the LED turns on and off.  I have another light dependent resistor near the LED strip and I am using the Arduino Uno to print to the serial monitor its state every second.
I can listen to the serial port via Python and record the seconds via Python.  No worries
What I would like to do is have the Arduino code print to the serial monitor only if the state of the LED changes.  For example, when the LDR turns on the LED strip, Arduino prints to the serial monitor once, then in the morning when the LED goes off, print to the serial monitor once.  I am having trouble figuring out the code to do that.  The LDR is not like a button since it is always reporting back analog data.    Any help is appreciated.

body:
If you have already set the resistor to print to `Serial` every second, then it is simple to modify. Your code is probably like this:

    void loop() {
    // something something
    Serial.println(analogRead(resistorPin));
    // other other
    }

and you want something like this:

    int lastValue,newValue;
    int treshold=200; // or some other empirical value,
    // analogRead() returns 0..1024, so it should be safely inside
    void loop() {
    // something something
    newValue=analogRead(resistorPin);
    if (newValue-lastValue > treshold) {
        Serial.print("Value increased to ");
        Serial.println(newValue);
        lastValue=newValue;
        };
    if (lastValue-newValue > treshold) {
        Serial.print("Value decreased to ");
        Serial.println(newValue);
        lastValue=newValue;
        };
    // other other
    }

the `treshold` value should be set so the event is triggered if substantial change in value happend (so probably those LEDs went on/of) but not trigger when there is a smal change (like cloud going on sky).

Eventually you can also print the time, at which the event happened, using something like http://playground.arduino.cc/Code/DateTime or http://playground.arduino.cc/Code/Time or any other library suiting your needs. You may also consider to use some real time module like https://www.pololu.com/product/2770 or https://www.adafruit.com/product/264 or https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview or any other RTC module you like/have.


body:
You wrote: “_I am using the Arduino Uno to print to the serial monitor
its state every second._” This is exactly the right thing to do. Make a
record of the analog readings for a few days, then plot the readings as
a function of time.

Once you have a nice plot, take a close look at it. You should be able,
by reading the plot, to decide on a threshold value that you can use to
tell whether the LEDs are on or off. Or, better yet, two thresholds in
order to have some hysteresis.

Then you can write something like this:

    const uint8_t LDR_PIN = ...;
    const uint16_t THRESHOLD_LOW = ...;
    const uint16_t THRESHOLD_HIGH = ...;

    uint8_t state = LOW;

    void loop()
    {
        uint16_t reading = analogRead(LDR_PIN);
        if (state == LOW && reading >= THRESHOLD_HIGH) {
            Serial.println("Reading is now HIGH.");
            state = HIGH;
        } else if (state == HIGH && reading < THRESHOLD_LOW) {
            Serial.println("Reading is now LOW.");
            state = LOW;
        }
    }


body:
An LDR doesn't have a "state", being a resistor that varies continuously, and inversely with the light intensity. The LED strip has distinct states: lit and not lit. It sounds like you want your code to deduce the LED state from the sensor value. You'll need to define lighting states based on the the LDR readings, and those readings won't be consistent; they'll vary from measurement to measurement of the same lighting conditions and they'll be affected by changes in the ambient lighting. If you can exclude ambient light falling on the LDR, the job will be easier. @Edgar_Bonet described a way to ranges of LDR readings corresponding to 'lit' and 'not lit'

When a moving average of LDR readings, or some number of consecutive LDR readings falls within the range contrary to the state your code been keeping for the LED lighting, it should change the state and print.

If ambient lighting changes are unavoidably affecting the LDR, you'll definitely need to keep some sort of moving average and watch for a large difference between a small number of averaged readings and the longer-term moving average used to correct for ambient. This is a kind of auto-zeroing and it can lead to its own errors: sensing the room lights being turned on or off, cloud shadows, or a person or animal passage throwing a shadow, can all cause false change-of-state detection.

Update:

I'd add that you might compare the LDR output to 3 ranges: [0 - MAXDARK], [MINLIGHT - 1023], and "neither" - the gray zone in between. This is analogous to how the digital input-pin receivers in the MUC decide whether a digital signal (which is inherently analog) is HIGH or LOW. You'll have to experiment with the values of MAXDARK and MINLIGHT to find the right values for your environment.

Then you you'd print, once, whenever the LDR signal solidly enters either the MAXDARK or MINLIGHT zones, and not again until after the signal has solidly exited that zone, or equivalently, solidly entered the gray zone.

"Solidly" is probably something like NCONSECUTIVE averaged samples. Again, you'll have to find a value for NCONSECUTIVE that is both reliable and responsive. Too low a value may give you several time-stamps for the same event; too high a value will delay how quickly you detect the event (which might be totally irrelevant for a twice-a-day event).


body:
>  I need to know the times (in local time) that the LED turns on and off. .. I am having trouble figuring out the code to do that.

simple.

1. attach a pin to the circuit's output that turn on / off the led.

2. set up your arduino to read the state or state changes of that pin. this can be done via interrupts or polling.

3. based on the state of the pin, determine if the led is on or off, and record the current time.

step #1 can be done with light sensors (on the led's light output). but that can be slightly trickier.

> The LDR is not like a button since it is always reporting back analog data.

you can set up the ldr to read it like a button.


message:
Can I make delayMicroseconds more accurate?

I'm trying to bit bang DMX data and that requires 4us pulses. Not having much luck with the results I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

Here's a quick little test I did:

    unsigned long ptime;

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

    void loop() {
      ptime = micros();
      delayMicroseconds(4);
      Serial.println(micros() - ptime);

      delay(1000); //just to keep the serial monitor from going nuts
    }

And the results:

> 8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

I was kinda shocked at just how bad it's accuracy is. It's double the time I wanted to delay, but it's not even consistent to where I could just divide by 2!

Is there anything I can do to get correct, consistent results?

body:
Your test results are misleading.  `delayMicroseconds()` actually delays fairly precisely (for delays of more than 2 or 3 microseconds).  You can examine its source code in file /usr/share/arduino/hardware/arduino/cores/arduino/wiring.c (on a Linux system; or on some similar path on other systems).

However, the resolution of `micros()` is four microseconds. (See, eg, [the garretlab page about `micros()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring.c/micros.html).) Hence, you will never see a reading *between* 4 microseconds and 8 microseconds.  The actual delay might be just a few cycles over 4 microseconds, but your code will report it as 8.

Try doing 10 or 20 `delayMicroseconds(4);` calls in a row (by duplicating the code, not by using a loop) and then report the result of  `micros()`.


body:
> I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

`micros()` has a [well-documented](https://www.arduino.cc/en/reference/micros) resolution of 4 µs.

You could improve the resolution by changing the prescaler for Timer 0 (of course that throws out the figures, but you can compensate for that).

Alternatively use Timer 1 or Timer 2 with a prescaler of 1, which gives you a resolution of 62.5 ns.

---

>      Serial.begin(9600);

That's going to be slow anyway.

---

>   8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

Your output is exactly consistent with the 4 µs resolution of `micros()` coupled with the fact that sometimes you would get two "ticks" and sometimes one, depending on exactly when you started the timing.

---

Your code is an interesting example of measurement error. `delayMicroseconds(4);` will delay for close to 4 µs. However your attempts to measure it are at fault.

Also, if an interrupt occurs then it will stretch the interval a bit. You need to turn interrupts off if you want an exact delay.


body:
As explained in the previous answers, your actual _problem_ is not the
accuracy of `delayMicroseconds()`, but rather the resolution of
`micros()`.

However, to answer your actual _question_, there is a more accurate
alternative to `delayMicroseconds()`: the function `_delay_us()` from
the AVR-libc is cycle-accurate and, for example

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

    _delay_us(1.125);

does exactly what it says. The main caveat is that the argument has to
be a compile-time constant. You have to `#include <util/delay.h>` in
order to have access to this function.

Note also that you have to block the interrupts if you want any kind of
accurate delay.

**Edit**: As an example, if I were to generate a 4 µs pulse on PD2
(pin 19 on the Mega), I would proceed as follows. First, notice that the
following code

    noInterrupts();
    PORTD |= _BV(PD2);   // PD2 HIGH
    PORTD &= ~_BV(PD2);  // PD2 LOW
    interrupts();

makes a 0.125 µs long pulse (2 CPU cycles), because that's the
time it takes to execute the instruction that sets the port `LOW`. Then,
just add the missing time in a delay:

    noInterrupts();
    PORTD |= _BV(PD2);   // PD2 HIGH
    _delay_us(3.875);
    PORTD &= ~_BV(PD2);  // PD2 LOW
    interrupts();

and you have a cycle-accurate pulse width. It is worth noting that this
cannot be achieved with `digitalWrite()`, as a call to this function
takes about 5 µs.


body:
When measured with an oscilloscope, I found that:

`delayMicroseconds(0)` = `delayMicroseconds(1)` = 4 μs real delay.

So, if you want a 35 μs delay you need:

    delayMicroseconds(31);


body:
> Is there anything I can do to get correct, consistent results?

The Arduino implementation is quite generic thus may not be as effective in some applications. There are a few ways for short delays, each with its own shortfalls.

1. Use nop. Each is one instruction so 16th of a us.

2. Use tcnt0 directly. Each is 4us as the prescaler is set to 64. You can change the prescaker to achieve 16th us resolution.

3. Use ticks, you can implement a clone of systick and use it as basis of the delay. It offers finer resolution plus accuracy.

edit:

I used the following block to time the various approaches:

 time0=TCNT0;
 delay4us();    //65
 //t0delayus(4*16);   //77
 //_delay_us(4);    //65
 //delayMicroseconds(4);  //45
 time1=TCNT0 - time0;  //64 expected

before that, I had reset the timer0 prescaler to 1:1 so each TCNT0 tick is 1/16th of a microsecond.

1. delay4us() is built up from NOP(); it produced a delay of 65 ticks, or just over 4us;
2. t0delayus() is built up from timer0 delays. it produced a delay of 77 ticks; slightly worse than delay4us()
3. _delay_us() is a gcc-avr function. performance on par with delay4us();
4. delayMicroseconds() produced a delay of 45 ticks. the way arduino implemented its timing functions, it tends to under-count, unless in an environment with other interrupts.

hope it helps.


message:
Simplifying code, getting invalid conversion from 'const char*' to 'char*'

I have a program that does 4 times the same thing with different parapmeters; and was trying to simplify my code to take one parameter as a variable.

Example (what was):

    const char MQTT_PUB_IRRIGATION_TANK_VALVE[]      = "ArgyleCourt/Property/Hub/IrrigationTank/Valve";
    const char MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE[] = "ArgyleCourt/Property/Hub/HouseBoreWaterTank/Valve";

    publishTankValveStatusIrrigation(false);

    void publishTankValveStatusIrrigation(bool demandStatus) {
      if (demandStatus) {
        mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "ON");
      } else {
        mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "OFF");
      }
    }

    publishTankValveStatusHouse(false);

    void publishTankValveStatusHouse(bool demandStatus) {
      if (demandStatus) {
        mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "ON");
      } else {
        mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "OFF");
      }
    }

to one function now passing the topic also inot the function, thus needing only one function:

    publishTankValveStatus(false, MQTT_PUB_IRRIGATION_TANK_VALVE);
    publishTankValveStatus(false, MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE);

    void publishTankValveStatus(bool demandStatus, char topicToPublishTo) {
      if (demandStatus) {
        mqttClient.publish(topicToPublishTo, "ON");
      } else {
        mqttClient.publish(topicToPublishTo, "OFF");
      }
    }

when I compile the simplified function, I get "warning: invalid conversion from 'const char*' to 'char' [-fpermissive]", but do neither understand why or how to fix it.

body:
The function declaration

    void publishTankValveStatus(bool demandStatus, char topicToPublishTo)

declares `topicToPublishTo` as a `char`, that is, as a single character instead of as an array of characters that is constant.

Change `char` to `const char *` to say that  `topicToPublishTo` is an array of characters that is constant.


message:
How do I sense that the serial monitor is started?

When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.

body:
You can't. There is no way of detecting if the serial monitor is open or not.

However, you can [disable the automatic reset](http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection) and provide some functionality in your code for saving data to EEPROM when prompted through a command entered on the serial monitor (if you now need to even save the data).


body:
What you really want to do is to store the data before the computer shuts down.

Here is what I did.
 I am running a Mega in a car and using it for a lot of things.  The Mega receives its power from the ignition switch.  When the ignition switch it turned on, the Mega boots up.  In the "setup" section of the program, I set a digital output HIGH.  The digital output is tied to the coil of a relay.  One side of the relay is tied directly to the battery.  Once the relay is energized, the relay supplies power to the Mega.  I have a digital input tied to the power coming from the ignition switch through a resistor and a zener diode to clamp the voltage at 5 volts.  In the main program I monitor the input power digital input.  When I see the power go down,(ignition switch is turned off), I run a Shutdown program that stores all of the data I need stored to the EEProm.  Once that is done, I set the digital output LOW.  This de-energizes the relay and removes the power from the Mega.  If you push the reset button, that is a hardware reset and you lose your data.  If I want to reset the computer, I simply run the "Shutdown" routine. I can do that using a remote switch that drives a digital input.


message:
Cannot locate Rx Tx pins on SIM800a GSM module

I recently bought a SIM800a GSM module in India and I am unable to find the Rx Tx pins of the module to make calls using a Arduino duimilanove.

The main problem is also that I can't find the data sheet for Sim800a in the net so that I can use a multi meter to determine the Rx Tx pins.

Here are some screenshots of the module-

[![Top View showing 4 unlabeled pins compare with the labelled picture on the net ][1]][1]
[![Side View 1][2]][2]
[![Side View 2][3]][3]

There is no label showing Rx Tx here. There is I2C protocol(SCL,SDA) but I dont know how to code in Arduino for making a call using I2C.

I found a SIM800a picture on ebay with labels(not the data sheet) but when I tried using the pins in that manner it did not work. The SIM800a I have is connected to the network as the network led blinks after 3 sec and when I call it then the alarm rings. But it is unable to transmit calls or sms.

[![labelled sim800a][4]][4]

This is the code I am using. I remove the Rx Tx pins before uploading the code and immediately put them after uploading.
<pre>
char phone_no[]="9953642386";
void setup()
{
Serial.begin(9600);  //Open Serial Connection at baudrate 9600
delay(5000);
Serial.println("AT"); // Wake up GSM
Serial.print("ATD"); //Dial the phone number using ATD command
Serial.print(phone_no);
Serial.println(";"); // Semicolon is a must at the end
delay(5000);
Serial.println("ATH"); // After a delay of 5 secs Hang the call
}
void loop()
{
// empty loop.If you enter the above code here,the call will be made FOR EVER repeatedly.
//Take Caution while coding under loop.At some condition you’ve to terminate the Call
}
</pre>
Otherwise is it possible to use the SDA and SCL pins for this purpose of calling to a phone from the gsm module ?
Any help would be appreciated.

  [1]: https://i.stack.imgur.com/TaOSb.jpg
  [2]: https://i.stack.imgur.com/l1jAw.jpg
  [3]: https://i.stack.imgur.com/H974M.jpg
  [4]: https://i.stack.imgur.com/AGpYS.jpg

body:
[This datasheet](http://simcom.ee/documents/SIM800/SIM800_Hardware Design_V1.08.pdf) may help you.  On page 14 you can see TXD and RXD are pins 9 and 10.

Orientation is hard to determine, but it appears that pin 1 is where the most red on the label is.

[![enter image description here][1]][1]
You should now be able to trace where those pins go to. They look like they go to high numbered pins, around the 11/12 area.

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


message:
Reading Arduino serial data in Octave on Mac

I am trying to read serial port data generated by Arduino in Octave on Mac. I installed and loaded the instrument-control package for the same. I used this piece of code to check if the package was installed properly

    if (exist("serial") == 3) disp("Serial: Supported") else disp("Serial: Unsupported") endif

I do get an output saying Serial: Supported.

I am following the tutorial [here][1] for step by step guidance.
I next use `s=serial('portname')` to create a serial port object. However, I am not sure what name to use instead of COM5 on Windows for Mac.

I checked and my Arduino is connected to cu.usbmodem1421 so I tried following 3 options a)cu.usbmodem1421 b) usbmodem1421 c)1421 but in each case I get an error saying "serial: Error opening the interface: No such file or directory".

Could anyone tell me what port name I can use or if there are any suggestions for the big picture problem as to how to read Arduino serial data in Octave (on Mac)? Thanks for the help in advance.

  [1]: http://irnas.eu/other projects/2015/06/04/serial-octave-arduino

body:
You most likely need the full canonical pathname for the port:

    /dev/cu.usbmodem1421

On the Mac, as in Linux and other Unix derivatives, most devices, serial ports included, are special files in the `/dev` directory.


message:
Using Lego temperature sensor with Arduino

I have Arduino mega and Lego temperature sensor which I would like to connect to the Arduino. I'm trying to use a I2C connection between them, with no luck. I connected the sensor and Arduino referring to the picture below:[![wiring][1]][1]
I'm using the Wire library for transmitting data. This is my code currently:

    #include < Wire.h >
    byte ADDRESS=0x98;
    byte CONFIG=0x01;
    void setup(){
      Serial.begin(9600);
      Wire.begin();
      Wire.beginTransmission(ADDRESS);
      Wire.write(CONFIG);
      Wire.endTransmission();
      delay(100);
    }
    void loop(){
      Wire.beginTransmission(ADDRESS);
      Wire.write(CONFIG);
     Wire.endTransmission();
      Wire.requestFrom(ADDRESS,2);
      delay(100);
      int avail=Wire.available();
      Serial.println(avail);
      delay(100);
    }

I found the config and address values from [RobotC drivers][2] for the same sensor. But all I get is zeros. Is there any way i could check for a defect sensor? Is my code correct?

  [1]: https://i.stack.imgur.com/CAUwz.png
  [2]: https://github.com/botbench/robotcdriversuite/blob/master/include/lego-temp.h

body:
I managed to get it work with the following code:

    float getTemp(){
        #define ADDRESS 0x4C
        #define CONFIG 0x00
        float temp;
        Wire.beginTransmission(ADDRESS);
        Wire.write(CONFIG);
        Wire.endTransmission();
        delay(50);
        Wire.requestFrom(ADDRESS,2);
        temp=Wire.read();
        if(Wire.read()==128){
            temp+=0.5;
        }
        return temp;
    }
And connect the green wire to 3.3V, not to the 5V.


message:
Conditional compilation, how to determine whether a variable has been declared?

Whilst using #if/#end constructs, how can I determine whether a specific variable has already been declared?,
e.g.,

    #if [the variable "pinname" has been declared]
    Serial.print(F("Pin name: "));
    Serial.println(pinname);
    #end

If this question has been addressed, I cannot find a reference for it.

body:
Normally you use the "#ifdef" directive.

The opposite is "#ifndef".

For example, if you only wanted to include variable definitions once many use this pattern for a header file named, say, "my_variables.h":

    #ifndef MY_VARIABLES_H
    #def MY_VARIABLES_H

    int counter;
    bool flag;

    #endif

In this way, no matter how many times you include this file, you only define the variables once.  Because after the 1st time the compiler sees this file, the variable MY_VARIABLES_H is defined and the subsequent time the compiler sees this file, the compiler will skip over the variable defines.


body:
You cannot. Simple as that.

I suspect this is an [XY Problem][1]. If you edit your post stating what you're actually trying to do, I'll edit my answer (or delete it if I don't know).

  [1]: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem


message:
ESP8266 unstable connection

I try to flash an ESP12E microcontroller through an FTDI serial converter. It seems like the UART connection is a bit unstable, because when I try to flash it via esptool it often throws "Timed out waiting for packet header" error. Also when I thy to get the flash_id the same error occures at around 50% of the time. The simplier commands like get_mac and chip_id are working well.

I'm using an ESP module with wires soldered to its pads. It is put into a breadboard and it's connected to a USB-UART converter via jumper wires.

What could be the problem?

body:
Power supply...

I designed a pcb for the ESP module, it works like a charm since then. Used a TC1262 regulator, a 100n ceramic and a 1000u electrolyte capacitor (maybe 100u would have been enough) very close to the Vcc and GND pins.

Seems like the ESP is really sensitive to the power supply stability.


message:
Capacitor Questions

I've designed a board (HAT) that uses the ATmega328P microcontroller, and I think I might have made some mistakes in the board design. The design is most like the Arduino Pro mini, but with a 5A dual channel H-bridge, running at 3.3V 16MHz, and using the Raspberry Pi as the power source.

My Board: https://github.com/cescalemodels/BaseStationHAT/tree/master/Hardware

Arduino Pro Mini: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

1) Do I have to have C3? I think it's for power stability and needs to be put next to the microcontroller, but I'm really not sure and want to eliminate it as a possibility as to which part made the board fail.

2) Do I need C2 if I'm not using the DTR Pin?

3) I assume that I don't need C13 and C10 because I'm getting power from the Pi, but can someone confirm?

If it helps, when I boot the raspberry pi, the serial port comes up, but I am totally incapable of communicating. Are there other components that I'm missing?

body:
Every active chip should have adequate decoupling. That is the point of C3, to provide decoupling for the MCU. It is required.

While you don't need capacitors on the output of a non-existent regulator you do need a reservoir capacitor on the power input to your board. 10uF should be adequate.

No, you don't need the DTR capacitor if DTR is not connected to anything.

All that aside, there are two fundamental flaws I can see:

* The raspberry pi can only provide something like 50mA on the 3.3v supply. (Or originally anyway, it may have improved with newer versions)
* The ATMega chip cannot run reliability at 16MHz from just 3.3v. 10MHz is your top limit IIRC.


message:
Arduino pins always reading HIGH (1)

I have tried changing pinModes and I/O declarations but still getting erratic or unexpected pin readings (HIGH), even though, I think, that I have set them LOW during setup. I read elsewhere that this is not uncommon, but I have not found a similar situation or a suitable explanation/solution. I can only believe that it is a basic misunderstanding (still learning). Thanks for any support. By the way, I had deleted the use of the keypad for trial purposes. My code is below:

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

    //////////////////////////// Initialize & Includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;
    boolean pir_SensorPin = 2;
    int led_OutPin = 11; // green
    int alarm_OutPin = 12; // red
    int alarm_count = 0;
    boolean switchPin = 4; // alarm on test
    boolean keypadPIN;
    int z = 0;
    int i = 0;
    int waitTime = 5000;

    //////////////////////////// Setup Keypad //////////////////////////
    const byte ROWS = 4; // four rows
    const byte COLS = 4; // four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// Setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection;
      pinMode (switchPin, INPUT);       // Set pinMode.
      pinMode (led_OutPin, OUTPUT);     // Set pinMode.
      pinMode (alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (pir_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (led_OutPin, LOW);   // Set output pins to LOW for start.
      digitalWrite (alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (switchPin, LOW);
      digitalWrite (pir_SensorPin, LOW);
      Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = Network READY");
        digitalWrite (led_OutPin, HIGH);
      }
      //  attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
      Serial.println ("System Ready");

    }

    //////////////////////////// State Setup //////////////////////////
    enum STATE {
      armed, // system acknowledges trigger
      unarmed, // system unarmed via keypad entry setting keypadPIN = LOW
      justActivated, // PIR-triggered
      alarm // confirm system unarmed then goto unarmed state else start alarm
    };

    STATE systemState = unarmed;
    long timeGettingArmed;

    /////////////////////////// Trigger ///////////////////////////////
    //void trigger() {
    //  systemState = alarm;

    //////////////////////////// State Machine //////////////////////////
    void loop() {
      check(); Serial.print ("switchPin = "); Serial.println (switchPin);
      Serial.print ("pir_SensorPin ="); Serial.println (pir_SensorPin);
      switch (systemState) {
        case armed:
          Serial.println ("armed");
          if (digitalRead (pir_SensorPin == HIGH)) {
            systemState = alarm;
          } else if (digitalRead (keypadPIN == LOW)) {
            systemState = unarmed;
          }
          break;
        case unarmed:
          if (digitalRead (pir_SensorPin == HIGH)) {
            Serial.println ("unarmed");
            timeGettingArmed = millis(); // Or just do a delay here.
            systemState = justActivated;
          }
          break;
        case justActivated:
          Serial.println ("juatActivated");
          if (timeGettingArmed + waitTime < millis()) {
            systemState = armed;
          }
          break;
        case alarm:
          Serial.println ("alarm");
          if (digitalRead (keypadPIN == LOW)) {
            systemState = unarmed;
          } else {
            beep();
          }
          break;
      }
    }

    //////////////////////////// Alarm //////////////////////////
    void beep() {
      Serial.println("at beep");
      // (sms.SendSMS("**********", "*** Motion Detected in Studio! ***"));
      Serial.println ("MOTION detected: SMS Sent");
      for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
        digitalWrite (alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
        digitalWrite (alarm_OutPin, LOW); delay (500);
        digitalWrite (led_OutPin, HIGH); // delay (1000);
        Serial.println (alarm_count);
      }
      systemState = armed;
    }

    void check() {
      if (digitalRead (switchPin == HIGH)) { // manual test in lieu of keypad attached
        (keypadPIN = LOW); // unarmed
      }
      else {
        (keypadPIN = HIGH); // armed
      }
      Serial.print ("switchPin = "); Serial.println (switchPin);
      Serial.print ("keypadPIN = "); Serial.println (keypadPIN);
    }

    Serial output shows:
    pir_SensorPin =1
    switchPin = 1
    keypadPIN = 1
    switchPin = 1

body:
Your code to read from the pins is incorrect. You write

    if (digitalRead (pir_SensorPin == HIGH)) {

However, this compares `pir_SensorPin == HIGH`, (which is `2 == HIGH`), producing a true or false that it then passes as the argument to `digitalRead`, which will try to interpret that as a pin number. Fix your parentheses:

    if (digitalRead(pir_SensorPin) == HIGH)  {

(This problem occurs throughout your code.)

You also are writing an input pin in your setup, which is not necessarily wrong (it is one way of enabling or disabling the pullup resistor), but you should understand why you're doing it:

    pinMode (pir_SensorPin, INPUT);   // Set pinMode.
    ...
    digitalWrite (pir_SensorPin, LOW);


message:
Life span of arduino

We are students of Pragati Engineering College -AP. We are currently working on Automatic Street Light  project selected in Smart India Hackathon 2017 under ministry of steel. For this project  We are using Arduino nano to control street lights in industries. Now we are requiring some general following  information about arduino nano.

What is the life span of Arduino nano?
We need a micro-controller with on analog input pin to read analog voltage and four digital pins for output. The program that we are dumping include  serial communication with Java UI in PC. The program occupies 6750 bytes, 318 bytes for global variables and 1730 bytes for local variables. We would like to know which arduino board is best suitable for our project?

body:
> What is the life span of Arduino nano ?

Electronics doesn't really "die". Treated well, it should last for years. I have a [RFID security system](http://gammon.com.au/forum/?id=11283) that I made in 2011 (six years ago, as I write this) and it is still working perfectly.

> We would like to know which arduino board is best suitable for our project ?

These sorts of questions are hard to answer. What is "best"? Price? Size? Weight? Ease of use?


body:
Atmel chips (the ones used in the Arduino) have been used in all sorts of industrial appilications way before Arduino came along. Same for other micro controllers like the still popular 8051.
What you want to focus on might be the enclosure, seal it against the outside.

Rather than using a (chunky) pre-manufactured Arduino board, you'll have to pick the right chip for your application and design a board around it. http://www.atmel.com/products/microcontrollers/avr/


body:
> What is the life span of Arduino nano ?

Many years.

Flash memory can degrade with time and the program can become corrupted or lost - however:

> Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

Wet electrolytic capacitors dry out over time. When resurrecting old hardware the first thing you do is replace all the electrolytic capacitors. Depending on how much you de-rate them they could last a few years, or tens of years, before they need replacing. If possible avoid them and use MLCC and tantalum instead since they never dry out.

The biggest problem of any kind of industrial installation is that of the environment. Corrosion from airborne contaminates (water, etc) will destroy the PCB (oxidise the copper of the tracks, etc) long before the components have worn out. Proper sealing, and even "potting" in extreme environments, is essential for longevity.

Another important thing to remember is to factor in a certain number of failures over the intended lifetime of the product. If you find you will be needing to replace portions of a unit on a semi-regular basis then make those portions easy to replace. For instance, it may be more cost effective to routinely replace a board after 5 years rather than have to replace the entire unit every 8 years because the board that has failed is impossible to replace (e.g., it's potted).

As others have mentioned you shouldn't be using an Arduino of any form in a product. Instead you will be designing (or paying someone to design) a dedicated PCB. During that design phase extra steps can be taken to make the board more rugged - such as wider tracks and thicker copper that will take longer to corrode; increased clearances that will take longer for corroded copper to bridge; components chosen to have a suitable [MTBF](https://en.wikipedia.org/wiki/Mean_time_between_failures), etc.

Many components have a "service life" or "lifetime" quoted. This is especially important for components such as electrolytic capacitors. For instance, the [EEUFR1C471 from Panasonic](http://uk.farnell.com/panasonic-electronic-components/eeufr1c471/cap-alu-elec-470uf-16v-rad/dp/1800634) (to pick one at random) is quoted as 6000 hours at 105°C. 105°C is the maximum temperature you can run it at, so the quoted service life is a *minimum* at *worst case* parameters. 6000 hours is, of course, just 250 days (about 8 months or so) - but of course that is *worst case*, and the *minimum guaranteed* time (they *guarantee* that it will run for *at least* 6000 hours at 105°C). Run it at a lower temperature and you get longer life out of it.


body:
> What is the life span of Arduino nano ?

the answer is use dependent. Just like you don't know for sure what's the life span of a particular individual, it is hard to know the life span of a product in a particular application, as it depends on the environment, design, and operations of that application.

> We would like to know which arduino board is best suitable for our project ?

hard to tell, and likely none. street lighting is exposed all sorts of elements, from high / low temperatures to moistures and lightening for example, and demands high reliability in all conditions, particularly in failure. Arduino wouldn't be great in that environment.

if you have to go down that path, develop the code in arduino and burn the hex into bare chips so you have the choice of the chip and other components going into your application.


message:
Design vehicle tracking device

I want to create an Arduino based vehicle tracking device which will be moved into a production board without Arduino later. Right now I have a few questions:

 - What GPS module should I use for a best result (little time to fix from a cold start and high accuracy locations)? It will be good if support GLONASS. I want to detect when the car is turning (using HMC5983). I've bought Ublox NEO-6M GPS module and tested it into the car, but it cannot find a location.
 - What MCU I should buy? I also want to communicate with OBD II port of vehicle over the CAN protocol (using MCP2551 + MCP2515). For now i choose ATMega328.
 - How to power all elements ?

PS: Data from the vehicle and the GPS locations will be send over GPRS with SIM800l module.

Cheers

body:
There are some SIMCOM modules with GPRS + GPS, for example: [SIM968][1]

In addition to GPS, it also supports GLONASS/Galileo/QZSS.

As for the MCU, you will need something more powerful than ATMega328, because 2KB RAM is not enough for multi-threading + GPS code + GSM/GPRS code + CAN + etc. Also it hasn't CAN peripheral. You will need MCU with ARM core. From Arduino line, [Arduino Due][2] looks suitable: has 96KB RAM, multiple HW serials, CAN. There is also compatible CAN library [here][3]. Also worth looking on STM32F103 (or STM32F407 with Cortex M4) which also can used be with Arduino IDE with some extra effort (STM32 MCUs usually more cost effective than Atmel counterparts, and have higher performance).

  [1]: http://www.simcom.eu/index.php?m=termekek&prime=1&sub=41&id=0000000245&page=1
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardDue
  [3]: https://github.com/McNeight/CAN_Library


message:
(SOLVED) Fast HW check: (18 digital + 4 analog to I2C ) Arduino Mini Pro + MCP23017 or STM32?

**Arduino Mini Pro+MCP23017** or  **STM32**

I want make device, which reads 17 digital buttons and 4 analog, process it somehow and send the result to I2C bus. Also there is a LED to be managed. I may want to attach some wireless too later, but I am not really sure, if I woud do it (which would need 5-6 mor digital pins). I need to update the firmware often, as it is under heavy developement just now. I should make the PCB as soon as possible, but programming can wait some time.

The PCB would have buttons and analogs on it (and `MCP` in the arduino case). Also lot of connectors, like I2C, programming interface and some power regulators, the LED (or maybe more of them, if there was few free pins, but it is not mandatory). The processor will be connected via wires for space reasons (and maintainability and the board may be redesined later), so only long row of soldering pads on PCB for it.

**Main decision:**
If I opt to Arduino, then `MCP` will be part of the PCB and connected to `I2C` bus, if I use STM32, no `MPC` will be present and buttons would go directly to output connector.

Making the HW is no problem for me, the logic inside is also easy (basically read all inputs, normalize analogs to some range, make some simple tests and if desired, send result over I2C. Reply to some simple I2C too.)

I have a lot of Arduino Mini Pro, but it is few legs short for the task, so I would use MCP23017 expander for 16 of that digital buttons.

I also got some these STM32
https://www.aliexpress.com/item/STM32F103C8T6-ARM-STM32-Minimum-System-Development-Board-Module-For-Arduino/32279776568.html but did not open the package yet. Anyway I want to learn to use them "sometimes soon".

Maybe it is just the kind of starter project, which I would like to do.

Now I am just not sure about the number of available pins on the STM32, on first look it have more pins, but each description I found yet states too much details about additional functions, but I got confused about the basics here. So my question is:

**Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?**

body:
> Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?

it can be programed as Arduino, manage I2C communication, and still have 18+4 I/O pins free or 23+4 I/O free.

it is only knowable to the person programming it whether it can be done easily or comfortably.


message:
Gravity fan does not work when powered by 3.3V ESP8266

The gravity fan has 3 pins. I connected one pin to the ground, one pin to the digital pin numbered 2 on ESP8266. I uploaded this code but the fan doesn't run at all. The fan supposedly uses a 5V power supply but the ESP8266 only supplies 3.3V. Could this be the problem?

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

    void loop() {
      digitalWrite(2, HIGH);
    }

body: The ESP can only supply 12 milliamperes of current. The fan most likely uses a whole lot more. You could for example uses a transistor to turn on the fan.


message:
LCD display and ultrasonic sensor not functioning

[![enter image description here][1]][1]I am doing fish feeder project with level detection for the feeds but lcd display and ultrasonic sensor did not function.

    #include <LiquidCrystal.h>
    #define trigPin 12              // the trig pin to digital pin 12
    #define echoPin 13              // the Echo pin to digital pin 13
    #define L 8
    #define M 9
    #define H 10
    // #define trigmotor 1 //closelid
    int led = A1;           // LED indicator to digital pin A1
    #include <Servo.h>
    Servo MyServo;

    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    const int thresholdH = 0;
    const int thresholdM = 70;
    const int thresholdL = 90;
    // defines variables
    long duration;
    int distance;
    float percentLV;

    void setup()
    {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      Serial.begin(9600); // Starts the serial communication
      pinMode(led,OUTPUT);
      digitalWrite(led,LOW);            //set the led off(initial condition)
      lcd.begin(16, 2);
    }
    void loop()
    {

    int degreesOfRotation = 8;
    int servoPinNumber = 11;
    float hoursBetweenMeals = 12;
    float mealDelayTime = 0;

    {
        MyServo.attach(11);
        MyServo.write(degreesOfRotation);
        mealDelayTime = hoursBetweenMeals * 1800000;
        delay(20);

        while(degreesOfRotation < 152) {
            MyServo.write(degreesOfRotation);
            delay(10);
            degreesOfRotation += 1;
        }
        while(degreesOfRotation > 8) {
            MyServo.write(degreesOfRotation);
            delay(10);
            degreesOfRotation -= 1;
        }
        delay(mealDelayTime);
    }

    {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance = (duration * 0.034 / 2);
      float percentLV = (40 - ( distance - 16 )) * 100 / 40;

      if (percentLV > thresholdL && percentLV < 100) {

        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("PLEASE REFILL!");
        lcd.setCursor(0, 1);
        //lcd.print(distance);
        lcd.print(percentLV);
        lcd.print(" %");
        digitalWrite(H, HIGH);
        digitalWrite(M, LOW);
        digitalWrite(L, LOW);
        //digitalWrite(trigmotor, HIGH);
        //delay(3000);
        //digitalWrite(trigmotor, LOW);
        //delay(1000);
        digitalWrite (led, HIGH);      // Turn on the led indicator
        delay(20);
      } else if (percentLV <= thresholdL && percentLV > thresholdM) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("U May Refill Now");
        lcd.setCursor(0, 1);
        //lcd.print(distance);
        lcd.print(percentLV);
        lcd.print(" %");
        digitalWrite(H, LOW);
        digitalWrite(M, HIGH);
        digitalWrite(L, LOW);
        //digitalWrite(trigmotor, LOW);
        digitalWrite (led, HIGH);      // Turn on the led indicator
        delay(20);
      } else if (percentLV <= thresholdM && percentLV > thresholdH) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Take it easy");
        lcd.setCursor(0, 1);
        //lcd.print(distance);
        lcd.print(percentLV);
        lcd.print(" %");
        digitalWrite(H, LOW);
        digitalWrite(M, LOW);
        digitalWrite(L, HIGH);
        //digitalWrite(trigmotor, LOW);
        digitalWrite (led, LOW);      // Turn off the led indicator
        delay(20);

      } else {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("FULL!!");
        lcd.setCursor(0, 1);
        //lcd.print(distance);
        lcd.print(percentLV);
        lcd.print(" %");
        //digitalWrite(trigmotor, LOW);
        digitalWrite (led, LOW);      // Turn off the led indicator
        delay(20);

        Serial.print("PercentLV: ");
        Serial.print(percentLV);
        Serial.println("%");
      }
      delay(1000);

    }

    }

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

body:
There doesn't appear to be anything wrong from a quick glance.  Have you got the right library for the LCD?

The chances are there is something wrong with your LCD.  So check your connections again.  Now create a new sketch that just prints hello world on the LCD, or better still use an example.  If that works, then the problem is an interaction between components.

So write a sketch that spins the servo back and forth while printing a message on the LCD.

Did that work, now add in the ultrasonic sensor and the code.

Now the other bits, and if that works, then you could look at what you have done differently, or just thank your lucky stars :)


message:
What if I detach AVR micro controller from the Arduino Board after uploading program?

What if I detach AVR microcontroller from the Arduino Board after uploading program? Does the microcontroller still have the program on it? Or the program will be deleted?

On the board where does Arduino store hex file?

I am very beginner in Embedded Programming. I am learning about microcontroller and Arduino. While learning about programming Arduino-Uno I got these question in my mind.

body:
The AVR µC got a flash memory that can store the code loaded in. That mean you can load the code with the arduino board, detach the avr and put it on another circuit. If the µC is powered well, it will behave just like the arduino.

Don't forget to set the /reset pin to high, if you do, the µC will be stuck to the 1st line of code ;)


message:
Using a potentiometer to control number of lit pixels on an NeoPixel strip

I'm working on controlling an [Adafruit NeoPixel strip][1] with an Arduino and a potentiometer. Specifically, I'm trying to use the potentiometer to control how many pixels are lit up on the strip. As I turn the potentiometer "up" (i.e., increasing the value), the number of lit-up pixels increases.

However, if I try to turn the potentiometer the other way and decrease the number of lit-up pixels, then the strip will stay at whatever the last value was.

I have a method below that's called during the 'void loop()' method that read in the potentiometer data:

    void readAndSendPotentiometerDataIfChanged(void) {
     //Read data from analog pin 2, and scale it
     int newPotentiometerValue = analogRead(A2) / 5.68;
      if (newPotentiometerValue != lastPotentiometerValue) {
          Serial.print("POT. value");
          Serial.print(newPotentiometerValue);
          lastPotentiometerValue = newPotentiometerValue;

          /* The value of "colorVal" is determined by a switch, and seems to be
             working properly */
          if (colorVal == "RED") {
            //If the value is 0, we want to clear the pixel values to white
            if (lastPotentiometerValue == 0) {
              clearPixels();
            } else {
              colorWipe(strip.Color(255, 0, 0)); // Red
            }
          } else if (colorVal == "BLUE") {
            if (lastPotentiometerValue == 0) {
              clearPixels();
            } else {
              colorWipe(strip.Color(0, 0, 255)); // Blue
            }
          }
       }
    }

The method below will clear out all 180 pixels on my strip to no color (clear).

    void clearPixels() {
       uint16_t clearColor = (127, 127, 127);
       strip.setPixelColor(180, clearColor);
       strip.show();
    }

Here's where the pixels on the strip get set...I'm sure the problem is in the for loop below, but I haven't been able to come up with a better way to set the pixels on the strip and then turn them on:

    void colorWipe(uint32_t c) {

      /* Use the value of 'lastPotentiometerValue' to determine how many pixels
       on the strip should be lit up */
      for(uint16_t i=0; i<lastPotentiometerValue; i++) {
        strip.setPixelColor(i, c);
        delay(0.5);
      }
       strip.show();
    }

Anyone have a pointer to how I could refactor my code so that the potentiometer works in both directions, and will light up or turn off the pixels on the strip as appropriate? Thank you!

**EDIT** Based on Ignacio's answer, I changed my `colorWipe` method to this:

    void colorWipe(uint32_t c) {

      for (uint16_t i = lastPotentiometerValue; lastPotentiometerValue<180; i++){
          uint16_t clearColor = (127, 127, 127);
          strip.setPixelColor(i, clearColor);
      }

      for(uint16_t i=0; i<lastPotentiometerValue; i++) {
        strip.setPixelColor(i, c);
        delay(0.5);
      }

       strip.show();
    }

However, now no strips are lit up.

**EDIT 2**

The condition was wrong; below is the code that works:

    void colorWipe(uint32_t c) {

      for(uint16_t i = lastPotentiometerValue; i<180; i++){
          uint16_t clearColor = (0, 0, 0);
          strip.setPixelColor(i, clearColor);
      }

      for(uint16_t i=0; i<lastPotentiometerValue; i++) {
        strip.setPixelColor(i, c);
        delay(0.5);
      }

       strip.show();
    }

  [1]: https://learn.adafruit.com/adafruit-neopixel-uberguide/neopixel-strips

body: You forgot to clear every *other* pixel in `colorWipe()`. Pixels that aren't sent a color retain their previous color.


message:
Press on pressure sensor once, turn on LED for 6 seconds

I am working on a project where I would like to press on a pressure sensor (0-1024) once and turn on the LED and turn off by itself after 6 seconds. I am quite new to arduino and I can't seem to understand how to code this with using a pressure sensor as a switch rather than an actual switch. Any ideas?

body:
Sensors which give a range of outputs need to have their outputs processed using a technique called [hysteresis][1].  That is, normally, the turn on threshold is higher then the turn off threshold.

For example, the thermostat in your home uses hysteresis when controlling your HVAC system.  Otherwise your thermostat would constantly be turning on and off your HVAC system likely causing an early failure.

[Here][2] is a stackexchange Arduino question about hysteresis.

  [1]: https://en.wikipedia.org/wiki/Hysteresis
  [2]: https://arduino.stackexchange.com/questions/9115/how-to-add-hysteresis-to-threshold-values


body:
If you're having a problem implementing the system in software, there is a hardware approach to do it. The phenomenon is called monostable multivibrator. Monostable mode retains its output for a certain time interval before coming back to previous state. You can use a simple [RC circuit configuration][1] to implement this functionality along with Arduino setup. Just interface FSR in voltage divider format, read the voltage and switch another GPIO interfaced with RC circuit configuration.

  [1]: http://www.electronics-tutorials.ws/waveforms/monostable.html


message:
ATtiny85 LM75 I2C

I would like to read temperature from a [LM75][1] using the **ATtiny85** running [a core by SpenceKonde][2] and utilizing the [TinyWireM][3] library.

My Logic Analyzer does not pick up any I2C communication, when I connect it to an Arduino Nano, it works fine. On the Nano, there is no need for **TinyWireM** so that's a big difference.

Therefore I conclude that the ATtiny85 is not speaking the right I2C slang to the device.

I also use SoftwareSerial and this works fine. It is visible on the Logic Analyzer.

[![enter image description here][4]][4]

The [LM75 library][5] is not made for ATtiny or TinyWireM, I replace the `Wire` references in-place by `TinyWireM` reference.

Should it be possible to 'just' replace Wire by TineWireM in the library and could I expect some meaningful data this way?

**[updated code]**

    #include <Arduino.h>
    #include <TinyWireM.h>
    #include <LM75.h>
    #include <SoftwareSerial.h>

    #define SOFTWARE_SERIAL_TX_PIN 3
    #define SOFTWARE_SERIAL_RX_PIN -1

    LM75 sensor;
    SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);

    void setup() {
      TinyWireM.begin();
      mySerial.begin(2400);
      mySerial.print("Starting..");
    }

    void loop() {
    delay(1000);
    mySerial.println("SO");
    mySerial.println(sensor.temp());
    delay(1000);
    }

  [1]: https://datasheets.maximintegrated.com/en/ds/LM75.pdf
  [2]: https://github.com/SpenceKonde/ATTinyCore
  [3]: https://github.com/adafruit/TinyWireM
  [4]: https://i.stack.imgur.com/7sqUj.png
  [5]: https://github.com/thefekete/LM75

body: The current ATtiny core includes a Wire library for the USI hardware used in the Tinys. This way you don't need to modify the LM75 library which is error prone.


body:
This is an old post I know but hopefully this information is helpful to someone. I modified the lm75 library by replacing all instances of Wire with TinyWire and as above no go, but turns out a 10k pull up on SCL / SDA is a necessity for the attiny 85. For whatever reason i2c works fine on an arduino UNO without pull ups but not on an attiny 85. So in short, add pull up resistors and it works. Bonus potato grade picture of attiny, LM75 and display module showing temperature.

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

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


message:
How to change colors and theme settings in 'Windows Store app' version of Arduino IDE?

In the standard Windows (Win32) version of the Arduino IDE, theme settings like syntax coloring can be modified in C:\Program Files (x86)\Arduino\lib\theme\theme.txt.

For the *Windows Store app* version of the IDE the theme files are stored in protected app storage space.

Is there a simple/safe way to change theme settings for the *Windows Store app* version of the IDE without messing up security settings and inadvertently lowering Windows security?

*(It would be easier and better if theme settings could be moved to the ArduinoData user folder where preferences.txt is stored.)*

body:
There is a way, but not necessarily simple. You basically need to replace the current theme files with the new ones.

 1. Rename `{Arduino IDE installation folder}/lib/theme` to `{Arduino IDE installation folder}/lib/theme.bak`
 2. Download https://github.com/jeffThompson/DarkArduinoTheme/archive/master.zip
 3. Copy the theme folder from the downloaded file to {Arduino IDE installation folder}/lib
 4. Restart the Arduino IDE if it's running.


body:
I think rrz0's answer skipped the part of the question:
"For the Windows Store app version of the IDE the theme files are stored in protected app storage space."

The only way is to take control of the windows app folder but I believe this is risky and M$ suggests that this can brick your pc (take that with a grain of salt).

There is an offline windows installer and zip link on the downloads page which I used to replace the windows store version. I see no advantage to the store version.


body:
I found the solution, based on a new functionality for themes that I wasn't aware of.

You need to create a themes folder in the folder where your projects are (the one that appears in the preferences section) and put inside it the theme in a zip file. After restarting it will appear as a new theme in the combobox themes.