body:
I am currently working on an Arduino project that needs alot of on/off toggles. Because my Arduino Mega does not have enough pins I connected 5 multiplexers to it ([the MuxShield 2's](http://mayhewlabs.com/products/mux-shield-2)). The problem is that only one of them functions correctly at any given moment.
Each multiplexer has 3 rows and they each have their `_shiftReg1`, `_shiftReg2` and `_shiftReg3` array in the library. I think there's something up with this, when I loop over the rows of each multiplexers only the first first, second and third row of any given multiplexer work as expected. The outputs on each row light up one by one as they should. But when I loop over a row number which is already looped over all the outputs turn on at once. I have no idea why this is happening and really need some help figuring this out.

This is my main project file, I commented which loops work and which ones don't:

    #include <Arduino.h>

    #include <MuxShield.h>
    #include <ToggleMux.h>

    // Initialize the Mux Shields
    MuxShield muxShield1 = MuxShield(31, 29, 27, 25, 23, 10, 11, 12, A0, A1, A2);
    MuxShield muxShield2 = MuxShield(41, 39, 37, 35, 33, 10, 11, 12, A3, A4, A5);
    MuxShield muxShield3 = MuxShield(2, 4, 6, 7, 8, 10, 11, 12, A6, A7, A8);
    MuxShield muxShield4 = MuxShield(51, 49, 47, 45, 43, 10, 11, 12, A9, A10, A11);
    MuxShield muxShield5 = MuxShield(22, 24, 26, 28, 30, 10, 11, 12, A12, A13, A14);
    // ToggleMux
    ToggleMux t1 = ToggleMux(muxShield1, 1, 0, muxShield3, 3, 0);
    ToggleMux t2 = ToggleMux(muxShield1, 1, 1, muxShield3, 3, 1);
    ToggleMux t3 = ToggleMux(muxShield1, 1, 2, muxShield3, 3, 2);
    ToggleMux t4 = ToggleMux(muxShield1, 1, 3, muxShield3, 3, 3);
    ...

    void setup()
    {
        muxShield1.setMode(1, DIGITAL_IN);
        muxShield1.setMode(2, DIGITAL_IN);
        muxShield1.setMode(3, DIGITAL_IN);

        muxShield2.setMode(1, DIGITAL_IN);
        muxShield2.setMode(2, DIGITAL_IN);
        muxShield2.setMode(3, DIGITAL_IN);

        muxShield3.setMode(1, DIGITAL_IN);
        muxShield3.setMode(2, ANALOG_IN);
        muxShield3.setMode(3, DIGITAL_OUT);

        muxShield4.setMode(1, DIGITAL_OUT);
        muxShield4.setMode(2, DIGITAL_OUT);
        muxShield4.setMode(3, DIGITAL_OUT);

        muxShield5.setMode(1, DIGITAL_OUT);
        muxShield5.setMode(2, DIGITAL_OUT);
        muxShield5.setMode(3, DIGITAL_OUT);
    }

    boolean hilo = true;

    void loop()
    {
        for (int i = 0; i < 16; i++) {     // works as expected
          muxShield3.digitalWriteMS(3, i, hilo ? 1 : 0);
          delay(10);
        }

        for (int i = 0; i < 16; i++) {     // turns them all on at once because row 3 has already been looped over
          muxShield4.digitalWriteMS(3, i, hilo ? 1 : 0);
          delay(10);
        }

        for (int i = 0; i < 16; i++) {     // works as expected
          muxShield4.digitalWriteMS(1, i, hilo ? 1 : 0);
          delay(10);
        }

        for (int i = 0; i < 16; i++) {     // works as expected
          muxShield4.digitalWriteMS(2, i, hilo ? 1 : 0);
          delay(10);
        }

        // for (int i = 0; i < 16; i++) {
        //   muxShield4.digitalWriteMS(3, i, hilo ? 1 : 0);
        //   delay(10);
        // }

        for (int i = 0; i < 16; i++) {    // turns them all on at once because row 1 has already been looped over
           muxShield5.digitalWriteMS(1, i, hilo ? 1 : 0);
           delay(10);
         }

         for (int i = 0; i < 16; i++) {    // turns them all on at once because row 2 has already been looped over
           muxShield5.digitalWriteMS(2, i, hilo ? 1 : 0);
           delay(10);
         }

         for (int i = 0; i < 16; i++) {    // turns them all on at once because row 3 has already been looped over
           muxShield5.digitalWriteMS(3, i, hilo ? 1 : 0);
           delay(10);
         }
         hilo = !hilo;

      // t1.listen();
      // t2.listen();
      // t3.listen();
      // t4.listen();
        ...
    }

This is my toggle library:

    #include "Arduino.h"
    #include "ToggleMux.h"
    #include "MuxShield.h"

    ToggleMux::ToggleMux(MuxShield muxShieldIn, int inRow, int inBit, MuxShield muxShieldOut, int outRow, int outBit) :
    _muxShieldIn(muxShieldIn),
    _muxShieldOut(muxShieldOut),
    _inRow(inRow),
    _inBit(inBit),
    _outRow(outRow),
    _outBit(outBit)
    {
        _state = 0;
        _previous = 0;
        _reading;

        _time = 0;
        _debounce = 100;
    }

    void ToggleMux::listen() {
        _reading = _muxShieldIn.digitalReadMS(_inRow, _inBit);
        _state = _muxShieldOut.digitalReadMS(_outRow, _outBit);

        if (_reading == 1 && _previous == 0 && millis() - _time > _debounce) {
            if (_state == 1) {
                _state = 0;
            } else {
                _state = 1;
            }

            _muxShieldOut.digitalWriteMS(_outRow, _outBit, _state);
            _time = millis();
        }

        _previous = _reading;
    }

    void ToggleMux::on() {
      _state = 1;
      _muxShieldOut.digitalWriteMS(_outRow, _outBit, 1);
    }

    void ToggleMux::off() {
      _state = 0;
      _muxShieldOut.digitalWriteMS(_outRow, _outBit, 0);
    }

And this is the MuxShield 2 library:

    /*
     MuxShield.cpp - Library for using Mayhew Labs' Mux Shield.
     Created by Mark Mayhew, December 29, 2012.
     Released into the public domain.
     */

    #include "Arduino.h"
    #include "MuxShield.h"
    #include "BitBool.h"

    int _shiftReg1[16] = {0};
    int _shiftReg2[16] = {0};
    int _shiftReg3[16] = {0};

    MuxShield::MuxShield(int S0, int S1, int S2, int S3, int OUTMD,int IOS1, int IOS2, int IOS3, int IO1, int IO2, int IO3)
    {
        _S0 = S0;
        _S1 = S1;
        _S2 = S2;
        _S3 = S3;
        _OUTMD = OUTMD;
        _IOS1 = IOS1;
        _IOS2 = IOS2;
        _IOS3 = IOS3;
        _IO1 = IO1;
        _IO2 = IO2;
        _IO3 = IO3;

        pinMode(_S0,OUTPUT);
        pinMode(_S1,OUTPUT);
        pinMode(_S2,OUTPUT);
        pinMode(_S3,OUTPUT);
        pinMode(_OUTMD,OUTPUT);
        digitalWrite(_OUTMD,LOW);
        pinMode(_IOS1,OUTPUT);
        pinMode(_IOS2,OUTPUT);
        pinMode(_IOS3,OUTPUT);
    }

    MuxShield::MuxShield()
    {
        _S0 = 2;
        _S1 = 4;
        _S2 = 6;
        _S3 = 7;
        _OUTMD = 8;
        _IOS1 = 10;
        _IOS2 = 11;
        _IOS3 = 12;
        _IO1 = A0;
        _IO2 = A1;
        _IO3 = A2;

        pinMode(_S0,OUTPUT);
        pinMode(_S1,OUTPUT);
        pinMode(_S2,OUTPUT);
        pinMode(_S3,OUTPUT);
        pinMode(_OUTMD,OUTPUT);
        digitalWrite(_OUTMD,LOW);
        pinMode(_IOS1,OUTPUT);
        pinMode(_IOS2,OUTPUT);
        pinMode(_IOS3,OUTPUT);
    }

    void MuxShield::setMode(int mux, int mode)
    {
        switch (mux) {
            case 1:
                switch (mode) {
                    case DIGITAL_IN:
                        pinMode(_IO1,INPUT);
                        digitalWrite(_IOS1,LOW);
                        break;
                    case DIGITAL_IN_PULLUP:
                        pinMode(_IO1,INPUT_PULLUP);
                        digitalWrite(_IOS1,LOW);
                        break;
                    case DIGITAL_OUT:
                        pinMode(_IO1,OUTPUT);
                        digitalWrite(_IOS1,HIGH);
                        break;
                    case ANALOG_IN:
                        digitalWrite(_IOS1,LOW);
                        break;
                    default:
                        break;
                }
                break;
            case 2:
                switch (mode) {
                    case DIGITAL_IN:
                        pinMode(_IO2,INPUT);
                        digitalWrite(_IOS2,LOW);
                        break;
                    case DIGITAL_IN_PULLUP:
                        pinMode(_IO2,INPUT_PULLUP);
                        digitalWrite(_IOS2,LOW);
                        break;
                    case DIGITAL_OUT:
                        pinMode(_IO2,OUTPUT);
                        digitalWrite(_IOS2,HIGH);
                        break;
                    case ANALOG_IN:
                        digitalWrite(_IOS2,LOW);
                        break;
                    default:
                        break;
                }
                break;
            case 3:
                switch (mode) {
                    case DIGITAL_IN:
                        pinMode(_IO3,INPUT);
                        digitalWrite(_IOS3,LOW);
                        break;
                    case DIGITAL_IN_PULLUP:
                        pinMode(_IO3,INPUT_PULLUP);
                        digitalWrite(_IOS3,LOW);
                        break;
                    case DIGITAL_OUT:
                        pinMode(_IO3,OUTPUT);
                        digitalWrite(_IOS3,HIGH);
                        break;
                    case ANALOG_IN:
                        digitalWrite(_IOS3,LOW);
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }

    }

    void MuxShield::digitalWriteMS(int mux, int chan, int val)
    {
        int i;

        digitalWrite(_S3,LOW);                              //S3 here is LCLK
        digitalWrite(_OUTMD,HIGH);                          //set to output mode
        switch (mux) {
            case 1:
                _shiftReg1[chan] = val;                     //store value until updated again

                for (i=15; i>=0; i--) {
                    digitalWrite(_S0,LOW);                  //S0 here is i/o1 _sclk
                    digitalWrite(_IO1,_shiftReg1[i]);       //put value
                    digitalWrite(_S0,HIGH);                 //lactch in value
                }
                break;
            case 2:
                _shiftReg2[chan] = val;                     //store value until updated again

                for (i=15; i>=0; i--) {
                    digitalWrite(_S1,LOW);                  //S1 here is i/o2 _sclk
                    digitalWrite(_IO2,_shiftReg2[i]);       //put value
                    digitalWrite(_S1,HIGH);                 //lactch in value
                }
                break;
            case 3:
                _shiftReg3[chan] = val;                     //store value until updated again

                for (i=15; i>=0; i--) {
                    digitalWrite(_S2,LOW);                  //S2 here is i/o3 _sclk
                    digitalWrite(_IO3,_shiftReg3[i]);       //put value
                    digitalWrite(_S2,HIGH);                 //lactch in value
                }
                break;
            default:
                break;
        }
        digitalWrite(_S3,HIGH);                     //latch in ALL values
        digitalWrite(_OUTMD,LOW);                   //Exit output mode

    }

    int MuxShield::digitalReadMS(int mux, int chan)
    {
        digitalWrite(_OUTMD,LOW);   //Set outmode off (i.e. set as input mode)
        int val;
        switch (mux) {
            case 1:
                digitalWrite(_S0, (chan&1));
                digitalWrite(_S1, (chan&3)>>1);
                digitalWrite(_S2, (chan&7)>>2);
                digitalWrite(_S3, (chan&15)>>3);

                val = digitalRead(_IO1);
                break;
            case 2:
                digitalWrite(_S0, (chan&1));
                digitalWrite(_S1, (chan&3)>>1);
                digitalWrite(_S2, (chan&7)>>2);
                digitalWrite(_S3, (chan&15)>>3);

                val = digitalRead(_IO2);
                break;
            case 3:
                digitalWrite(_S0, (chan&1));
                digitalWrite(_S1, (chan&3)>>1);
                digitalWrite(_S2, (chan&7)>>2);
                digitalWrite(_S3, (chan&15)>>3);

                val = digitalRead(_IO3);
                break;
            default:
                break;
        }
        return val;
    }

    int MuxShield::analogReadMS(int mux, int chan)
    {
        digitalWrite(_OUTMD,LOW);
        int val;

        digitalWrite(_S0, (chan&1));
        digitalWrite(_S1, (chan&3)>>1);
        digitalWrite(_S2, (chan&7)>>2);
        digitalWrite(_S3, (chan&15)>>3);

        switch (mux) {
            case 1:
                val = analogRead(_IO1);
                break;
            case 2:
                val = analogRead(_IO2);
                break;
            case 3:
                val = analogRead(_IO3);
                break;
            default:
                break;
        }
        return val;
    }

title: Arduino toggles on multiplexer not working

Answers: 0


body:
I have developed a code to read an image stored on my SD Card and display it on a TFT. I can read the image from the SD Card successfully but I cannot draw it on the TFT. I dunno where is the bug.
Could you please guys help me figure it out?

Board: Arduino DUE
<!-- language-all: lang-cpp -->

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

    #include "ascii_data.h"

    #define SERIAL_PORT  9600

    #define PIN_SCE   10
    #define PIN_RESET   6
    #define PIN_DC    5
    // #define PIN_SDIN
    // #define PIN_SCLK
    #define PIN_LED   2

    #define LCD_COMMAND  LOW
    #define LCD_DATA   HIGH
    #define CHAR_WIDTH   6
    #define CHAR_HEIGHT  8
    #define LCD_WIDTH   84
    #define LCD_HEIGHT   48
    #define CHARS_PER_ROW  (LCD_WIDTH / CHAR_WIDTH)
    #define CHARS_PER_COL  (LCD_HEIGHT / CHAR_HEIGHT)

    #define PIN_SCSD   4

    void draw();
    void reset();
    void cls();
    void lcdMode(int mode);
    void lcdInitialize();
    void printString(int y, const char *value);
    void printString(int x, int y, const char *value);
    int printChar(int x, int y, char value);
    void setPixel(int x, int y, int value);
    void lcdWrite(int value);

    byte data[84][6] = {0};

    String input = "";
    bool complete = false;

    // ----------------------------------------------------------------------------

    void setup()
    {
      // Enable I/O stream
      Serial.begin(SERIAL_PORT);
      Serial.println("Serial Init..");

      // pin modes
      pinMode(PIN_SCE, OUTPUT);
      pinMode(PIN_RESET, OUTPUT);
      pinMode(PIN_DC, OUTPUT);
      pinMode(PIN_LED, OUTPUT);
      pinMode(PIN_SCSD, OUTPUT);

      // SD stuff
      SD.begin(PIN_SCSD);

      // display stuff
      reset();

      SPI.begin(PIN_SCE);
      SPI.setClockDivider(PIN_SCE, SPI_CLOCK_DIV16);

      lcdInitialize();

      input.reserve(200);

      printChar(0, 0, 'a');
    }

    void loop()
    {
      while (Serial.available() > 0) {
        char ch = (char)Serial.read();
        //Serial.print(ch);
        if (isprint(ch) && ch != '\n') {
          input += ch;
          //Serial.println(input);
        }
        else {
          complete = true;
        }
      }

      if (complete) {
        Serial.print("Command: ");
        Serial.println(input);

        //Serial.println(input.startsWith("exists(") && input.endsWith(")"));

        if (input.startsWith("exists(") && input.endsWith(")")) {
          String file = input.substring(7, input.length() - 1);

          Serial.print("File: ");
          Serial.println(file);

          File f = SD.open(file);
          if (f) {
            Serial.println("File does exists");
            f.close();
          } else {
            Serial.println("File does not exist");
          }

        } else if (input.startsWith("print(") && input.endsWith(".img)")) {
          String file = input.substring(6, input.length() - 1);
          File f = SD.open(file);
          if (f) {
            cls();

            Serial.print("Printing image: ");
            // Dimensionen auslesen
            int width = 0;
            int height = 0;

            char ch = '\0';
            String dim = "";

            while (f.available()) {
              ch = (char)f.read();

              if (ch != ',' && ch != '\n')
                dim += ch;
              else {
                if (width == 0) {
                  width = dim.toInt();
                  dim = "";
                } else if (height == 0) {
                  height = dim.toInt();
                }

                if (ch == '\n') {
                  break;
                }
              }
            }

            Serial.print("Dimensions of image: ");
            Serial.print(width);
            Serial.print(" x ");
            Serial.println(height);

            for (int i = 0; i < height; ++i) {
              for (int x = 0; x < width; ++x){
                char ch = '\0';
                while (ch != '\n') {
                  ch = f.read();
                  if (ch == ','){
                    continue;
                  }else (ch == '0' || ch == '1') {
                    int pix = ch - '0';
                    setPixel(x, i, pix);
                  }
                }
              }
            }
          }

        } else if (input.startsWith("print(") && input.endsWith(")")) {
          String file = input.substring(6, input.length() - 1);
          File f = SD.open(file);
          if (f) {
            cls();

            int x = 0;
            int y = 0;
            Serial.print("Printing: ");
            while (f.available()) {
              char ch = (char)f.read();
              Serial.print(ch);
              if (-1 == printChar(x, y, ch));

              draw();

              x = (x + 6) % 84;
              if (x == 0) {
                y = (y + 8) % 48;
              }
            }
            Serial.println();

          } else {
            Serial.println("Error: File does not exist");
          }

        } else {
          Serial.println("Unknown command");
        }

        complete = false;
        input = "";
      }

      draw();

      delay(10);

    }

    // ----------------------------------------------------------------------------

    void draw()
    {
      lcdMode(LCD_DATA);

      for (int b = 0; b < 6; ++b) {
        for (int x = 0; x < 84; ++x) {
          lcdWrite(data[x][b]);
        }
      }
    }

    void reset()
    {
      digitalWrite(PIN_RESET, LOW);
      delay(500);
      digitalWrite(PIN_RESET, HIGH);
    }

    void cls()
    {
      for (int x = 0; x < LCD_WIDTH; ++x) {
        for (int y = 0; y < LCD_HEIGHT; ++y) {
          setPixel(x, y, 0);
        }
      }
    }

    void lcdMode(int mode)
    {
      digitalWrite(PIN_DC, mode);
    }

    void lcdInitialize()
    {
      lcdMode(LCD_COMMAND);

      // FUNCTION SET (extended instruction set)
      lcdWrite(0x21);

      // SET BIAS
      lcdWrite(0x14);

      // SET TEMP COEFFICIENT
      lcdWrite(0x04);

      // SET CONTRAST
      lcdWrite(0xBF);

      // FUNCTION SET (normal instruction set)
      lcdWrite(0x20);

      // SET DISPLAY MODE (normal)
      lcdWrite(0x0C);

      // reset display
      lcdWrite(0x40);
      lcdWrite(0x80);
    }

    void printString(int y, const char *value)
    {
      printString((84 - strlen(value) * 6) / 2, y, value);
    }

    void printString(int x, int y, const char *value)
    {
      do
      {
        printChar(x, y, *value);
        x += 6;
      } while (*++value != '\0');
    }

    int printChar(int x, int y, char value)
    {
      lcdMode(LCD_DATA);

      if (value < ' ') {
        return -1;
      }

      for (int dx = 0; dx < 6; ++dx) {
        for (int dy = 0; dy < 8; ++dy) {
          setPixel(x + dx, y + dy, !!(font[value - ' '][dx] & (1 << dy)));
        }
      }

      return 0;
    }

    void setPixel(int x, int y, int value)
    {
      if (x >= 0 && x < 84 && y >= 0 && y < 48) {
        if (value) {
          data[x][y / 8] |= (1 << (y % 8));
        } else {
          data[x][y / 8] &= ~(1 << (y % 8));
        }
      }
    }

    void lcdWrite(int value)
    {
      digitalWrite(PIN_SCE, LOW);
      SPI.transfer(PIN_SCE, value, SPI_CONTINUE);
      digitalWrite(PIN_SCE, HIGH);
    }

title: Bug read an image from SD card and draw it on TFT

Answers: 0


body:
I just made an addressable RGB LED strip controller but im concerned about if I'm going to break the thing.

I know it sounds vague so let me elaborate: there is an external power supply connected to my 5V pin and the LED strips positive so it powers both the strip and Arduino, but I also have my Arduino connected to my PC at all times. So I'm concerned about IF my power supply is for some reason not connected the Arduino will supply power on its own.

Is there a way to prevent 5V pin from outputting 5V, so it only accepts 5V

EDIT:
There are cases when the USB isn't connected so I need the 5V to be connected at all times, if its still vague then is there a way to only use data on USB and disregard the power?

title: Prevent 5V output on Arduino Nano 5V pin

Answers: 1

body:
A simple diode is all you need. The USB power already goes through a diode, so another diode the same will create a "highest voltage wins" situation.

That is, if the voltage provided by the USB port is higher than the voltage you provide on the +5V pin (after the diode's forward voltage drop) then the USB port will power the nano. If the voltage on the +5V pin is higher (after the diode's voltage drop) than the USB then the voltage on the +5V pin will power the nano.

No power will flow out of the 5V pin to your LED strip because the diode is in the way.

Connect the 5V external power to the *anode* of the diode, and the 5V pin of the Arduino to the *cathode* of the diode. The cathode is generally the end of the diode with the stripe.  Make sure the diode can pass enough current to power the Arduino when the USB is un-powered. The 1N4001 is a popular choice and very easy to get hold of.

That choice of diode also has a higher forward voltage drop than the on-board USB diode (0.7V as opposed to about 0.4V), so the USB will generally be chosen by default when connected and powered up, which is as it should be for a bus-powered device.


body:
I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB [Strips][1]. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

- one cable on 12V
- one cable on G
- one cable or R
- one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

  [1]: https://www.amazon.co.uk/gp/product/B00XBHW0YS/ref=s9_simh_gw_g201_i2_r?ie=UTF8&fpl=fresh&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=&pf_rd_r=565KNQFHRJ455NFM59T2&pf_rd_t=36701&pf_rd_p=026d359a-cb34-4790-9249-ec9f152ee8e2&pf_rd_i=desktop

title: Connect an Arduino directly to RGB LED strip

Answers: 5

body:
No. Two reasons:

1. The Arduino can only supply about 40 mA per pin max. Your LEDs will require about 1000 mA or so per channel (based on the 3 A PSU supplied with the unit).
2. The LEDs are individually addressed and codes have to be transmitted to them. This requires code to be written for the micro and an interface to the data line.

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

_Figure 1. The IR controller._

The IR controller supplied with the kit interfaces the power and provides the data signal to the strip.

The simplest way to control from your micro is to fit it with an IR (infra-red) LED and transmit the codes to the IR controller. This method also makes it almost impossible for you to damage your micro or the LED strip as the only connection between them will be by infra-red light.

Someone has probably figured this out already and you may find the complete code for an Arduino in a web search.

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

body:
Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.

You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).

Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).

As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.

body:
  https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd_lpo_328_bs_t_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1

You can use the logic level ports to drive Logic level power MoSFET switches or use a RS85 IC to communicate to a DMX-512 interface special effects driver to RGB.

Other options include
Use 5A PWM 3channel dimmer purchased on line with 12V- 14.5Vmax PSU >40W per 5m reel string .

e.g. Laptop universal 65W charger ($30) with 14V -16V setting. and long AWG18 wire with 1-2V drop

(comments)

- You start by improving your question with details on what you want to do with the interface.
- if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard

body: You can use a couple of relays on the arduino outputs, and control it from there.

body:
No. there is no way to connect those directly.

You can use Solid state relays (SSR) for this.
I did it before and was able to make different colors.

Connect an external 12v directly 12V pin in srips.

Use SSR to connect from GPIO to LED R G and B pins


body:
I have tried fading the RGB Led with different colour format and sequence.
Working of Code :-

 - When value of number is 1, the Red LED fades gradually and glow up with the delay interval of 10ms with fade amount 5.
 - When value of number is 2, the Green LED works as above.
 - The change of state from Red to green takes 4 seconds.

Blue Led Code can also be added to this and various other colour combinations can be made, which will complex the code and add up difficulty is debugging and finding errors because every combination should have different name for fading so that it doesn't conflict with other combinations.

Here is my code. However, I need some suggestions regarding quality of my code. Is it the efficient way to do code. How can I improve the code. Any constructive suggestions would be of great help.

    int RED_LED = 12;           // the PWM pin the LED is attached to
    int BLUE_LED = 14;
    int GREEN_LED = 15;

    int RedLedBrightness = 0;    // how bright the LED is
    int GreenLedBrightness = 0;    // how bright the LED is

    int RedFadeAmount = 5;
    int GreenFadeAmount = 5;

    unsigned long previousMillis = 0;
    const long interval = 10;

    unsigned long previousMillis2 = 0;
    const long interval2 = 4000;

    int j = 0;

    void setup()
    {
      pinMode(RED_LED, OUTPUT);
      pinMode(BLUE_LED, OUTPUT);
      pinMode(GREEN_LED, OUTPUT);

      Serial.begin(115200)
    }

    void loop()
    {
        if (millis() - previousMillis2 >= interval2)
        {
         previousMillis2 = millis();

        j += 1;
        if (j > 2)
        {
            j = 1;
        }
        Serial.print("\n");
        Serial.println(j);
       }
        SpecialFunction(j);
    }

    void SpecialFunction(int Number)
    {
      if (millis() - previousMillis >= interval)
      {
        previousMillis = millis();

        if (Number == 1)
        {
          RedGradualChange();
        }

        else if (Number == 2)
        {
          GreenGradualChange();
        }
      }
    }

    void RedGradualChange(void)
    {
      analogWrite(GREEN_LED, 0);

      GreenLedBrightness = 0;    // how bright the LED
      GreenFadeAmount = 5;

      analogWrite(RED_LED, RedLedBrightness);
      RedLedBrightness = RedLedBrightness + RedFadeAmount;

      if (RedLedBrightness <= 0 || RedLedBrightness >= 1020)
      {
        RedFadeAmount = -RedFadeAmount;
      }
    }

    void GreenGradualChange(void)
    {
      analogWrite(RED_LED, 0);

      RedLedBrightness = 0;
      RedFadeAmount = 5;

      analogWrite(GREEN_LED, GreenLedBrightness);
      GreenLedBrightness = GreenLedBrightness + GreenFadeAmount;

      if (GreenLedBrightness <= 0 || GreenLedBrightness >= 1020)
      {
        GreenFadeAmount = -GreenFadeAmount;
      }
    }

title: Code Optimisation

Answers: 1

body:
Without deciphering what all those functions are supposed to do, I can see a few fundamental flaws and inefficiencies:

1. Don't use string - especially if you're only then using it to convert into a char array. Just use the char array.
2. You're storing a number in a char array then comparing it to string constants. What is wrong with dealing with just numbers in the first place...?
3. This bit is wrong: `if (incomingByte = '#')` - you have an assignment (`=`) instead of a comparison (`==`) so it will always be true.
4. If you fix point 3 the rest of the code won't work, since your string will now always have `#` at the end (`3#` for instance) and the comparison against `3` (for example) will fail.

You should learn more about how to input values through serial:

* https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

----

For your fading code there is a lot of redundancy in there. Personally I would use a *bitfield* indicating which LEDs are to fade and which aren't.

Basically you have a single value and OR together bits within it to indicate the enabled LEDs.  For instance, assign the value `1` to red, `2` to green and `4` to blue. These correspond to `0b001`, `0b010` and `0b100` respectively.

When the state is changed, either by your loop or by an external serial signal, you reset all three colour brightnesses to 0 (to keep them synchronised) and set the right bits in the bitfield for the colours you want fading. For instance, for red you set the bitfield to 1. For cyan you set it to 6 (0b110).  Then in your processing loop you just fade the colours that are enabled, and write all three values (the colour that isn't enabled will already be 0).  This also has a side-effect that you now already have numbers assigned to the colours:

    0 = 0b000 = All off
    1 = 0b001 = Red
    2 = 0b010 = Green
    3 = 0b011 = Yellow
    4 = 0b100 = Blue
    5 = 0b101 = Magenta
    6 = 0b110 = Cyan
    7 = 0b111 = White

In fact, since all the colours are fading together, you don't even need separate values for each colour - just one global brightness value.

Some code (untested) for you:

    #define RED   0b001
    #define GREEN 0b010
    #define BLUE  0b100

    int brightness = 0;
    uint8_t enabled = 1;
    int fadeAmount = 5;

    const uint8_t RED_LED = 12;
    const uint8_t BLUE_LED = 14;
    const uint8_t GREEN_LED = 15;

    unsigned long previousMillis = 0;
    const long interval = 10;

    unsigned long previousMillis2 = 0;
    const long interval2 = 4000;

    void setup() {
      pinMode(RED_LED, OUTPUT);
      pinMode(BLUE_LED, OUTPUT);
      pinMode(GREEN_LED, OUTPUT);

      Serial.begin(115200);
    }

    void loop()
    {
        if (millis() - previousMillis2 >= interval2) {
            previousMillis2 = millis();
            enabled ++;
            if (enabled >= 8) enabled = 1;
            Serial.println(enabled);
        }

        if (millis() - previousMillis >= interval) {
            previousMillis = millis();
            if (enabled & RED) {
                analogWrite(RED_LED, brightness);
            } else {
                analogWrite(RED_LED, 0);
            }
            if (enabled & GREEN) {
                analogWrite(GREEN_LED, brightness);
            } else {
                analogWrite(GREEN_LED, 0);
            }
            if (enabled & BLUE) {
                analogWrite(BLUE_LED, brightness);
            } else {
                analogWrite(BLUE_LED, 0);
            }
            brightness += fadeAmount;
            if (brightness > 1023) {
                brightness = 1023;
                fadeAmount = -fadeAmount;
            } else if (brightness < 0) {
                brightness = 0;
                fadeAmount = -fadeAmount;
            }
        }
    }


body:
I recently started using the [ESP8266 12E][1] <sup>(Amazon link)</sup> and hooked the board up to the Arduino IDE.

When trying to run any of the example sketches, all sketches compile and upload correctly. The blink sketch correctly causes the LED to blink, however, in the serial monitor a varying and large quantity of junk characters appear:

[![screenshot][2]][2]

The first thing I investigated was of course the baud rate. Online, documentation for the ESP8266 indicate 115200 as the correct baud rate, but on the bottom of the device, the baud rate is listed as 9600.

The junk characters, of course, appear whether the baud rate is 9600 or 115200. Using trial-and-error, I tried each other option. I've also tried several USB to micro-USB (c) cables. They're the same ones I use to charge my phone - is that the issue?

Am I missing something simple here? I searched each of the other Stack Exchange questions about garbage serial monitor values and they all seemed to indicate that the baud rate was the culprit, or that the CL / NR values needed to be changed. Experimentation with these did not result in removing the characters.

 [1]: https://www.amazon.com/gp/product/B010O1G1ES/ref=ask_ql_qh_dp_hza
 [2]: https://i.stack.imgur.com/HYlPl.png

title: ESP8266 12e Arduino IDE outputs garbage values on serial monitor

Answers: 2

body:
The baud rate you specify in your program and the baud rate in the serial monitor *must* match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.

For example:

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

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.

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

body:
I had what I think is the same problem you did.  I posted my solution to it here:

[Link to my solution][1]

It seems that the ESP can upload code at 115200, but it can't talk to the serial monitor at that baud rate.  The solution is to programatically change the baud rate within your sketch.  The change in baud rate doesn't 'stick'.  You have to include it in your sketch so it is set every time the sketch is run.

Hope that helps.

  [1]: https://arduino.stackexchange.com/questions/47832/serial-monitor-not-properly-interpreting-data-from-my-nodemcu-v3/47843#47843


body:
I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.

I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.

This is the code I have until now.

    int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
    int fsrReading;     // the analog reading from the FSR resistor divider
    void setup(void) {
      // We'll send debugging information via the Serial monitor
      Serial.begin(9600);
    }

    void loop(void) {
      fsrReading = analogRead(fsrPin);

      Serial.print("Analog reading = ");
      Serial.println(fsrReading);     // the raw analog reading

      delay(100);
    }

title: Getting the highest value from analog reading?

Answers: 1

body:
You don't want to delay ever. Instead you want to change your thinking to "X miliseconds have passed, time to print and reset":

    int maxval = 0;
    uint32_t lastSample = 0;

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

    void loop() {
        if (millis() - lastSample > 100) { // Every 100ms:
            lastSample = millis();
            Serial.println(maxVal);
            maxVal = 0;
        }
        int reading = analogRead(0);
        if (reading > maxVal) {
            maxVal = reading;
        }
    }

Every 100ms it will print the maximum analog value read during the past 100ms.

You can replace the 100ms with any other value you choose, or even with a check to see if a button has been pressed, in which case you get the maximum reading since the last time the button was pressed:

    // global
    bool lastButtonValue = HIGH;

    // in loop()
    if (digitalRead(3) != lastButtonValue) {
        lastButtonValue = digitalRead(3);
        if (lastButtonValue == LOW) {
            // ... do the print and reset
        }
    }


body:
I'm using the Teensy 2.0 (atmega32u4) and decided to switch from Arduino IDE with Wiring to pure C. I think it's much more useful to master programming microcontrollers on that level. Wiring seems to be quite limited at some point.

It was really easy to use some basic libraries such as _avr/io_, or _util/delay_ and write simple programs like "arduino hello world".

My problem comes with more complex tasks such as acting as usb mouse. On http://pjrc.com are references just to use with arduino ide/wiring. I couldn't find anything useful on google. Is there any good reference for pure C programming tennsy/arduino and/or using libraries such as "usb_mouse.h" (from pjrc.com) with pure C?

----------

**EDIT 1**

Let me add some details (based of @st2000 answer).. Yes, Tennsy (and Arduino) are microcontrollers, not microprocessors. Programming avr chips in pure C doesn't require so much work as programming microprocessors. This is the simplest avr C program I could come with (typical blinky):

    #include <avr/io.h>
    #include <util/delay.h>

    int main(void) {
            (CLKPR = 0x80, CLKPR = 0x00);
            DDRD |= (1<<6);
            PORTD &= ~(1<<6);

            int sviti = 0;

            while (1) {
                    if (sviti)
                            PORTD |= (1<<6);
                    else
                            PORTD &= ~(1<<6);
                    sviti ^= 1;
                    _delay_ms(40000);
            }
    }

As you can see (@st2000), there are no dozens of setting up registers. It does not require any expensive equipment to upload resultant .HEX file - for teensy the only thing you need is a USB cable.

If you want a concrete example, I want to use [this library](http://www.pjrc.com/teensy/usb_mouse.html) with pure C, but it's obviously meant for wiring and arduino IDE primary. So how to use this library with pure C? And back to my main question, how to generally use libraries of this kind with pure C avr programming?

title: From Wiring to pure C

Answers: 2

body:
Refer to the actual processors used on the platforms to find reference material for ordinary C or C++ programming.  There are different processors used on various Arduino boards.  Be aware that this approach normally requires programming hardware which range from a few dollars to hundreds of dollars.  Also be aware that "[bare metal programming][1]" requires the programmer to setup the processor's resources of interest.  This normally involves setting dozens (as in the Arduino Uno AVR processors) if not thousands (as in Arduino Zero's ARM processors) of registers which can deal with everything from the processor's clock to interrupt vectors.

USB programming is very complex.  Consider the complete description of RS232 could be contained in a white paper.  The equivalent for USB would be at least a book.  To simplify your efforts, we can eliminate all USB Host features as a mouse is a peripheral or USB Device.  Further, you will probably want to limit your USB Device to a USB HID or Human Interface Device.  This allows most OSs to easily recognize and use the mouse as the HID definition is more complete / restrictive. Also note, embedded processors which happen to have a USB port usually only support USB Devices as USB Host requires additional features & resources.  Now that the scope of USB support has been narrowed, you can start searching through the different processor's libraries for what you need to create a USB HID Mouse.

  [1]: https://en.wikipedia.org/wiki/Bare_machine

body:
> And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.

nothing magic about going in "pure c".


body:
Is there anything built into the Arduino Uno or the XBee Pro 2 radio module that I can poll within my Arduino script to act as a unique identifier? Mac address or otherwise? If anyone has a code snippet that can do this it'd be extremely appreciated.

Currently my Arduino nodes are broadcasting only to my node.js server, but my server is broadcasting to all the nodes, so if they're all waiting to be assigned an identifier number through the handshake function I wrote, they all receive the same one. If I stagger powering them up this is avoided and they each get a unique ID, but I hope there exists a cleaner solution.

title: Arduino or XBee unique identifier?

Answers: 1

body:
When programming the Uno's, you could write identifying values into particular EEPROM bytes.  To automate the process, write a development-system program to produce serial-numbered HEX files, with the serial number counting up each time the program runs.

For example, if you store IDs into byte 0x1E of EEPROM, the serial number file would look as follows when the serial number is 0x23:

    :01001E0023BE
    :00000001FF

The first line in the above file says 01 bytes of payload, stored at address 001E, record type 00 (data), payload byte 23, checksum BE.   See [wikipedia's Intel HEX article](https://en.wikipedia.org/wiki/Intel_HEX) for further explanation of HEX file format.  In brief, each time the serial number byte goes up by one, the checksum byte goes down by one.

To program a serial number byte into EEPROM from a file called `SNfile.hex`, issue a command like the following.

    avrdude -p atmega328p -c arduino -P /dev/ttyUSB1 -b57600 -U eeprom:w:SNfile.hex:i

See the `avrdude` manpage for explanation.

In your sketch, use [EEPROM.read(address)](https://www.arduino.cc/en/Reference/EEPROMRead) to read a unit's serial number.  For example:

    #include <EEPROM.h>
    byte mySN = EEPROM.read(0x1E);

[Note, regarding your question about  “anything built in... to act as a unique identifier”, I once spent quite a while looking for such a thing on Uno, Nano, and Mega2560 Arduinos, and found nothing.  I haven't looked at XBee radio modules for such data.]


body:
is there a way to make the Arduino act as a voltage source, by generating sinusoidal, triangular and other kinds of signals? If so, can it be done using LabVIEW? (I've already managed reading analog signals using VISA)

Thank you!

title: Generating analog signals

Answers: 1

body:
The Due (and similar SAM based boards) have a DAC built in which can be set to different voltages (I forget the range off hand, maybe 0-Vcc at 12-bit resolution). Change that voltage fast enough, and you have a waveform.

Other Arduinos have PWM outputs which, when filtered through a low-pass filter, give a voltage proportional to the duty cycle of the PWM. Again, change the duty cycle fast enough and you have a waveform (limited by the *carrier frequency* of the PWM).

Can you do it from LabVIEW? Who knows? I have never used it.


body:
So, I have 3 buttons to a arduino.
I want to detect the button press on the 3 of them.

For that, i've created a function:

    int OnKeyPress (int port) {

   int  LastState, BeginState, r;
   r = 0;

   BeginState = digitalRead(port);

   if (BeginState != LastState) {
    if (BeginState == 1) r = 1 ;
   }

   delay(5);
   LastState = BeginState;
   return r;
    }

   I want to instantiate 3 instances of this code, separately and they have to retain this variables `int  LastState, BeginState, r;` for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.

Just, how?

title: OnKeyPress in a arduino

Answers: 1

body:
This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.

The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method.  There are several approaches to preserve these variables from one call to the next.  They can be declared as static integers.  Or they can be defined globally.

It appears you are recreating the existing [Bounce library][1].  I encourage you to continue if you are learning.  However, you may want to look at the Bounce library's [code][2] for guidance.

  [1]: http://playground.arduino.cc/Code/Bounce
  [2]: https://github.com/thomasfredericks/Bounce2


body:
I'm trying to mix `Serial.read()` and `Serial.readBytes()` when reading over one of the Serial ports on my Arduino Due.
I thought that using `Serial.read()` would clear what is on the serial, and then subsequent reads by `readBytes()` would not pick up what has already been read by the Serial.

The main reason I'm trying this approach is because large Serial reads can be unstable using the Arduino supplied `Serial.read()` - I've checked the Serial buffer with a logic analyzer, so I know that the data is on the Serial line, but `Serial.read()` drops some bytes.

Hence why I want to use `Serial.readBytes()`.

Here's what I'm doing:
<!-- language-all: lang-cpp -->

    #define FIXED_LENGTH 10
    char * buffer, * bp;
    int index, i, bufSize;
    while(1)
      {
      if(Serial3.available())
      {
        data = Serial3.read();
        Serial.print(data,HEX); //Check the data received
        buffer[index]=data;
        index++;

        if(index == FIXED_LENGTH){
           //...code to calculate bufSize from buffer...//
           bp = (char*)calloc(1,bufSize); //calloc bp size
           Serial3.readBytes(bp,bufSize); //read the rest of what's on the serial
           break;
        }
      }
      }

I get the correct output from the first part of the code - that is, it correctly calculates `bufSize` from buffer. But when I try to store the following length into bp, it gives me more or less the first output that I have already read on the first few passes!

Example:

Data coming in over `Serial3.read()` `[10]`: `0123456789`

The next characters in `Serial3` are `[6]`: `ABCDEF`

Stored into `bp` using `Serial3.readBytes()` `[6]`: `000045`

Do I need to flush `Serial3` before attempting to read the next set of bytes off of it? Do I need to wait/set a timeout before advancing to the next operation?

title: Reading Serial Data Using readBytes() and Use of Serial.read()

Answers: 0


body:
I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.

Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html

I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?

      #include <JeeLib.h> //  power saving library
      ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
      #include <SoftI2C.h> // rweather lib for RTC module
      #include <DS3232RTC.h> //rweather lib for RTC module
      SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
      DS3232RTC rtc(i2c);
      RTCTime time;
      int gatePin = 12;   //  mosfet Gate connected to digital pin
      int startHour = 6; // want to replace with sunrise time
      int endHour = 19; // want to replace with sunset time

    void setup()
    {
     pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
    }

    void loop()
    { // main loop starts here
      rtc.readTime(&time);  //get current time
      if (time.hour >= startHour && time.hour < endHour) // check daytime
      {   // if condition begins here
          while(time.hour < endHour ) // daytime operating period

          {   //  while loop (day) begins here
          digitalWrite(gatePin, HIGH);   // turn on gate for power supply
          Serial.flush(); //needed before sleepy
          Sleepy::loseSomeTime(30000); // low power wait
          digitalWrite(gatePin, LOW);    // turn off gate for power supply
          Serial.flush(); // needed before sleepy
          for (int i=0; i <= 3; i++){
            Sleepy::loseSomeTime(65000); // low power wait
            } // end for loop
          rtc.readTime(&time);
          } // end while loop (day)
          } //  if condition (daytime) ends here
    else
      { // else condition (night time) starts here
        while (time.hour >= endHour || time.hour < startHour )
        { // while loop (night) begins here
        for (int i=0; i <= 59; i++){
        Serial.flush(); // needed before sleepy
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
        rtc.readTime(&time);
        } // while loop (night) ends here
    // need to refine timing else hour-long wait periods can run past the end of night period
      } // else condition (night) ends here
    } //  main loop ends here

I will be very grateful for advice, many thanks in advance!

EDIT: Part of my original question could be answered - see below about time-date format *without* using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.

title: How to improve date-time control from RTC?

Answers: 2

body:
> Is there a simple way to convert to date-time object?

Not with this library. But you can find [other][Christensen]
[libraries][Tecsmith] supporting the DS3232 which work with the [Arduino
Time library][]. This time library provides both the date and time in a
single object, either:

* a `time_t`, which is just the number of seconds elapsed since a
  standard “epoch”
* a `tmElements_t` struct, which has the date and time broken into
  separate elements (year, month, day, hour...).

> Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more
accurate ones are also the more complex.

> `#include <SoftI2C.h>`

Doesn't your Arduino have a hardware I2C port? That would be more
efficient than software emulation.

> `Serial.flush(); //needed before sleepy`

It's only needed if you are actually using the serial port.

**Edit**: I saw on your [other question][] that you have been bitten by
an incompatibility between the Arduino Time library and the file
`time.h` from avr-libc. Now I just noticed that avr-libc includes the
functions [`sun_rise()` and `sun_set()`][sun_rise] that you may find
handy. Not sure they will play well with the Arduino time libraries
though. One possible incompatibility is the fact that they use different
epochs for defining `time_t` (year 1970 v.s. 2000).

[Christensen]: https://github.com/JChristensen/DS3232RTC
[Tecsmith]: https://github.com/Tecsmith/DS3232RTC
[Arduino Time library]: https://github.com/PaulStoffregen/Time
[other question]: https://arduino.stackexchange.com/q/29600
[sun_rise]: http://www.nongnu.org/avr-libc/user-manual/group__avr__time.html#ga21a491a92bce972d041e2194b4577943

body:
I hope I am allowed to summarise progress. Edgar Bonet's answer above pointed me in the right direction regarding date-time format and I want to 'accept' that answer, although it did not resolve my difficulties with RTC. I need to ask a new question about RTC later.

Using the Time library Edgar Bonet recommended, I managed to set and change date-time format, and calculate duration between date-time instances. I hope my example below could perhaps be useful for other beginners. If anyone has suggestions to improve this example, please add them.

        #include <TimeLib.h> // https://github.com/PaulStoffregen/Time
        time_t tstart;

        void setup()  {
        Serial.begin(9600);
        // assume no RTC available therefore set date-time in this sketch
        // when serial monitor opens, date-time will be set as follows
        setTime(8,30,0,17,10,2016); // (hr,min,sec,day,mnth,yr);
        tstart = now();
        Serial.print("Started at: ");
        digitalClockDisplay();
        Serial.println();
        }

        void loop(){
        Serial.println("Waiting...");
        delay(20000 + random(500, 5000) );
        Serial.println();
        time_t tnow = now();
        Serial.print("Now it is: ");
        digitalClockDisplay();
        time_t duration = tnow - tstart;
        Serial.print("Duration since start: ");
        showDuration(duration);
        Serial.println();
        Serial.println();
        }

        // function to print current date-time
        // modified from example in TimeLib
        void digitalClockDisplay(){
          Serial.print("Date: ");
          Serial.print(day());
          Serial.print("-");
          Serial.print(month());
          Serial.print("-");
          Serial.print(year());
          Serial.print("  Time: ");
          Serial.print(hour());
          printDigits(minute());
          printDigits(second());
          Serial.println();
        }
        // utility function from TimeLib
        // to print leading zeros
        void printDigits(int digits){
          Serial.print(":");
          if(digits < 10)
            Serial.print('0');
          Serial.print(digits);
        }

        // function from example TimeRTCLog
        void showDuration(time_t duration){
        // prints the duration in days, hours, minutes and seconds
          if(duration >= SECS_PER_DAY){
             Serial.print(duration / SECS_PER_DAY);
             Serial.print(" day(s) ");
             duration = duration % SECS_PER_DAY;
          }
          if(duration >= SECS_PER_HOUR){
             Serial.print(duration / SECS_PER_HOUR);
             Serial.print(" hour(s) ");
             duration = duration % SECS_PER_HOUR;
          }
          if(duration >= SECS_PER_MIN){
             Serial.print(duration / SECS_PER_MIN);
             Serial.print(" minute(s) ");
             duration = duration % SECS_PER_MIN;
          }
          Serial.print(duration);
          Serial.print(" second(s) ");
        }


body:
I'm trying to understand how to control an RGB LED strip, I set up all the `TIP120` (because I could get my hands on an n-channel mosfet), if I power everything in this way I can change colours and everything:
[![enter image description here][1]][1]

but now I'm facing a dilemma now, whats the correct way to manage to switch my power strip ON/OFF based on an input from a pir sensor? I mean, how can I handle 12V 3A (requested by my led strip), how do I correctly wire my Arduino up in order to make it switch the LED strip ON/OFF?

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

title: How do I turn off a 12V 3A RGB LED strip?

Answers: 1

body: That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.


body:
I want to change the `I2C` frequency of my Arduino Mega 2560. I did find two methods. One method is to change the `TWBR` variable after `Wire.begin()`. The other one is to use `Wire.setClock()` after `Wire.begin()`.

Whats the difference between the 2 methods? which one is better? Can I set any `I2C` frequency I want?

title: Difference between Wire.setClock() method and TWBR method for changing I2C Frequency

Answers: 2

body:
They are both one and the same. One is easier to remember though (I'll let you work out which).

`Wire.setClock(frequency)` just (ultimately) does:

    TWBR = ((F_CPU / frequency) - 16) / 2;

You can set any frequency that ends up with that formula generating an integer between 0 and 255.

body:
> Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.

There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

> Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

> Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.

Cheers!


body:
I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  https://arduino.stackexchange.com/questions/17797/arduino-ide-underlying-code-and-libraries  Maybe I'm missing them?

Also, is it possible to set a breakpoint?

Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.

Thanks,

Dave

title: How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan

Answers: 2

body:
The simplest way is to look at the source on Github:

* https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.

body:
Yes, they need a right-click->"Go To Definition"

Assuming the first appearance of a variable is the definition (variable declaration), use the following easily learnt "hack"..

Double click variable, then ^F, Esc, ^Home, ^G

..(where ^ = Ctrl).


body:
I had never used Arduino before. When I tried to interface my new Arduino Uno board to my computer, the computer failed to recognize the board.

Why isn't the board interfaced successfully? How should I troubleshoot that problem?

title: My computer dose not recognise my Arduino Uno

Answers: 1

body: Majenko is probably right.  If it is a clone Arduino board you will need to install some CH340 drivers.  If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.


body:
I at the moment trying smoothly move a stepper motor. The problem with the stepper motor, is that it makes a high pitch noise while it moves, or sometime a crackling noise from the motor.

So i tried ramping up the frequency of the step signal, which seemed to help a bit but not perfect. Then I tried micro stepping rather than  full stepping, which also helped a bit but still, the noise is very clear.

The motor I am using is a [PK244-01A][1]
And the driver it is connected to is [this one][2]

I am not at all sure if the ramping I do is either too steep, or completely  incorrect, but here is the code that controls the motor.

    void stepper_motor::step_pwm()
    {

        digitalWrite(en_pin,HIGH);

        delay(0.005);

        digitalWrite(dir_pin,HIGH);
        //LOW  - Move towards the sensor
        //HIGH -  Move away from the sensor

        delay(0.005);
        int increment = 0;
        int step_count = 0;
        while(step_count <= max_step)
        {
          digitalWrite(step_pin,LOW);
          delayMicroseconds(2000);
          digitalWrite(step_pin,HIGH);
          delayMicroseconds(2000-increment);
          step_count++;

          if(step_count >= 1)
          {
            increment++;
            step_count = 0;
          }
        }

    }

  Anything I could do to make the noise of the motor less significant?

  [1]: https://www.orientalmotor.co.in/products/st/list/detail/?product_name=PK244-01A&brand_tbl_code=ST&series_code=G000&type_code=Unipolar 6 lead wires&type=Standard Type
  [2]: http://www.sainsmart.com/zen/documents/20-019-201/ST330  Stepper Motor Driver Board User Manual.pdf

title: Ramping a stepper motor

Answers: 2

body:
I had a similar issue once before. It actually matters a lot to properly ramp up your stepper motor. Especially under load if you ramp up too steep you can loose steps.

Since you are already using the arduino environment I suggest you could use the [AccelStepper][1] library.

I lets you set the acceleration and max. speed parameters nicely and uses a properly calculated ramp.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/

body: You need to be using the adjusted delay for both the high and the low part of the signal.  Also, what happens when the variable "increment" is larger than 2000?  Nothing good, for certain.  I'd personally like to be able to delay by a negative number and undo some things that are already done, but I don't think yoz can turn back time using an Arduino.


body:
I am at the moment trying to make a bipolar stepper motor move.
I am interfacing it through a control board, which takes the input `Step`, `Dir`, `En`, and 5V.

I am providing those input signal via an Arduino, but can't get the damn thing to move. all it does it move a step forward and backwards, like it being stuck or and tries to wiggle out of something.. What could the reason be..

Here is the Code:

    #include "stepper_motor.h"
    int max_step = 200;
    stepper_motor::stepper_motor()
    {
      pinMode(BUILTIN_LED,OUTPUT);
      pinMode(step_pin,OUTPUT);
      pinMode(dir_pin,OUTPUT);
      pinMode(en_pin,OUTPUT);

      alive_bool = true;
      position_bool = false;
      step_count = 0;
    }

    void stepper_motor::step_pwm()
    {

      if(position_bool==true)
      {
        //Dir pin low
        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,LOW);

        delay(0.005);

        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,HIGH);

        delay(0.005);

        int step = 0;
        while(step < max_step)
        {
          digitalWrite(step_pin,HIGH);
          delay(1);
          digitalWrite(step_pin,LOW);
          delay(1);
        }

        //digitalWrite(en_pin,LOW);
        //position_bool = false;
      }
      else
      {
        //Dir pin high
        delay(1000);
        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,LOW);

        delay(0.005);

        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,HIGH);

        delay(0.005);

        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,HIGH);
        digitalWrite(en_pin,HIGH);

        int step = 0;
        while(step < max_step)
        {
          digitalWrite(step_pin,HIGH);
          delay(1);
          digitalWrite(step_pin,LOW);
          delay(1);
        }

        //digitalWrite(en_pin,LOW);
        //position_bool = true;
      }

    }

Updated step_pwm():

    void stepper_motor::step_pwm()
    {
        //Start -  En Low , DIR HIGH, STEP high
        //init configuration!
        digitalWrite(step_pin, HIGH);
        digitalWrite(dir_pin,HIGH);
        digitalWrite(en_pin,LOW); // Previous LOW

        delay(0.005);

        //T1-  En HIGH , DIR HIGH, STEP HIGH
        //Enable high
        //digitalWrite(step_pin, HIGH);
        //digitalWrite(dir_pin,HIGH);
        digitalWrite(en_pin,HIGH);

        delay(0.005);

        //T2-  En HIGH , DIR low, STEP HIGH
        //Direction choosen
        //digitalWrite(step_pin, HIGH);
        digitalWrite(dir_pin,LOW);
        //digitalWrite(en_pin,HIGH);

        delay(0.005);
        //T2-  En HIGH , DIR low, STEP HIGH
        //STEP  step between low and high with 2.5µs between

        while(1)
        {
          digitalWrite(step_pin,LOW);
          delay(2.5);
          digitalWrite(step_pin,HIGH);
          delay(2.5);
        }

    }

The control board i am using is a [ST330-v3][1]
The motor i am using is [this one][2]
here is a little block diagram of how things are connected.

[![enter image description here][3]][3]

  [1]: http://www.sainsmart.com/zen/documents/20-019-201/ST330  Stepper Motor Driver Board User Manual.pdf
  [2]: https://www.orientalmotor.com.sg/products/st/list/detail/?product_name=PK244-01A&brand_tbl_code=ST&series_code=G000&type_code=Unipolar 6 lead wires&type=Standard Type
  [3]: https://i.stack.imgur.com/jsaYI.png

title: Make a stepper motor move

Answers: 2

body:
You must set EN BEFORE you set DIR.  The datasheet says EN must be high for at least 5 microseconds before you set DIR.  You should probably just set EN high when your program starts, then not fool with it until your program ends.

The next thing is that I don't see you incrementing the variable "step" anywhere.  So, if you did get the stepper to turn, it wouldn't stop.

-------------

The updated code looks like it ought to work.

You should use DelayMicroseconds instead of Delay(0.005) though.  Delay takes an integer instead of a decimal value, so you won't get what you expect.  Curse the Arduino IDE for not throwing a fit when pass a float for an int.

-------------

It looks like anything working properly is purely luck.  The board you are using(NOT an Arduino) uses 3.3V logic levels.  The ST330 says a high must be at least 4V, so if it reacts to your control signals at all it is just luck.

The 8266 outputs are rated for 12mA, the ST330 inputs need about 20mA, so you are over doing it.  The 8266 might put up with, and might just die on you.

You might be able to drive the ST330 by switching the mode of the pins.

Low would be "set pin to mode output and set low."

A high would be "set mode input."

Input mode leaves the pin floating, which the ST330 will interpret as a high.

Other than that, you could use NPN transistors to drive the ST330 inputs, then invert your output signals.

The NPN would invert your signal (a high becomes a low) so you would have to set an output to low to get a high going into the ST330.

----------

You can use NPN transistors like this to drive the ST330:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/PzYWz.png)

<!-- End schematic -->

Setting the  GPIO from the ESP8266 to high would cause a low on the ST330 input.

Setting the GPIO pin to low would cause a high on the ST330 input.

This is the solution I would prefer if I needed to use the ESP8266 with the ST330.

----------

If you'd like to try a purely software solution, then do this:

 1. To send a low to the ST330 input, set the GPIO to pin mode output and set the output to low. (pinMode(step_pin,INPUT) then DigitalWrite(step_pin,LOW))
 2. To send a high to the ST330 input, set the pin mode to INPUT (pinMode(step_pin,INPUT)

When the GPIO pin is in input mode, it floats.  It doesn't have a voltage level of its own - it acts like it is disconnected.

If that works, I'd still prefer to use the transistors.

----------

You can avoid all of this using the UNO.  It has 5V logic levels on the outputs.

body:
This is problematic:

     delay(0.005);

The Arduino delay() function takes an `unsigned long` as an input, which is an integer rather than floating point type.  As a result, the argument you pass to it will be treated as zero.  Depending on how delay() is implemented this will result in either no delay (beyond overhead), or a minimum that may be longer than you intended.

Of course you now seem to only be running this code once, and then going into an unending loop which uses a 2.5 ms delay that will, for the same reason, be more of a 2ms delay.


body:
I have these 2 motor shields:
**Adafruit Motor Shield V2** and
**Seed Motor Shield V2**.

They are stacked on top of an **Arduino UNO**.

My question is, how can I power 2 of those motor shields with one 3S Lipo battery(**Turnigy 3S 2200mAh 20C**), given that I have 6 identical 4.6-6V DC gearmotors?

Thanks!

title: How to power two stacked motor shields with one 3S Lipo battery (11.1V)?

Answers: 1

body:
You can avoid using a linear voltage regulator. Try using [this][1] voltage regulator.

You will get 5 Volts 2 Amp output which should be easy to connect to motor shield's input power ports.

  [1]: https://www.amazon.com/DROK-Converter-Step-down-Transformer-Stabilizer/dp/B00JUFJ1GA/ref=sr_1_2?s=electronics&ie=UTF8&qid=1475207248&sr=1-2&keywords=voltage+regulator+5+volt&th=1


body:
I'm an Arduino newbie, no background in C/C++, needing help to understand Arduino IDE verbose output about compiler errors. My searching failed to find suitable info - have I missed a relevant guide?

Below example of compiler errors produced when I try to compile Example sketch (TestRTC) from a downloaded library. I assume this Example code is valid. Guessing that my errors relate to missing components. The library was one of two recommended in answer to [question][1]. I used IDE Manage Libraries to install from downloaded zip files. Windows file manager shows both library folders are present.

In example below: Which components did the compiler find/not find? Where did compiler search for needed components? What other useful info could be gleaned from this error output?

Would be very grateful for general advice on interpreting error text as well as this particular example. Many thanks.

    Arduino: 1.6.11 (Windows 7), Board: "Arduino/Genuino Uno"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino
    Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\Wire.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master\DS3232RTC.cpp" -o "nul"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "nul"
    Generating function prototypes...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp.o"
    In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

         static void read(tmElements_t &tm);

                          ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:83:23: error: 'tmElements_t' has not been declared

         static void write(tmElements_t &tm);

                           ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:84:27: error: 'tmElements_t' has not been declared

         static void writeTime(tmElements_t &tm);

                               ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:85:27: error: 'tmElements_t' has not been declared

         static void writeDate(tmElements_t &tm);

                               ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:61: error: 'tmElements_t' has not been declared

         static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                                                                 ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:88:61: error: 'tmElements_t' has not been declared

         static void writeAlarm(uint8_t alarm, alarmMode_t mode, tmElements_t tm);

                                                                 ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:110:24: error: 'tmElements_t' has not been declared

         static void _wTime(tmElements_t &tm);

                            ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:111:24: error: 'tmElements_t' has not been declared

         static void _wDate(tmElements_t &tm);

                            ^

    TestRTC:79: error: 'tmElements_t' does not name a type

     inline uint8_t monthLength(const tmElements_t *date)

                               ^

    TestRTC:297: error: 'tmElements_t' does not name a type

     void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                                  ^

    TestRTC:79: error: 'tmElements_t' does not name a type

     inline uint8_t monthLength(const tmElements_t *date)

                                      ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'uint8_t monthLength(const int*)':

    TestRTC:81: error: request for member 'Month' in '* date', which is of non-class type 'const int'

         if (date->Month != 2 || !isLeapYear(date->Year))

                   ^

    TestRTC:81: error: request for member 'Year' in '* date', which is of non-class type 'const int'

         if (date->Month != 2 || !isLeapYear(date->Year))

                                                   ^

    TestRTC:82: error: request for member 'Month' in '* date', which is of non-class type 'const int'

             return monthLengths[date->Month - 1];

                                       ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdTime(const char*)':

    TestRTC:213: error: 'tmElements_t' was not declared in this scope

         tmElements_t tm;

         ^

    TestRTC:218: error: expected unqualified-id before '.' token

             tm.Hour = readField(args, posn, 23);

               ^

    TestRTC:219: error: expected unqualified-id before '.' token

             tm.Minute = readField(args, posn, 59);

               ^

    TestRTC:221: error: expected unqualified-id before '.' token

                 tm.Second = readField(args, posn, 59);

                   ^

    TestRTC:223: error: expected unqualified-id before '.' token

                 tm.Second = 0;

                   ^

    TestRTC:224: error: expected primary-expression before '.' token

             if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                   ^

    TestRTC:224: error: expected primary-expression before '.' token

             if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                    ^

    TestRTC:224: error: expected primary-expression before '.' token

             if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                                       ^

    TestRTC:228: error: expected primary-expression before ')' token

             RTC.writeTime(tm);

                             ^

    TestRTC:233: error: expected primary-expression before ')' token

         RTC.read(tm);

                    ^

    TestRTC:234: error: expected primary-expression before '.' token

         printDec2(tm.Hour);

                     ^

    TestRTC:236: error: expected primary-expression before '.' token

         printDec2(tm.Minute);

                     ^

    TestRTC:238: error: expected primary-expression before '.' token

         printDec2(tm.Second);

                     ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdDate(const char*)':

    TestRTC:245: error: 'tmElements_t' was not declared in this scope

         tmElements_t tm;

         ^

    TestRTC:256: error: expected unqualified-id before '.' token

             tm.Day = (byte)(value % 100);

               ^

    TestRTC:257: error: expected unqualified-id before '.' token

             tm.Month = (byte)((value / 100) % 100);

               ^

    TestRTC:258: error: expected unqualified-id before '.' token

             tm.Year = CalendarYrToTm( (unsigned int)(value / 10000) );

               ^

    TestRTC:259: error: expected primary-expression before '.' token

             if (tm.Month < 1 || tm.Month > 12) {

                   ^

    TestRTC:259: error: expected primary-expression before '.' token

             if (tm.Month < 1 || tm.Month > 12) {

                                   ^

    TestRTC:263: error: expected primary-expression before ')' token

             uint8_t len = monthLength(&tm);

                                          ^

    TestRTC:264: error: expected primary-expression before '.' token

             if (tm.Day < 1 || tm.Day > len) {

                   ^

    TestRTC:264: error: expected primary-expression before '.' token

             if (tm.Day < 1 || tm.Day > len) {

                                 ^

    TestRTC:269: error: expected primary-expression before ')' token

             RTC.writeDate(tm);

                             ^

    TestRTC:274: error: expected primary-expression before ')' token

         RTC.read(tm);

                    ^

    TestRTC:275: error: expected primary-expression before '.' token

         if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

               ^

    TestRTC:275: error: expected primary-expression before '.' token

         if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

                                              ^

    TestRTC:276: error: expected primary-expression before '.' token

         Serial.print(tm.Day, DEC);

                        ^

    TestRTC:277: error: expected primary-expression before '.' token

         Serial.print(months[tm.Month - 1]);

                               ^

    TestRTC:278: error: expected primary-expression before '.' token

         Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                           ^

    TestRTC:278: error: 'tmYearToCalendar' was not declared in this scope

         Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                                ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: At global scope:

    TestRTC:297: error: 'tmElements_t' does not name a type

     void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                                  ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void printAlarm(byte, alarmMode_t, int)':

    TestRTC:324: error: request for member 'Second' in 'time', which is of non-class type 'const int'

                 printDec2(time.Second);

                                ^

    TestRTC:328: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

                 printDec2(time.Minute);

                                ^

    TestRTC:330: error: request for member 'Second' in 'time', which is of non-class type 'const int'

                 printDec2(time.Second);

                                ^

    TestRTC:336: error: request for member 'Day' in 'time', which is of non-class type 'const int'

                   Serial.print(time.Day);

                                     ^

    TestRTC:340: error: request for member 'Wday' in 'time', which is of non-class type 'const int'

                   Serial.print(days[time.Wday - 1]);

                                          ^

    TestRTC:343: error: request for member 'Hour' in 'time', which is of non-class type 'const int'

                 printDec2(time.Hour);

                                ^

    TestRTC:345: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

                 printDec2(time.Minute);

                                ^

    TestRTC:347: error: request for member 'Second' in 'time', which is of non-class type 'const int'

                 printDec2(time.Second);

                                ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarms(const char*)':

    TestRTC:359: error: 'tmElements_t' was not declared in this scope

         tmElements_t time;

         ^

    TestRTC:362: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

             RTC.readAlarm(alarmNum, mode, time);

                                               ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:362:43: note: candidate is:

    In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

         static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                     ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarm(const char*)':

    TestRTC:373: error: 'tmElements_t' was not declared in this scope

         tmElements_t time;

         ^

    TestRTC:391: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 time.Hour = readField(args, posn, 23);

                      ^

    TestRTC:392: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 time.Minute = readField(args, posn, 59);

                      ^

    TestRTC:393: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 if (time.Hour == 99 || time.Minute == 99) {

                          ^

    TestRTC:393: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 if (time.Hour == 99 || time.Minute == 99) {

                                             ^

    TestRTC:417: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

         RTC.readAlarm(alarmNum, mode, time);

                                           ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:417:39: note: candidate is:

    In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

         static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                     ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

    Multiple libraries were found for "DS3232RTC.h"
     Used: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master
     Not used: C:\Program Files (x86)\Arduino\libraries\RTC
    Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
    Using library DS3232RTC-master in folder: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master (legacy)
    exit status 1
    'tmElements_t' does not name a type

  [1]: https://arduino.stackexchange.com/questions/29577/how-to-improve-date-time-control-from-rtc/29581#29581

title: How to properly understand verbose compiler error text? For beginner level

Answers: 2

body:
Consider the Arduino paradigm as a collection of well established (very) sophisticated computing tools. Arguably, the C compiler is the most complex of these tools.  So understanding the compilers output can be challenging at times.

That said, the normal way to approach compiler problems is to solve the 1st error the compiler finds then recompile.  More often then not solving the 1st error will resolve many other errors.

A guess, in this particular case, is that an include file has been omitted.  Find where the type "tmElements_t" is defined and check to see if the include file (a.k.a. header file) where it is defined needs to be included into the source code file where the 1st errors shows up.

Added later...

Ug, the 1st error is not even your code!  It is in the DS323RTC library you downloaded.  We can probably assume this library is working and compiles.  So that leaves the burden on us to find the reason why your code does not compile.  Besides, you can't go back to GitHub saying there is a bug in the library with out trying to solve the problem first.

The 1st stop is to read any readme.txt file at GitHub or the copy of it you downloaded with the library.  We find in the 1st few dozen lines this:

    To use the DS3232RTC library, the Time and Wire libraries must also be included. For brevity, these includes are not repeated in the examples below:

    #include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
    #include <Time.h>         //http://www.arduino.cc/playground/Code/Time
    #include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

So right away we see we need to include Time.h.  If you look in the Time library (another library you need to download if you have not already) you will find that it is where tmElements_t is defined.  It does bother me that Time.h is included after DS323RTC.h.  If you are still having problems try including Time.h first.

body:
As @st2000 said, it's best to start with the first error shown as that error may be causing other errors that will go away once you fix the first one. You should be aware of the difference between warnings and errors. Warnings may or may not be related to the error preventing your code from compiling so I'd just focus on the error at first. So scroll the console window all the way up and then start reading down until you find the first error. If the output is very long you may find it useful to copy the output and paste into a text editor then do a search for the word error, starting from the beginning of the file.

In your compiler output the first error listed is:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

         static void read(tmElements_t &tm);

                          ^
The first thing we can learn from this is the file where the error occurred:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h

The next part of the error message is:

    :82:22

This means that the error occurred at line 82, column 22 of the file DS3232RTC.h. This makes it easy for you to find that code in the file. Any decent text editor will show the current line number and column at the cursor.

The next part of the error message is a description of the problem:

    error: 'tmElements_t' has not been declared

Often you may not understand exactly what it means. This is where your favorite search engine comes in handy. You can try searching for "'tmElements_t' has not been declared". The 'tmElements_t' part is very specific to this code so you will get less results but they may lead you to others who have had the same problem and the solutions they found.

Searching for the general error "has not been declared" will give you a broader description of what the compiler is trying to tell you.

Finally is the actual code line:

     static void read(tmElements_t &tm);

                      ^
The carat shows the column number of the error.

Unfortunately the actual bug may often be in previous code so this isn't as simple as it may seem.

Now lets talk about your specific issue. A search for "'tmElements_t' has not been declared" does yield some results from others having similar problems but you will probably find after going through their solutions that none of them fix the error. This is because the error is caused by a recent update to a new version of avr-libc in Arduino IDE 1.6.10/Arduino AVR Boards 1.6.12 and later. This version of avr-libc contains a file named time.h. On a case insensitive operating system such as Windows this will cause

    #include <Time.h>
to include the wrong file, time.h which causes the error since indeed that file doesn't declare tmElements_t. This problem is known to the author of the Time library and he has moved the code to a file named TimeLib.h as a workaround. The file Time.h was left for backwards compatibility. So the solution is to change:

    #include <Time.h>

to:

    #include <TimeLib.h>

I was able to get the TestRTC sketch to compile by just making this change in TestRTC.ino but you may also need to change line 25 of DS3232RTC.h.

I have submitted a pull request to fix this issue to the DS3232RTC repository: [https://github.com/Tecsmith/DS3232RTC/pull/9][1]

EDIT: My pull request has now been merged so the issue can also be solved by installing the updated Tecsmith/DS3232RTC library.

If this solves your problem please also update [your other question][2] so that the people trying to help you there will know it's fixed.

  [1]: https://github.com/Tecsmith/DS3232RTC/pull/9
  [2]: https://arduino.stackexchange.com/questions/29577/how-to-improve-date-time-control-from-rtc/29581#29581