body:
To elaborate on Edgar Bonet's answer and my comment under it, you cannot usefully put PROGMEM variables as local variables because local (non-static) variables have to be allocated on the stack.

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

    void lookUpInSBox(size_t which, byte *address, byte* binaryOutcome, size_t addressFrom){

       ...

        const uint8_t SBoxes[8][4][16] PROGMEM = {

                                 /*S1*/

       { {14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
         { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
         { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
         {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13}    },

You could make them global. But if you prefer  not to do that, put `static` in front of them. Doing that on your code reduced it to 247 bytes.

<!-- language-all: lang-none -->

    Global variables use 247 bytes (12%) of dynamic memory, leaving 1,801 bytes for local variables. Maximum is 2,048 bytes.

---

You expect a bit more than the 60 you counted. The serial buffers take a bit (128 bytes).

See [Putting constant data into program memory (PROGMEM)](http://www.gammon.com.au/progmem) for more information. On a tiny sketch I found the following 346 bytes already in use:

* 34 bytes for the HardwareSerial instance (Serial)
* 64 bytes for the Serial transmit buffer
* 64 bytes for the Serial receive buffer
* 4 bytes for the Serial transmit buffer head and tail pointers
* 4 bytes for the Serial receive buffer head and tail pointers
* 9 bytes for keeping track of millis / micros
* 4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)
* 128 bytes for the heap safety margin
* 6 bytes for a few nested function calls (main -> setup -> getFreeMemory)
* 16 bytes for the compiler vtable for HardwareSerial
* 4 bytes for variables __brkval and __flp (used in memdebug)
* 2 bytes pushed onto the stack in main (to save registers)
* 2 bytes pushed onto the stack in setup (to save registers)
* 4 bytes pushed onto the stack in getFreeMemory (to save registers)
* 1 byte because the stack pointer starts at 0x8FF rather than 0x900

The sketch on my page used dynamic memory allocation so it used a bit more than yours does (for keeping track of it).

---

> Once it starts printing gibberish or looping (that means it prints something and starts again from the beginning of the program) I know I have run out of SRAM

I'm a bit puzzled by all the `new`/`delete` you are doing. Why do that? For example:

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

    byte *E;
    E = new byte[48/8];
    for(size_t i = 0; i < 48; i++){
        insertBit( E, i, bitValue( R, E_BIT[i]-1 ) );
    }

    // XOR Kn and  E(Rn-1)
    byte KxorE[48/8];
    for (size_t i = 0; i < 48; i++){
        insertBit( KxorE, i, bitValue( K, i ) ^ bitValue( E, i ) );
    }
    delete[] E;

Massive amounts of dynamic memory allocation may fragment memory. Can't you rewrite to not do that? You can pass arrays by reference, it just seems weird (and slow) to do all that allocation.


sender: user

message:
How to read data from PC

I'm new to Arduino.

I'm passing some data from my Android phone to my Macbook via bluetooth (throught the app Sensoduino).

What I'd like to do now is to export that data to my Arduino Mini Pro.

Is there any way to achieve it?

(NOTE: I'm not able to connect my Android Phone directly to the Arduino via Sensoduino)

sender: assistant

body:
A simple bluetooth module like a HC-05 wired to your Arduino will give you a  serial stream that can be read and/or written.

With the RX/TX connected to say pins 10 & 11, a SoftwareSerial() object will provide access:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

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

    void loop()
    {
        int value;

        if (mySerial.available(sizeof(int)))
        {
            value = mySerial.parseInt();
        }
    }

If you connect the module to pins 0 & 1 - you can just use the Arduino standard Serial functions, but it will cause problems uploading to the board.  In which case you would disconnect the bluetooth module for uploading.


message:
Help Understanding FFT Analysis and analogRead()?

Here's the deal, I'm attempting to learn how to use an FFT (Fast Fourier Transformation) Library for sound analysis (link is [here][1]). My issue is that this comes with included C++ code to show users how to use the FFT library. There are three examples, but I'll show this one because it's closest to the application I have planned for it:

    /*
    fft_adc_serial.pde
    guest openmusiclabs.com 7.7.14
    example sketch for testing the fft library.
    it takes in data on ADC0 (Analog0) and processes them
    with the fft. the data is sent out over the serial
    port at 115.2kb.
    */

    #define LOG_OUT 1 // use the log output function
    #define FFT_N 256 // set to 256 point fft

    #include <FFT.h> // include the library

    void setup() {
      Serial.begin(115200); // use the serial port
      TIMSK0 = 0; // turn off timer0 for lower jitter
      ADCSRA = 0xe5; // set the adc to free running mode
      ADMUX = 0x40; // use adc0
      DIDR0 = 0x01; // turn off the digital input for adc0
    }

    void loop() {
      while(1) { // reduces jitter
        cli();  // UDRE interrupt slows this way down on arduino1.0
        for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
          while(!(ADCSRA & 0x10)); // wait for adc to be ready
          ADCSRA = 0xf5; // restart adc
          byte m = ADCL; // fetch adc data
          byte j = ADCH;
          int k = (j << 8) | m; // form into an int
          k -= 0x0200; // form into a signed int
          k <<= 6; // form into a 16b signed int
          fft_input[i] = k; // put real data into even bins
          fft_input[i+1] = 0; // set odd bins to 0
         }
        fft_window(); // window the data for better frequency response
        fft_reorder(); // reorder the data before doing the fft
        fft_run(); // process the data in the fft
        fft_mag_log(); // take the output of the fft
        sei();
        Serial.println("start");
        for (byte i = 0 ; i < FFT_N/2 ; i++) {
          Serial.println(fft_log_out[i]); // send out the data
        }
      }
    }

Now, with that said, I have a very general grasp of the idea that those lines referencing some variable called ADMUX and ADCSRA have to do with the analogRead() method and that the ADCH and ADCL refer to another two components that are combined to provide the returned integer that analogRead() spits out. What I don't understand whatsoever are those seemingly random strings of characters that these are being set equal to. For example, what does 0x40 or 0x01 or 0xe5 even refer to in the setup() method (if nothing else maybe somebody could point me in the right direction for this, because that part I really am entirely clueless about). And furthermore, why manipulate these directly in the first place, because if you reference the [source code][2] for analogRead() they look awfully similar. Thanks for any help in advance!

  [1]: http://wiki.openmusiclabs.com/wiki/ArduinoFFT
  [2]: http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html

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

It would have been preferable if the author of that code had used proper bit masks. For example:

      ADCSRA = 0xe5; // set the adc to free running mode

Looking at the datasheet:

[![ADCSRA][1]][1]

Now, **0xe5** is **11100101** in binary.

So that line could have been written:

      ADCSRA = bit (ADEN) | bit (ADSC) | bit (ADATE) | bit (ADPS2) | bit (ADPS0);

The last two (ADPS2 and ADPS0) give the prescaler (of 32):

[![ADC prescaler][2]][2]

The other bits are explained in the datasheet:

* **Bit 7 – ADEN: ADC Enable**

    Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the ADC off while a
    conversion is in progress, will terminate this conversion.

* **Bit 6 – ADSC: ADC Start Conversion**

    In Single Conversion mode, write this bit to one to start each conversion. In Free Running mode, write this bit to
    one to start the first conversion. The first conversion after ADSC has been written after the ADC has been
    enabled, or if ADSC is written at the same time as the ADC is enabled, will take 25 ADC clock cycles instead of
    the normal 13. This first conversion performs initialization of the ADC.
    ADSC will read as one as long as a conversion is in progress. When the conversion is complete, it returns to
    zero. Writing zero to this bit has no effect.

* **Bit 5 – ADATE: ADC Auto Trigger Enable**

    When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a
    positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits,
    ADTS in ADCSRB.

---

You can work through the other registers in a similar way.

  [1]: https://i.stack.imgur.com/RpyEo.png
  [2]: https://i.stack.imgur.com/MpmBO.png


body:
Nick Gammon already gave a very fine answer about the meaning of the
mysterious numbers you were wondering about. Here I am trying to answer
only your last question:

> why manipulate these directly in the first place, because if you
> reference the source code for analogRead() they look awfully similar.

One of the reasons is, as Dave X said in a comment, to get a higher
sample rate. Assuming this is an Arduino Uno or similar (ATmega328P @
16 MHz), the Arduino core normally configures the ADC prescaler to 128.
This gives a conversion time of 104 µs (equal to 13 × prescaler ÷
F\_CPU), and a maximum sample rate of about 9.6 kHz. This is fine for
telephone quality audio, but insufficient for hi-fi applications. This
example code sets the prescaler to 32 for a conversion time of 26 µs and
a maximum sample rate around 38 kHz. According to Atmel, the ADC should
work fine with this kind of sample rate, except that you should not
expect to get the full resolution.

The main reason, however, is not to get a _fast_ sample rate, but rather
to get a _consistent_ sample rate. The problem with `analogRead()` is
that it is a _blocking_ function. If you look at its source code you
will see a busy wait like this:

 // ADSC is cleared when the conversion finishes
 while (bit_is_set(ADCSRA, ADSC));

This means that the CPU is not doing anything useful while waiting for
the ADC to finish the conversion. If you do `analogRead()` in a loop,
the CPU will wait for the ADC, then the ADC will be idle while the CPU
completes the loop and so on. The conversion period is then the time
required by the ADC _plus_ the time taken by the CPU to loop. And the
CPU time is hard to predict because it can be influenced by interrupts
and by conditional branches inside the loop.

This code, in contrast, configures the ADC to work in _free running
mode_. In this mode, the ADC starts a new conversion as soon as the
previous one is done. This way you get a steady sample rate while the
ADC and the CPU work in parallel. In the loop you see these lines:

    while(!(ADCSRA & 0x10)); // wait for adc to be ready
    ADCSRA = 0xf5; // restart adc

The comments are a bit misleading. The first line (which I would rather
write `loop_until_bit_is_set(ADCSRA, ADIF);`) waits for a flags that is
set when the current conversion is done and the data register updated.
The next line does not restart the ADC (it restarted itself, as it is in
free running mode): it only clears the flag so that it can be
meaningfully tested on the next iteration.

Now, I have a few comments on this code that are not directly related to
your question, but may be useful if you are going to build your program
on this basis.

First, it should be noticed that the whole ADC-reading loop is done with
interrupts disabled. This is _not_ normally needed, as the free running
mode gives you a steady sampling even if the CPU timing is somewhat
jittery. The only valid reason I see for disabling interrupts is if
one of your ISRs takes so long to execute that you may miss one sample.
This could very well be the case with such a high sampling frequency.
But still, there is no point in keeping the interrupts disabled during
the FFT processing. And there is no point in turning off Timer 0 if you
are disabling interrupts anyway.

My second point is about the three lines starting with `byte m = ADCL;`.
Those are meant to read the ADC data register in the proper order: low
byte first. However, the C compiler is well aware of the proper way to
do read a 16-bit I/O register (see “Accessing 16-bit Registers” in the
datasheet chapter about Timer 1). Thus, these three lines can be
simplified to just `int k = ADC;`.

My last point is that having the CPU left adjust the result (`k <<= 6`)
takes some time, as it is implemented as a loop. There is no point in
doing this when the ADC can do it for free: you just have to set the
ADLAR bit when configuring ADMUX in `setup()`. Then the 5 lines starting
with `byte m = ADCL;` would be reduced to

    int k = ADC - 0x8000;  // ADC reading as a 16 bit signed int


message:
Mysterious behavior when using objects

I am writing a project that involves using complementary filters to combine gyroscope and accelerator readings in 3 directions. The relevant code is below.

    class CompFilter {
     public:
       long prevTime;
       float alpha;
       int angle;

       CompFilter(float Alph);
       int combine (float gyroRate, float accelAngle);
    };

    CompFilter::CompFilter(float Alph) {
     alpha = Alph;
     prevTime = 0;
     angle = 0;
    }

    int CompFilter::combine(float gyroRate, float accelAngle){
      Serial.println("Here THREE");

     long timeStep = millis() - prevTime;
     if (timeStep == 0) { timeStep = 1;}

     angle = alpha * (angle + gyroRate * timeStep);

     angle += (1.0 - alpha) * accelAngle;

     prevTime = millis();

     return angle;
    }

    //Global Objects
    CompFilter *senPitch; CompFilter *senRoll;  //Declare Complementary Filters

    //Adjustable Parameters
    float alpha = .5;   //Constant affecting Gyro's vs. Accel's influence on sensor reading

    void setup(void)
    {
      //Open Data Channel
      Serial.begin(115200);
      Serial.println(F("IMU Complementary Filter Tester")); Serial.println("");

     //Initialise TMU sensors
     sensorInit(accel, mag, gyro);
     senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha);
      Serial.println("HERE ONE");
    }

    void loop(void)
    {
     //Variables for reading sensors
     sensors_event_t accel_event, mag_event, gyro_event;
     sensors_vec_t   orientation;

     // Retrieve Sensor Readings
     accel.getEvent(&accel_event);
     gyro.getEvent(&gyro_event);
     mag.getEvent(&mag_event);

     Serial.println("HERE TWO");

     int anglePitch = senPitch->combine(gyro_event.gyro.y, orientation.pitch);
     int angleRoll = senRoll->combine(gyro_event.gyro.x, orientation.roll);
   }

I had to keep track of a couple of pieces of information for each direction, so rather than trying to use parallel arrays, I created a CompFilter class. I think I am using the correct syntax in the class and constructing the object, but I am getting very unusual outputs from Serial.print().

    RE ONE
    RE TWO
    Here THREE
    Here THREE
    entary Filter Tester

Depending on how I fiddle with the code, I can get setup() repeating over and over or loop() running once before silently failing.

I suspect that I have misdirected a pointer somewhere, but I am not sure. I would appreciate any help.

body:
Dave X is absolutely right.

I never assigned the senRoll pointer to an object. Then when I tried to dereference it, it went to some random address. I guess there are very few memory protections, so rather than causing a seg fault it just caused erratic behavior.

Thanks for the help.


message:
How to upload a sketch via Arduino Nano

I have two Nano boards, but the first one seems the CH340 chipset was burn. :( ,

 1. Nano v3, CH340 chipset but unable to identify after connect to my Mac using USB
 2. Nano v3, FTDI chipset and in good condition
 3. USB to Serial module, using FTDI chipset

I am trying to upload a sketch via a USB-to-Serial module OR another Nano board (or UNO board v3) to my CH340 Nano Board.

**Question:**

 1. How to wire them up?
 2. Is it need upload a "Arduino as ISP" first?
 3. step-by-step tutorial or website talking about this ??

body:
I presume you have boot loader on your Nano, so you can use your USB to serial, just wire (D0)TX->RX(USB), (D1)RX->TX(USB), GND-GND and supply power to the target Nano. You will need to reboot Nano just before the uploading the code. Uploading is same as usual.

Using other Arduino as ISP needs more wires as well as 2nd Arduino, so i would use above method.


body:
Check this video [https://www.youtube.com/watch?v=0zuRukW7o0A][1]

- Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
- Open Terminal from Recovery mode
- Run the command csrutil enable --without kext
- Reboot
- Install driver

  [1]: https://www.youtube.com/watch?v=0zuRukW7o0A


message:
Arduino CAN SPI Configuration problem

I am using an Arduino UNO along with a Cooking Hacks CAN Bus Module and Multiprotocol Radio Shield. The CAN module is connected to the radio shield which is plugged into the Arduino. I got this radio shield keeping future applications in mind where I can combine multiple protocols, for eg. CAN and Bluetooth.

I connected them through an OBD2-DB9 cable to the car's OBD port but noticed that I was not really getting any messages. Well I am getting messages but just:

       -- Constructor Can(uint16_t speed) --
       SPI configured
       The MCP2515 has been successfully reset, configuration mode activated
       Speed=500kps
       -- End Constructor Can(uint16_t speed) --

       Data in buffer 0
       id: 7FF  rtr: FFFFFFFF => Data in buffer 0
       id: 7FF  rtr: FFFFFFFF => Data in buffer 0
       id: 7FF  rtr: FFFFFFFF => Data in buffer 0

After analysing the connections, I realised that the hardware is probably fine since the continuity between the pins of the cables is fine and the CAN module(MCP2515 + MCP2551) is receiving power and I also checked the voltages at the pins and think they're mostly fine apart from a few pins which I'm not sure about. Which brings me to the software issue. I can see that the SPI is not getting configured properly and the MCP2515 controller doesn't enter configuration mode which means the bit times defined are not being used and hence the controller is not initialising like it should. I even tried manually changing to configuration mode by changing the values of the REQOP bits of the CANCTRL register as opposed to doing a software reset which was how I was doing it initially. Even then, no luck. To verify the SPI connection, I chose a random read/write control register like BFPCTRL and wrote a value to it and then read it back to verify that it matched the values I wrote. However, the value read back is not the same as the value I wrote. Also, the controller only has trouble going into configuration mode. It seems to change to normal and listen only mode without problem since the CANSTAT register displays the correct values for the REQOP bits. I don't understand why the controller has problem entering configuration mode but no problem changing to the other modes. Can anybody help me?

SPI Code:

        bool CAN::begin(uint16_t speed)
        {
        #if (DEBUGMODE ==1 )
        Serial.println("-- Constructor Can(uint16_t speed) --");
        #endif

        //Initialization SPI
        SPI.begin();
        SPI.detachInterrupt();
        SPI.setBitOrder(MSBFIRST);
        // both mode 0 & 3 should work
        SPI.setDataMode(SPI_MODE0);

        //Set the SPI frequency
        SPI.setClockDivider(SPI_CLOCK_DIV4);

        #if (DEBUGMODE==1)
        Serial.println("SPI configured");
        #endif

        //Configure MCP2515 pins
        pinMode(CAN_CS,OUTPUT);
        pinMode(CAN_INT,INPUT);
        digitalWrite(CAN_CS,HIGH);

        writeRegister(BFPCTRL, (1<<B0BFM) | (1<<B1BFM));
        int dat = readRegister(BFPCTRL<<2);
        Serial.println(dat);

        //Software resets MCP2515
        reset();
        delay(100);
        //After the reset, controller enters configuration mode
        dispMode();

When I read back the values of B0BFM and B1BFM bits, they should be 1 but the display says that their values are 0.

       void CAN::writeRegister( char direction, char data )
       {
       //CS low to select the MCP2515
       digitalWrite(CAN_CS,LOW);

      SPI.transfer(SPI_WRITE);
      SPI.transfer(direction);
      SPI.transfer(data);

      //CS line again to release
      digitalWrite(CAN_CS,HIGH);
       }

      char CAN::readRegister(char direction)
      {
      char data;
      //CS low to select the MCP2515
      digitalWrite(CAN_CS,LOW);

      SPI.transfer(SPI_READ);
      SPI.transfer(direction);
      //Read data SPI
      data = SPI.transfer(0xff);

      //CS line again to release
      digitalWrite(CAN_CS,HIGH);
      return data;
      }

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

body:
In SPI protocol you'll need to read the SPI buffer twice because the data you wrote will be read by the IC and the IC will respond to it in the next communication and that's when you know.

Also, by looking at the message, I see that your IC is working fine, but is your CAN bus initialised properly? I'm a FSAE team member and I've faced this issue with the CAN Bus termination resistances and the ODB-II configuration on the Sparkfun CAN Bus shield.

Also, have you tried any other libraries for the CAN Shield? For me the seeedstudio library of their CAN shield worked very well.


message:
Error: invalid types 'int[int]' for array subscript

I am trying to get an Arduino to work with some Adafruit Motor shields.
Everything seemed to work fine, but when I tried to create a function, I get the error in the subject. As far as I can tell, everything was declared properly (the array is initialized and is indexed elsewhere with without issue). Only the function seems to cause an issue.

Would anyone have a guess at what's wrong?

        //////// Imports
        #include <Wire.h>
        #include <Adafruit_MotorShield.h>
        #include "utility/Adafruit_PWMServoDriver.h"

        ////////My globals. Times are in milliseconds
        unsigned long currentTime = 0;
        unsigned long elapsedTime = 0;
        unsigned long startTime = 0;
        byte currentMotor = 1;
        byte currentShield = 1;
        byte motorRunning = 0;

        //// Settings

        // How many seconds between motors
        unsigned long endTime = 4000;

        // How many shields and motors per shield
        const int nShields = 1;
        const int nMotorsPerShield = 3;

        /////////MicroManager globals
        unsigned int version_ = 2;
        const unsigned long timeOut_ = 1000;
        byte currentPattern_ = 0;
        unsigned long time;

        /////////Adafruit globals
        Adafruit_MotorShield afms[nShields];
        Adafruit_DCMotor *motor[nShields][nMotorsPerShield];

        ////////////Setup
        void setup() {
          Serial.begin(57600);

          unsigned char address = 96;

          for (int i = 0; i < nShields; i++) {
            afms[i] = Adafruit_MotorShield(address);
            address = ++address;
            afms[i].begin();
          }

          for (int i = 0; i < nShields; i++) {
            for (int j = 0; j < nMotorsPerShield; j++) {
              motor[i][j] = afms[i].getMotor(j + 1);
              motor[i][j]->setSpeed(255);
            }
          }

          pinMode(13, OUTPUT);
        }

        ////////////////////Main
        void loop() {
          currentTime = millis();
          elapsedTime = currentTime - startTime;

          if (elapsedTime > endTime) {
            startTime = currentTime;
            currentMotor = currentMotor + 1;
            if (currentMotor > nMotorsPerShield) {
              currentMotor = 1;
            }
          }

          if (Serial.available() > 0) {
            int inByte = Serial.read();

            switch (inByte) {
              case 1:
                if (waitForSerial(timeOut_)) {
                  currentPattern_ = Serial.read();
                  if (currentPattern_ == 0) {
                    for (int i = 0; i < nShields; i++) {
                      for (int j = 0; j < nMotorsPerShield; j++) {
                        motor[1][j]->run(RELEASE);
                      }
                    }
                  }
                  else {
                    switchMotor();
                  }
                  Serial.write( byte(1));
                  digitalWrite(13, HIGH);
                }
                break;

              case 30:
                Serial.println("MM-Ard");
                break;

              case 31:
                Serial.println(version_);
                break;
            }
          }

          digitalWrite(13, LOW);
        }

        ////////////////Function definitions

        bool waitForSerial(unsigned long timeOut)
        {
          unsigned long starTime = millis();
          while (Serial.available() == 0 && (millis() - starTime < timeOut) ) {}
          if (Serial.available() > 0)
            return true;
          return false;
        }

        void switchMotor()
        {
          int shield = currentShield - 1;
          int motor = currentMotor - 1;
          for (int i = 0; i < nShields; i++) {
            for (int j = 0; j < nMotorsPerShield; j++) {
              if (i == shield && j == motor)
                motor[i][j]->run(FORWARD);
              else
                motor[i][j]->run(RELEASE);
            }
          }
        }

body:
Take a close look at this line:

    motor[1][j]->run(RELEASE);

Looks like it should be:

    motor[i][j]->run(RELEASE);

Otherwise it is an illegal index (as there is only one shield).

The next error is in the function switchMotor(). Again, have a close look at the definition of "motor". There is a local variable with that name but you want to also access the global array with the same name.

    void switchMotor()
    {
      int shield = currentShield - 1;
      int motor = currentMotor - 1;
          ^
      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          if (i == shield && j == motor)
            motor[i][j]->run(FORWARD);
            ^
          else
            motor[i][j]->run(RELEASE);
        }
      }
    }

My guess is that this is where the compiler give you the error message!

Cheers!


body:
I get a warning flag in UECIDE for the line:

    address = ++address;

> ‣ operation on 'address' may be undefined [-Wsequence-point]

Increment address, and then assign the new value from address into address.  That seems a bit odd to me.  I think you just meant to increment:

    address++;

Or

    address = address + 1;

Also it flags up the `1` instead of `i` that Mikael found:

> ‣ array subscript is above array bounds [-Warray-bounds]

And of course there is the (somewhat hard to spot - Kudos to Mikael for finding it - it took me a bit to see it myself) naming conflict:

> ‣ invalid types 'int[int]' for array subscript

It was only when I used the advanced editing facilities of UECIDE to highlight all occurrences of `motor` that I found there was extra ones that shouldn't have been there causing the problem.

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

So just changing the integer variable name from `motor` to something else fixes it:

    void switchMotor()
    {
      int shield = currentShield - 1;
      int thismotor = currentMotor - 1;       // RENAMED MOTOR
      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          if (i == shield && j == thismotor)  // RENAMED MOTOR
            motor[i][j]->run(FORWARD);
          else
            motor[i][j]->run(RELEASE);
        }
      }
    }

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


message:
Need help debugging my Binary Clock

I have tried everything but I can't get my binary clock to display correctly. The diagram and code are here: [Binary Clock | Electronics Lab][1].

The hardware is based off this (it also explains the process that my program is trying to do): [DIY: Binary Clock with Arduino][2]. The problems lie in a, probably, simple error as my variable `tempTime`, which is used to convert the individual digits to their binary equivalent, does not change when I tell it to. All this occurs in the display function. (Sorry, I'm new Here and only a high school student)

While debugging it I realized that the only problem is the variable `tempTime` - the hardware and other functions work as they were intended.
Can anyone help? (Sorry if this is not very well documented).

  [1]: https://123d.circuits.io/circuits/1586601-binary-clock
  [2]: http://www.danielandrade.net/2008/07/15/binary-clock-with-arduino/

        int digitPins[4][4] = {{13,6,-1,-1},{12,7,3,1},{11,8,4,-1},{10,9,5,2}};
    int time[4] = {0,0,0,0};
    int steps[4]={1,2,4,8};
    int tempTime = 0;
    void setup(){
      for(int x = 0; x < 4; x++){
        for(int y =0; y<4; y++){
        pinMode(digitPins[x][y],OUTPUT);
        }
      }
     Serial.begin(9600);
       convertHour(12);
       convertMinute(57);
      Serial.println("The time is:");

      for(int z = 0; z < 4; z++){
        if(z == 2){
        Serial.print(":");
        }
      Serial.print(time[z]);
      }
      display();
    }
    void loop(){

    }
    void display(){
      int displayer[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
    /*
    0 - Hour
    1 - Hour
    2 - Minute
    3 - Minute
    4 - Hour(Total)
    5 - Minute(Total)
    */

      int counter1 = 0;
      for(int i = 0; i < 4; i++){ //Loop for the individual digits
        tempTime = time[i];
        if(tempTime >= 10){
        tempTime = tempTime % 10;
        }
        Serial.print("\nBegining new iteration i = ");
        Serial.print("\nStarting with digit: ");
        Serial.print(tempTime);
        Serial.print(i);
        Serial.println("");
        for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
          if(time[i]/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
            Serial.print("\n");
            Serial.print(time[i]);
            Serial.print("/");
            Serial.print(steps[j]);
            Serial.print(" = ");
            Serial.print(time[i]/steps[j]);
           tempTime =tempTime - (time[i]*steps[j]);
            displayer[counter1] = digitPins[i][j];
            Serial.print("\nAdded: ");
            Serial.print(digitPins[i][j]);
            counter1++;
          }
        }

      }
      clear();
      for(int a = 0; a < 13; a++){
      digitalWrite(displayer[a],HIGH);
      }
    }
    void clear(){
      for(int x = 0; x < 4; x++){
        for(int y =0; y<4; y++){
        digitalWrite(digitPins[x][y],LOW);
        }
      }
    }
      void convertHour(int value){
        int digits[] = {0,0};
        if(value >= 10){
         debug("Bigger than 10");
           if(value >= 20){
            digits[0] = 2;
            }else{
             digits[0] = 1;
            }
        }
        digits[1] = value - (digits[0] * 10);
        //String hour = digits[0]+""+digits[1];
        //Serial.print(digits[0]);
        //Serial.print(digits[1]);
        time[0] = digits[0];
        time[1] = digits[1];
      }
    void convertMinute(int value){
      int digits[2] = {0,0};
      int val = value;
      if(value >= 10){
       digits[0] = val/10;
      }
      digits[1] = value - (digits[0] * 10);
      Serial.print("\n");
      Serial.print(digits[0]);
      Serial.print(digits[1]);
      time[2] = digits[0];
      time[3] = digits[1];
    }
      void debug(String value){
        boolean de = true;
        if(de){
        Serial.println(value);
        }
      }

body:
In your “Loop to determin the arrangement”, you are erroneously using
`time[i]` in several places where you mean `tempTime`. Also, to update
`tempTime` you only have to subtract `steps[j]`. With these fixes, your
loop becomes:

    for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
      if(tempTime/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
        Serial.print("\n");
        Serial.print(tempTime);
        Serial.print("/");
        Serial.print(steps[j]);
        Serial.print(" = ");
        Serial.print(tempTime/steps[j]);
        tempTime = tempTime - steps[j];
        displayer[counter1] = digitPins[i][j];
        Serial.print("\r\nAdded: ");
        Serial.print(digitPins[i][j]);
        counter1++;
      }
    }

Now, if you learn a little bit about how binary numbers work, and about
the binary operators in C and C++, you can rewrite your loop in a
simpler form:

    for (int j = 3; j >= 0; j--) {
      int weight = 1 << j;      // 2 raised to the power j
      if (tempTime & weight) {  // if bit j of tempTime is set
        displayer[counter1++] = digitPins[i][j];
        Serial.print("Added bit ");
        Serial.print(j);
        Serial.print(", weight ");
        Serial.print(weight);
        Serial.print(", output ");
        Serial.println(digitPins[i][j]);
      }
    }

As a side note, it is considered good practice to print a new line at
the _end_ of each string you print (using `println()`), rather than at
the beginning.

**Edit**: As your `display()` function is way too complex for what it
does, I did not resist the temptation to simplify it:

    void display() {
      for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4 && digitPins[i][j] >= 0; j++)
          digitalWrite(digitPins[i][j], time[i] & (1<<j));
    }


message:
Since double and float represent the same data type (usually), which is preferable?

It looks like on ATMega based boards, `float` and `double` are equivalent 32-bit (4-byte) data types.

However, on the Arduino Due, `doubles` are 64-bit (8-byte) where `floats` are 32-bit (4-byte), same as the ATMega boards.

I also saw one source on avr-gcc that listed `double` as non-standard.

So, when writing code for ATMega based boards are `floats` preferable to using `doubles`, since that would make the code equivalent for Due boards? Or are `doubles` preferable for any reason?

body:
See [avr-gcc](https://gcc.gnu.org/wiki/avr-gcc)

> Deviations from the Standard
>
>**double**
>
>    double is only 32 bits wide and implemented in the same way as float

---

>  when writing code for ATMega based boards ...

They are the same, therefore.

---

*(Edited to add)*

> When writing code, is it then preferable to using one over the other?

I don't really understand your question. You asked about writing code for the ATMega based boards. Do you really mean, if you are writing code for the Due? The quick answer would be, on the Due, double takes twice the RAM, however it is over twice as precise - around 7.2 decimal digits for float compared to 15.9 for double. (I'm not sure about the speed, probably double would be slower, unless it is implemented in floating-point hardware - however I cannot see any reference to that on the AT91SAM3X8E datasheet).

See: <https://en.wikipedia.org/wiki/Floating_point>

If you want more precision (however slower and taking more RAM) then you could use `double` - which won't make any difference on the ATmega based boards, but will on the Due.

---

As Edgar Bonet said:

> I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect.

That makes quite a bit of sense.

---

I warn you though that "preferable" is subjective. It is close to asking "what is best"? To which the reply is: "best for what?"


body:
Neither are preferable.

Unless your microcontroller has a hardware floating point unit using float or double results in huge overheads for your program.

So instead use integer mathematics whenever possible.

Instead of working in Volts, work in millivolts, for example.

However, if your MCU does have an FPU, and some modern more powerful ones do, then you should use the size of float or double that is native to the FPU. If it is a 32 bit FPU then use float. If it is a 64 bit FPU then you can use double.


message:
Arduino Hardware Issue

I have two Arduino Uno R3 boards and both of them now seem to have an issue. There's a micro sized 8 Pin chip near the dc power port. This seems to get incredibly hot (i managed to get a blister from touching it) and the "L" Led seems to stay dimly lit even when the reset button is pressed.

The Arduino Uno was working fine during operation and only started giving me this problem recently, i cant seem to find any visible short or loose terminal on the board.

I can see that the reset function is being used as my LCD does reset.
Would anyone have a reason for this mysterious issue?

body:
There are two issues here:

* The "L" LED lighting. On the R3 Uno this is driven by an op-amp and if pin 13 is "floating" the op-amp may, or may not, turn the LED on. So this is normal.

* The 8-pin chip near the power plug getting very hot. This is definitely not normal. You must be consuming a lot of current to do that. You could try measuring it. A Uno running an "empty" sketch should be consuming around 50 mA. Note that this chip is the op-amp mentioned in my first point. Possibly you have damaged it. Did you connect an LED (or motor) or similar to pin D13? If so, what current-limiting precautions did you take?

---

* Try running an empty sketch (or the Blink sketch) with no hardware connected to the board, to see if it still happens.

* Try measuring the power consumption, if possible, with a meter measuring the input through the 5V pin, if you have a 5V power supply you could use for this.

* Are these genuine boards, or cheap clones from eBay?


message:
Arduino Infinity Loop

I'm new to this Arduino programming. So I want to ask about my current project. My lecturer told me to make a temperature sensor using an LM35, where a green LED will light up when below some certain temperature that I set. The same goes for yellow and red LEDs for medium, and high temperatures. The tricky part here is that I need to make sure my buzzer (piezo) is on forever if it reaches the high temperature, until I press a button to reset it.

This is my coding so far:

<!-- language: c -->

    const int greenLed = 3;
    const int redLed = 4;
    const int yellowLed = 5;
    float tempC;
    int reading;
    int tempPin = 0;
    int speakerOut = 11;
    const int buttonPin = 2;
    int buttonState = 0;
    long duration = 10000;
    int tempo = 0;

    void setup() {
    // initialize digital pin 13 as an output.
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(2, INPUT);
    pinMode(11, OUTPUT);
    analogReference(INTERNAL);
    Serial.begin(9600);
    }

    // the loop function runs over and over again forever
    void loop() {
    buttonState = digitalRead(buttonPin);
    reading = analogRead(tempPin);
    tempC = reading / 9.31;
    Serial.println(tempC);
    delay(500);

    if (tempC < 30.00) {
    //Serial.println("Temp LOW");
    digitalWrite(3, HIGH);
    delay(10);
    }else {
    digitalWrite(3,LOW);
    delay(10);

    }

    if (31.00 < tempC < 33){
    //Serial.println("Temp MED");
    digitalWrite(4,HIGH);
    digitalWrite(5,LOW);
    delay(50);
    digitalWrite(4,LOW);
    digitalWrite(5,HIGH);
    delay(50);

    }else {
    digitalWrite(4,LOW);
    digitalWrite(5,LOW);

    }

    if(tempC >= 34){
    **WHAT SHOULD I FILL UP HERE TO MAKE SURE MY PIEZO BUZZER ON FOREVER**
    }
    if(buttonState = 1);{
    digitalWrite(11, LOW);
    }
  }

Any help would be great. Or if you have a better idea on how to do this, I'm gonna love it.

body:
You can use the [toneAC][1] library, which allows even better handling of piezo speakers then the standard "tone"-functions.

> **Features:** Nearly twice the volume (because it uses two out of phase pins in push/pull fashion)
    Higher quality (less clicking)
    Capability of producing higher frequencies (even if running at a lower clock speed)
    Nearly 1.5k smaller compiled code
    Bug fixes (standard tone library can generate some odd and unpredictable results)
    Can set not only the frequency but also the sound volume
    Less stress on the speaker so it will last longer and sound better

With the library you can do something like:

    int freq = 1000
    int vol = 10
    int length = 0
    boolean background = true

    toneAC(freq, vol, length, background);

The tone now will play forever in the background, until you stop it with:

    toneAC(0);

  [1]: http://playground.arduino.cc/Code/ToneAC


body:
1. The answer is simple add

        digitalWrite(speakerOut,HIGH);

2. Common mistake made by beginners is to use assign operator instead of compare operator

        if(buttonState=1)

    should actually be

        if(buttonState==1)

3. Never pull that pin LOW

        if(buttonState = 1);{
        digitalWrite(11, LOW);
        }

    is wrong use the below code

        if(buttonState == 1){
            digitalWrite(11, LOW);
        }

Don't forget to connect the button to buttonPin or you will get random HIGH or LOW from that pin since its floating

Hope this helps.


message:
Another traffic light project

I have a school project, where I'm going to make a traffic light system on a pls. I want to try it out on an Arduino first, just to get the hang of it.

To make it a little bit more advanced than I have found on the internet, I want to make the lights go in "emergency mode" if the green lights in both directions are on at the same time. It will then go into a yellow blink.

My idea is something like this:

<!-- language: c -->

    // Yellow blinking if fault in the system or operator activates it
    int killState = digitalRead(Kill);
    int resState = digitalRead(Res);
    if (killState == HIGH /*|| greenlights in both directions */) {
     while (resState == LOW;) { // Yellow blink as long as system is not reset
      BLINK();
     }
    }

I guess I need a variable or two that tells what state the lights are in, but I'm stuck. Any good solutions out there?

Another thing is the reset button. I haven't put much effort in it, but I want it to go into the starting point.

The link to the complete script can be found [here.][1]

  [1]: https://www.dropbox.com/s/evygp3w2gwvtxm9/lyskryss_v2.ino?dl=0

body:
For starters, take a close look at this line:

    while (resState == LOW;)

That is not the correct syntax. But the real issue is how is this while loop terminated? The value is never set again?

Cheers!


body:
You could do something simple to test if both red and green are on,  eg.

    if (digitalRead (RED_PIN) == HIGH && digitalRead (GREEN_PIN) == HIGH)
      {
      digitalWrite (RED_PIN, LOW);  // turn off red
      digitalWrite (GREEN_PIN, LOW);  // turn off green
      while (true)
        {
        digitalWrite (YELLOW_PIN, HIGH);
        delay (500);
        digitalWrite (YELLOW_PIN, LOW);
        delay (500);
        }  // end of while
      }  // end of it

---

If you have other questions please post your code and not a [snippet](http://snippets-r-us.com/) - however I suggest you try to get further on your own. This is obviously an exercise, and the more you try to work it out yourself the more you will learn.


message:
Trying to read a 93lc46b chip using Arduino

I am trying to read a 93lc46b EEPROM chip using Arduino. I am reusing the code from http://owlsan.blogspot.de/2012/10/accessing-93c4693c46n-serial-eeprom.html, except I have modified it for 93lc46b chip, plus I am using Arduino Uno and not Arduino Mega. The problem I am facing is, I get different set of bytes every time I try to read 93lc46b EEPROM chip. I doubt this might be some garbage data. Can you please explain me what and where exactly I am doing something wrong. The modified code snippet is as follows:

<!-- language: c -->

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

    #define CLEAN 0b00000000

    #define DDR93LC46B  _SFR_IO8(0x04)
    #define PORT93LC46B _SFR_IO8(0x05)
    #define PIN93LC46B  _SFR_IO8(0x03)

    #define SK 13
    #define DO 12
    #define DI 11
    #define CS 10

    #define READ 0x02

    #define SET_CS PORT93LC46B |= (1 << CS)
    #define CLR_CS PORT93LC46B &= ~(1 << CS)

    #define SET_SK {PORT93LC46B |= (1 << SK); _delay_us(0.01);}
    #define CLR_SK PORT93LC46B &= ~(1 << SK)

    #define SET_DI PORT93LC46B |= (1 << DI)
    #define CLR_DI PORT93LC46B &= ~(1 << DI)

    class SPI_93LC46B {
      private:
        uint8_t Transfer(uint8_t data) {
          SPDR = data;
          while(!(SPSR & (1 << SPIF))); // Wait for SPI interrupt flag
          return SPDR;                  // Return byte gathered from SPI data register
        }
        void Opcode(uint8_t opcode, uint8_t address) {
          SET_CS;
          SPCR &= ~(1 << SPE);               // SPI disable
         _delay_us(1);
          CLR_SK;
          SET_DI;                            // Send start bit
          SET_SK;
          CLR_SK;
          SPCR |= (1 << SPE);         // SPI enable
          Transfer((opcode << 6) | address); // Transmit byte
        }
      public:
        SPI_93LC46B() {
          SPCR =    CLEAN        // Set SPI control register
             & ~(1 << SPIE)  // SPI interrupt disable
             |  (1 << SPE)   // SPI enable
             & ~(1 << DORD)  // MSB first
             |  (1 << MSTR)  // SPI master device
             & ~(1 << CPOL)  // SPI
             & ~(1 << CPHA)  //  mode 0
             |  (1 << SPR1)  // XX/64 MHz
             & ~(1 << SPR0); //  speed
          SPSR =    CLEAN         // Init SPI status register
             & ~(1 << SPI2X); // SPI double speed
          DDR93LC46B =    CLEAN      // Set up inputs/outputs
                 |  (1 << SK)  // Serial clock output
                 |  (1 << DI)  // Data input (MOSI) output
                 |  (1 << CS)  // Chip select output
                 & ~(1 << DO); // Data output (MISO) input
          PORT93LC46B |= (1 << DO); // Data output (MISO) high
          CLR_DI;
          CLR_CS;
          CLR_SK;
         _delay_us(1);
        }
        ~SPI_93LC46B() {
          //
        }
        uint16_t Read(uint8_t address) {
          uint16_t data = 0;
          Opcode(READ, address);
          CLR_DI;
          SET_SK;
          CLR_SK;
          SPCR |=  (1 << CPHA);
          data = Transfer(0);
          data = (data << 8) | (Transfer(0));
         _delay_us(1);
          CLR_CS;
          CLR_DI;
          SPCR &= ~(1 << CPHA);
          return data;
       }
    };

    void setup(void) {
      Serial.begin(115200);
      _delay_ms(100);
      Serial.println("EEPROM writing/reading");
    }

    void loop(void) {
      Serial.println("new round");
      SPI_93LC46B _93LC46B;
      int i;
      uint16_t data;
      for(i = 0; i < 64; i++) {
        data = _93LC46B.Read(i);
        _delay_ms(50);
        Serial.print(data, HEX);
        Serial.print(" ");
        if((i + 1) % 8 == 0)
          Serial.println();
      }
      _delay_ms(10000);
    }

body:
This code is over complicated and has a lot of errors. Let us start with the obvious. Look closely at this section. Do you see the error(s)?

    #define SK 13
    #define DO 12
    #define DI 11
    #define CS 10

    #define READ 0x02

    #define SET_CS PORT93LC46B |= (1 << CS)
    #define CLR_CS PORT93LC46B &= ~(1 << CS)

    #define SET_SK {PORT93LC46B |= (1 << SK); _delay_us(0.01);}
    #define CLR_SK PORT93LC46B &= ~(1 << SK)

    #define SET_DI PORT93LC46B |= (1 << DI)
    #define CLR_DI PORT93LC46B &= ~(1 << DI)

The symbols SK, D0, DI, CS seem to be pin numbers but look how they are used in the SET_XX and CLR_XX macros. That is very wrong. They should be the bit numbers in the PORT register instead.

There is more. How about this?

    _delay_us(0.01);

What is the intention? _delay_ns(10)??? In any case yet another error.

Cheers!


message:
Arduino Nano no output on any controllable pins except for RX and TX pins

I have 2 Arduino Nanos which don't output anything on any controllable pins except for RX and TX pins. I used an LED which I have tested works on the 3.3v/GND and 5.0v/GND. When I try to control the RX and TX pins (1 and 2) the LED lights up on the board and the external LED I am using to test. I am using the example "Blink" program to test it, and I've tried it on both nanos. I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything. Why isn't it working?

        /*
      Blink
      Turns on an LED on for one second, then off for one second, repeatedly.

      This example code is in the public domain.
     */

    // Pin 13 has an LED connected on most Arduino boards.
    // Pin 11 has the LED on Teensy 2.0
    // Pin 6  has the LED on Teensy++ 2.0
    // Pin 13 has the LED on Teensy 3.0
    // give it a name:
    int led = 26;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
    }

body:
> I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything.
>
> No, the LED doesn't need a resistor ...
>
> because I tested it with the 5v and 3.3v therefore higher voltages doesn't blow it up

---

Sounds to me like you have damaged your output pins. Read [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html) by Mike Cook.

The LED may briefly light up, but without a resistor you are damaging both the LED and the output pin. It is no surprise then, that afterwards the pins "none output anything".

Without a limiting resistor the output driver on the Arduino is overloaded and may burn out. Whether you have damaged the LED, the pin, or both, is hard to say.

---

*(Edited to add)*

> still doesn't work on pins that I haven't used ...

Can you slow down a bit?

> I've tested pins 26 (serial) ...

There is no pin 26 from the IDE point of view. On the board pin 26 is A7 (analog input 7) which **cannot be used for digital input/output**.

Please specify exactly what pin you tried (just choose one) and stick to the Arduino number (printed on the board, eg. D05) and then show the code you used to access that pin.

---

> According to this ... the analogue pins can be used just the same as digital pins

That page shows a Uno. You have a Nano.

See [Arduino Nano - Arduino.cc](https://www.arduino.cc/en/Main/ArduinoBoardNano). On that page:

> Analog pins 6 and 7 cannot be used as digital pins.


body:
No, the LED doesn't need a resistor ...

That is correct, but the processor I/O - output pin - does.
Check the schematic to see how RX /TX LEDs are connected.


message:
Double ## in macros

I was looking at some macro use in an Arduino code. I believe what this macro does is it expands into a state that basically sets a pin to either input or output, but I'm a little confused about everything going on in this macro.

I do understand the point behind the do{...} while(0), but I'm sure what the ## are accomplishing. Also, what if anything do the underscores before DDR and PIN do? I would very appreciative of a simple clarification. Thank you!

    #define MASK(PIN)  (1 << PIN)

    /// set pin as input
    #define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)
    /// set pin as output
    #define _SET_OUTPUT(IO) do {DIO ##  IO ## _DDR |=  MASK(DIO ## IO ## _PIN); } while (0)

body:
`##` is the concatenation operator in macros. It joins two macros or pieces of text together when expanded.

    #define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)

    _SET_INPUT(3);

woukd expand to:

    do {DIO3_DDR &= ~MASK(DIO3_PIN); } while (0);

You can read more about how it works here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html


message:
How to perform action if two rfid tag UIDs have been detected?

I'm using an rfid-rc522 and I want to print to the serial a string of text if two rfid tags have been read in a given time period.

Essentially this:

 1. First tag is read (print to serial: Tag 1 has been read)

 2. Wait 2 seconds

 3. Second tag is read (print to serial: Tag 2 has been read)

 4. Print to serial: Tag 1 and Tag 2 has been read)

 5. Bonus: Keep this state - and then when a button is pressed (print to serial: Tag 1 and Tag 2 are finished)

I know how to read the UID and print to the serial if one is read.
Thank you so much for your help, it's greatly appreciated.

Here is my code so far:

    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_ST7735.h> // Hardware-specific library
    #include <SPI.h>
    #include <MFRC522.h>

    // For the breakout, you can use any 2 or 3 pins
    // These pins will also work for the 1.8" TFT shield
    #define sclk 4  // SainSmart: SCL
    #define mosi 5  // SainSmart: SDA
    #define cs   6  // SainSmart: CS
    #define dc   7  // SainSmart: RS/DC
    #define rst  8  // SainSmart: RES

    Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk, rst);

    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN);

    float p = 3.1415926;

    void setup(void) {
      Serial.begin(9600);
      SPI.begin();
      Serial.print("Starting cornhole leaderboard...");
      mfrc522.PCD_Init(); // Init MFRC522 card
      Serial.println("Scan PICC to see UID and type...");
      // Use this initializer if you're using a 1.8" TFT
      tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

      // Use this initializer (uncomment) if you're using a 1.44" TFT
      //tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab

      Serial.println("Initialized");

      uint16_t time = millis();
      tft.fillScreen(ST7735_BLACK);
      time = millis() - time;

      Serial.println(time, DEC);

      // large block of text
      tft.fillScreen(ST7735_BLACK);
    }

    void loop() {

      // Look for new cards
        if ( ! mfrc522.PICC_IsNewCardPresent()) {
            return;
        }

        // Select one of the cards
        if ( ! mfrc522.PICC_ReadCardSerial()) {
            return;
        }

        if (mfrc522.uid.uidByte[0] == 0xA4 &&
           mfrc522.uid.uidByte[1] == 0xB8 &&
           mfrc522.uid.uidByte[2] == 0xB8 &&
           mfrc522.uid.uidByte[3] == 0x96) {
              Serial.println("Nate has checked in to the game.");
              tft.fillScreen(ST7735_BLUE);
              tft.setTextSize(2);
              tft.setCursor(0, 0);
              tft.setTextColor(ST7735_YELLOW);
              tft.print("Nate ");
              tft.setTextColor(ST7735_WHITE);
              tft.println("has checked in ");
              tft.setTextSize(2);
              tft.println("to the game.");
              delay(2000);
              tft.fillScreen(ST7735_BLACK);
        }

        if (mfrc522.uid.uidByte[0] == 0x03 &&
           mfrc522.uid.uidByte[1] == 0xFD &&
           mfrc522.uid.uidByte[2] == 0xBC &&
           mfrc522.uid.uidByte[3] == 0x02) {
              Serial.println("Ted has checked in to the game.");
              tft.fillScreen(ST7735_RED);
              tft.setTextSize(2);
              tft.setCursor(0, 0);
              tft.setTextColor(ST7735_CYAN);
              tft.print("Ted ");
              tft.setTextColor(ST7735_WHITE);
              tft.println("has checked in ");
              tft.setTextSize(2);
              tft.println("to the game.");
              delay(2000);
              tft.fillScreen(ST7735_BLACK);

        }

    }

body:
What you can do is store the current time whenever a card is swiped, and then when another card is swiped check how long it's been since the last card was swiped

first create a couple of variables

    unsigned long swipedTime;
    int tag1 = 0;
    int tag2 = 0;
    int swipeTimeOut = 10000; // how much time in MS you have to swipe both cards

Next we'll jump down to where where you read the cards.

          if (mfrc522.uid.uidByte[0] == 0xA4 &&
               mfrc522.uid.uidByte[1] == 0xB8 &&
               mfrc522.uid.uidByte[2] == 0xB8 &&
               mfrc522.uid.uidByte[3] == 0x96) {

                   ........

                   if (tag2 == 1 && millis() - swipedTime < swipeTimeOut ){
                       // both tags have been swiped, print serial message here
                    }

                    tag1 = 1;
                    swipedTime = millis();
            }

            if (mfrc522.uid.uidByte[0] == 0x03 &&
               mfrc522.uid.uidByte[1] == 0xFD &&
               mfrc522.uid.uidByte[2] == 0xBC &&
               mfrc522.uid.uidByte[3] == 0x02) {

                   ........

                   if (tag1 == 1 && millis() - swipedTime < swipeTimeOut ){
                       // both tags have been swiped, print serial message here
                    }
                    tag2 = 1;
                    swipedTime = millis();

             }

You'll also want to come up with a system for resetting `tag1` and `tag2` to 0 or "checking them out".


body:
You could try:

    byte tag1[] = {0xA4, 0xB8, 0xB8, 0x96};
    byte tag1_read = 0;    // flag is set when tag 1 is read
    byte tag2[] = {0x3, 0xFD, 0xBC, 0x02};
    byte tag2_read = 0;    // flag is set when tag 2 is read

    int BUTTON = 3;

    void setup(){
        pinMode(BUTTON, INPUT_PULLUP);  //set button as input pulled high
        .... // the rest of your setup()
    }

    void loop() {

      // Look for new cards
        if ( ! mfrc522.PICC_IsNewCardPresent()) {
            return;
        }

        // Select one of the cards
        if ( ! mfrc522.PICC_ReadCardSerial()) {
            return;
        }

        if (tag1_read == 0 && memcmp(mfrc522.uid.uidByte, tag1, 4) == 0){
              Serial.println("Tag 1 has been read.");
              tag1_read = 1;   //tag 1 has been read
              //delay(2000);   //not sure why u need the delay
        }

        if (tag1_read && tag2_read == 0 && memcmp(mfrc522.uid.uidByte, tag2, 4) == 0) {
              Serial.println("Tag 2 has been read.");
              tag2_read = 1;    // tag 2 has been read
              Serial.println("Both tags have been read.");
        }

        if (digitalRead(BUTTON) == LOW && tag1_read && tag2_read){
            Serial.println("Both tags are finished.");
            tag1_read = 0; tag2_read = 0;
        }
    }

This code assumes the cards must be presented and read in order.


message:
Connecting arduino to an existing circuit

I have a little clock with a button on it that i need to push four times every second hour. I am trying to get the arduino micro to do it for me.

I am trying to figure out how to connect the arduino to trigger it. The clock is operated by a CR2 (3.0V) cell battery. Is there a way to do this without a transistor? If not what do i need? How can i find out how much amp my circuit requires?

The red arrow is pointing on the cable i think triggers the clock, and i think the black arrow is pointing on the cable that is the clock gnd.

(edit: I have found similar questions explaining the process with transistor, but not without..)

[![Picture of the button that i need to push][1]][1]

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

body:
Yes, This can be achieved without a transistor.

As the circuits would be on isolated power supplies: Arduino circuit on one and the clock on another, you can use a [Solid State Relay][1].

[![SSR][2]][2]

Use the relay with your Arduino (5v or 3.3v) and wire the relay contacts parallel to the clock switch. This will isolate any power issues as clock will be powered with its own power and Arduino will be powered with its own.

You can program Arduino with proper delays to actuate the relay accordingly.

Hope this helps.

  [1]: https://en.wikipedia.org/wiki/Solid-state_relay
  [2]: https://i.stack.imgur.com/P2xyt.jpg


body:
Connect the Arduino and your clock grounds together.
Get a small resistor - no less than 1 kOhm - and connect your VOM (in current mode) in series with the resistor and your Arduino output pin.
Set the output pin to LOW and observe
Did the clock reset?
What was the current on your VOM?
If the clock reset and the current was more than 20 mA get a bigger ( 10 kOhms )  resistor and try it again.
If the clock reset and your current was less than 20 mA you are done.

And if you really want to isolate the clock from Arduino use low current LED and connect the cathode to the output pin and anode to the clock.
Keep the resistor in the circuit.
Than you will also have an indicator of "circuit is active".


body:
You might try attaching an Arduino IO through a resistor to pin 4 (where your red arrow points), and Arduino ground to pin 1 (where your black arrow points).  Because the clock is battery-operated, you can connect its ground to the Arduino's ground without problem.

Before attaching the Arduino, use your DVM to measure the voltage between pins 4 and 1, with the switch open and with the switch closed.  In following, I'll suppose you have measured 3V when the switch is open and 0V when it's closed.  This would indicate that the clock's circuit pulls or drives pin 4 high when the switch is open.  In initial experiments, I'd start with a 1KΩ or so resistor (eg, any resistor between 500Ω and 2000Ω) in series with an ammeter and the Arduino IO.  If you measure at most a few microamps of current in both the “switch open” and “switch closed” cases (see below) then the circuit should function ok with the resistor in place (since there will be only a tiny voltage drop across it).  [If, on the other hand, you measure several milliamps of current in either case, then my ideas about the clock circuit might not apply; in which case you might need an optoisolator or relay.]

To represent switch operation, put the Arduino IO into INPUT mode to represent an open switch, and into OUTPUT LOW to represent a closed switch.  For example, in `setup()` say

    pinMode(ClockPin, INPUT);  // Also does digitalWrite(ClockPin, LOW);

and in your `loop()` say stuff like

    if (TheTimeHasCome) {
       for (int k=0; k<4; ++k) {
          pinMode(ClockPin, OUTPUT);  // Presses the button
          delay(50);                  // Holds the button
          pinMode(ClockPin, INPUT);   // Releases the button
          delay(50);                  // Wait between buttons
       }

The comment `// Also does digitalWrite(ClockPin, LOW);` is a reminder that `pinMode(ClockPin, INPUT);` has two actions: it sets ClockPin to be an input instead of an output, and takes the corresponding PORTx bit low (ie, resets a bit in PORTB, PORTC, PORTD, or whatever).  If we had said `pinMode(ClockPin, INPUT_PULLUP);`, then the corresponding PORTx bit would have been set high, and the pin would be weakly pulled to Vcc, eg +5V.  It would be a mistake to send 5V to the clock, as it's likely that would exceed its voltage tolerance.

Since `pinMode(ClockPin, INPUT);` leaves the appropriate PORTx bit low, there is no need to use [`digitalWrite()`](https://www.arduino.cc/en/Reference/DigitalWrite) separately in the sketch.  When ClockPin is an input, its high impedance allows the clock to pull pin 4 high; when ClockPin is an output, its 0 level connects pin 4 to pin 1.


message:
Pass class's public function as an argument to external command

I am trying to write a library for encoders.

main.ino:

    #include <./Encoders.h>

    Encoders encoders();

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

    void loop(){
        Serial.print("");
    }

Encoders.h:

    #ifndef Encoders_h
    #define Encoders_h

    #include "Arduino.h"

    class Encoders{
        public:
            Encoders();
            void EncodersSetup();
            long RightCount;
            long LeftCount;
            void R_A_RISE();
            void R_A_FALL();
            void R_B_RISE();
            void R_B_FALL();
            void L_A_RISE();
            void L_A_FALL();
            void L_B_RISE();
            void L_B_FALL();
        private:
            short R_A_SIG, R_B_SIG, L_A_SIG, L_B_SIG;
    };

    #endif

Encoders.cpp

    #include "Arduino.h"
    #include "Encoders.h"

    long RightCount;
    long LeftCount;
    long R_A_SIG, R_B_SIG, L_A_SIG, L_B_SIG;

    Encoders::Encoders(){
        attachInterrupt(0, R_A_RISE, RISING);
        attachInterrupt(1, R_B_RISE, RISING);
        attachInterrupt(2, L_A_RISE, RISING);
        attachInterrupt(3, L_B_RISE, RISING);
        R_A_RISE();
    }

    void Encoders::R_A_RISE(){
        detachInterrupt(0);
        R_A_SIG = 1;
        if(R_B_SIG == 0){
            RightCount++;
        }
        if(R_B_SIG == 1){
            RightCount--;
        }
        attachInterrupt(0, R_A_FALL, FALLING);
    }
    void Encoders::R_A_FALL(){
        detachInterrupt(0);
        R_A_SIG = 0;
        if(R_B_SIG == 1){
            RightCount++;
        }
        if(R_B_SIG == 0){
            RightCount--;
        }
        attachInterrupt(0, R_A_RISE, RISING);
    }
    void Encoders::R_B_RISE(){
        detachInterrupt(1);
        R_B_SIG = 1;
        if(R_A_SIG == 1){
            RightCount++;
        }
        if(R_A_SIG == 0){
            RightCount--;
        }
        attachInterrupt(1, R_B_FALL, FALLING);
    }
    void Encoders::R_B_FALL(){
        detachInterrupt(1);
        R_B_SIG = 0;
        if(R_A_SIG == 0){
            RightCount++;
        }
        if(R_A_SIG == 1){
            RightCount--;
        }
        attachInterrupt(1, R_B_RISE, RISING);
    }
    void Encoders::L_A_RISE(){
        detachInterrupt(2);
        L_A_SIG = 1;
        if(L_B_SIG == 0){
            LeftCount++;
        }
        if(L_B_SIG == 1){
            LeftCount--;
        }
        attachInterrupt(2, L_A_FALL, FALLING);
    }
    void Encoders::L_A_FALL(){
        detachInterrupt(2);
        L_A_SIG = 0;
        if(L_B_SIG == 1){
            LeftCount++;
            }
        if(L_B_SIG == 0){
            LeftCount--;
            }
        attachInterrupt(2, L_A_RISE, RISING);
    }
    void Encoders::L_B_RISE(){
        detachInterrupt(3);
        L_B_SIG = 1;
        if(L_A_SIG == 1){
            LeftCount++;
        }
        if(L_A_SIG == 0){
            LeftCount--;
        }
        attachInterrupt(3, L_B_FALL, FALLING);
    }
    void Encoders::L_B_FALL(){
        detachInterrupt(3);
        L_B_SIG = 0;
        if(L_A_SIG == 0){
            LeftCount++;
        }
        if(L_A_SIG == 1){
            LeftCount--;
        }
        attachInterrupt(3, L_B_RISE, RISING);
    }

When I try to compile this, I get errors like this:

    C:/Users/marcel/Documents/dev/Arduino/encodeurs/Encoders.cpp:10:38: error: cannot convert 'Encoders::R_B_RISE' from type 'void (Encoders::)()' to type 'void (*)()'

I tried answers on other threads. Most said to make the functions passed to `attachInterrupt()` `static`. That threw different errors:

    C:/Users/marcel/Documents/dev/Arduino/encodeurs/Encoders.cpp:16:33: error: cannot declare member function 'void Encoders::R_A_RISE()' to have static linkage [-fpermissive]

I also tried this:

    attachInterrupt(0, &Encoders::R_A_RISE, this, RISING);

with no success.

The Arduino in question is a Mega but I doubt that matters.

# Edit: Per Nick Gammon's answer, I now have this.

MotorEncoderMaster.ino

    #include </home/marcel/dev/Arduino/encoders/MotorEncoderMaster/Encoders.h>
    Encoders * Encoders::instances [2] = { NULL, NULL };

    // instances of our class
    Encoders right;
    Encoders left;

    void setup (){
        right.begin (2);   // pin D2
        left.begin (3);   // pin D3
    }  // end of setup

    void loop (){
        // whatever
    }  // end of loop

Encoders.h:

    class Encoders{
        volatile bool switchChanged;

        static Encoders * instances [2];

        static void switchPressedExt0(){
            if(Encoders::instances [0] != NULL){
                Encoders::instances [0]->switchPressed();
            }
        }

        static void switchPressedExt1 (){
            if (Encoders::instances [1] != NULL){
                Encoders::instances [1]->switchPressed();
            }
        }

        public:
            void begin (const int whichPin){
                pinMode (whichPin, INPUT_PULLUP);
                switch (whichPin){
                    case 2:
                        attachInterrupt(0, switchPressedExt0, CHANGE);
                        instances [0] = this;
                        break;

                    case 3:
                        attachInterrupt(1, switchPressedExt1, CHANGE);
                        instances [1] = this;
                        break;

                }
            }

            void switchPressed(){
                switchChanged = true;
            }

    };

When I try to compile this, I get :

    In file included from MotorEncoderMaster.ino:1:0:
    /home/marcel/dev/Arduino/encoders/Encoders.h: In static member function ‘static void Encoders::switchPressedExt0()’:
    /home/marcel/dev/Arduino/encoders/Encoders.h:7:34: error: ‘NULL’ was not declared in this scope
        if(Encoders::instances [0] != NULL){
                                      ^
    /home/marcel/dev/Arduino/encoders/Encoders.h: In static member function ‘static void Encoders::switchPressedExt1()’:
    /home/marcel/dev/Arduino/encoders/Encoders.h:13:35: error: ‘NULL’ was not declared in this scope
        if (Encoders::instances [1] != NULL){
                                       ^
    /home/marcel/dev/Arduino/encoders/Encoders.h: In member function ‘void Encoders::begin(int)’:
    /home/marcel/dev/Arduino/encoders/Encoders.h:21:24: error: ‘INPUT_PULLUP’ was not declared in this scope
         pinMode (whichPin, INPUT_PULLUP);
                            ^
    /home/marcel/dev/Arduino/encoders/Encoders.h:21:36: error: ‘pinMode’ was not declared in this scope
         pinMode (whichPin, INPUT_PULLUP);
                                        ^
    /home/marcel/dev/Arduino/encoders/Encoders.h:24:45: error: ‘CHANGE’ was not declared in this scope
           attachInterrupt(0, switchPressedExt0, CHANGE);
                                                 ^
    /home/marcel/dev/Arduino/encoders/Encoders.h:24:51: error: ‘attachInterrupt’ was not declared in this scope
           attachInterrupt(0, switchPressedExt0, CHANGE);
                                                       ^

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

# Interrupt Service Routine (ISR) outside a class

Let's consider a simple use of interrupts:

    volatile bool switchChanged;

    void switchPressed ()
      {
      switchChanged = true;
      }  // end of switchPressed

    void setup ()
      {
      pinMode (2, INPUT_PULLUP);
      attachInterrupt (0, switchPressed, CHANGE);
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

That compiles fine.

---

# ISR inside a class as a class function (method)

Now let's imagine we want to put the interrupt handling into a class for our convenience.

    class myClass
      {
      volatile bool switchChanged;

      public:

      void begin ()
        {
        pinMode (2, INPUT_PULLUP);
        attachInterrupt (0, switchPressed, CHANGE);   // <--- line 10
        }  // end of myClass::begin

      void switchPressed ()
        {
        switchChanged = true;
        }  // end of myClass::switchPressed

      };  // end of class myClass

    myClass foo;  // make an instance of myClass

    void setup ()
      {
      foo.begin ();
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

That does **not** compile:

    ISR_in_class_test.ino: In member function ‘void myClass::begin()’:
    ISR_in_class_test:10: error: argument of type ‘void (myClass::)()’ does not match ‘void (*)()’

What is going on here?

ISRs have to be static functions, taking no arguments. However (non-static) class functions have an implied `this->` pointer which points to the particular *instance* of the class.

For example, if we have two instances:

    myClass foo;
    myClass bar;

If we call foo.begin() then `this->` points to "foo", and if we call bar.begin then `this->` points to "bar".

However an ISR, when fired by the processor, cannot know whether `this->` is "foo" or "bar" or something else. Thus the compiler cannot compile that line.

---

# ISR inside a class as a static class function

We can try to work around this by making the class function **static**. Doing that means that the function is not tied to any particular instance, and thus the attachInterrupt line will compile.

    class myClass
      {
      volatile bool switchChanged;   // <--- line 3

      public:

      void begin ()
        {
        pinMode (2, INPUT_PULLUP);
        attachInterrupt (0, switchPressed, CHANGE);
        }  // end of myClass::begin

      static void switchPressed ()
        {
        switchChanged = true;   // <--- line 15
        }  // end of myClass::switchPressed

      };  // end of class myClass

    myClass foo;  // make an instance of myClass

    void setup ()
      {
      foo.begin ();
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

However now we have a different problem:

    ISR_in_class_test.ino: In static member function ‘static void myClass::switchPressed()’:
    ISR_in_class_test:3: error: invalid use of member ‘myClass::switchChanged’ in static member function
    ISR_in_class_test:15: error: from this location

A non-static class variable cannot be called from a static class function. Why? Because the compiler doesn't know *which* variable you want. Is it `foo.switchChanged` or `bar.switchChanged`?

---

# ISR inside a class as a static class function with static variables

To make the static function work, it can only access static variables. So we can make switchChanged static. Plus we need to define an instance of this static variable.

    class myClass
      {
      static volatile bool switchChanged;  // declare

      public:

      void begin ()
        {
        pinMode (2, INPUT_PULLUP);
        attachInterrupt (0, switchPressed, CHANGE);
        }  // end of myClass::begin

      static void switchPressed ()
        {
        switchChanged = true;
        }  // end of myClass::switchPressed

      };  // end of class myClass

    volatile bool myClass::switchChanged;  // define

    myClass foo;  // make an instance of myClass

    void setup ()
      {
      foo.begin ();
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

Now the class compiles. However we have thrown away most of the advantages of having a class in the first place, as we are forced to use a static function, and that static function can only access static variables.

---

# Glue routines

To work around this problem we can write short "glue" routines. These are functions that interface between an ISR and an **instance** of a class.

    class myClass
      {
      volatile bool switchChanged;

      static myClass * instances [2];

      static void switchPressedExt0 ()
        {
        if (myClass::instances [0] != NULL)
          myClass::instances [0]->switchPressed ();
        }  // end of myClass::switchPressedExt0

      static void switchPressedExt1 ()
        {
        if (myClass::instances [1] != NULL)
          myClass::instances [1]->switchPressed ();
        }  // end of myClass::switchPressedExt1

      public:

      void begin (const byte whichPin)
        {
        pinMode (whichPin, INPUT_PULLUP);
        switch (whichPin)
          {
          case 2:
            attachInterrupt (0, switchPressedExt0, CHANGE);
            instances [0] = this;
            break;

          case 3:
            attachInterrupt (1, switchPressedExt1, CHANGE);
            instances [1] = this;
            break;

          } // end of switch
        }  // end of myClass::begin

      void switchPressed ()
        {
        switchChanged = true;
        }

      };  // end of class myClass

    myClass * myClass::instances [2] = { NULL, NULL };

    // instances of our class
    myClass foo;
    myClass bar;

    void setup ()
      {
      foo.begin (2);   // pin D2
      bar.begin (3);   // pin D3
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

This is a bit fiddly, however what it is doing is remembering in an array which instance of the class is associated with which interrupt. The "glue" routines switchPressedExt0 and switchPressedExt1 call the appropriate instance of the switchPressed function by using the remembered class pointer.

Now the non-static function switchPressed can access non-static class variables.

---

Adapted from my web page [Calling an ISR from a class](http://www.gammon.com.au/forum/?id=12983)


message:
Raspberry Pi Arduino Installer broken

I am tring to use ShorTie8's new arduino ARM installer on my RPI B+ by copying this into my terminal:

>cd

>sudo apt-get update -y && sudo apt-get dist-upgrade -y

>wget https://raw.githubusercontent.com/ShorTie8/Arduino_IDE/master/Arduino_IDE_builder.bash

>chmod +x Arduino_IDE_builder.bash

>sudo ./Arduino_IDE_builder.bash

>sudo Arduino/build/linux/work/./arduino

>sudo Arduino/build/linux/work/./install.sh

>sudo apt-get install -y mercurial subversion build-essential gperf bison ant texinfo zip automake flex libusb-dev libusb-1.0-0-dev libtinfo-dev pkg-config libwxbase3.0-dev libtools

But Getting The following Error at sudo ./Arduino_IDE_builder.bash

>+ echo -e '\n\nConfiguration values\n\n'

>Configuration values

>+ Stable=1.6.7
+ Update_me=yes
+ Silence_is_Golden=yes
+ echo -e '\n\nSystem check\n\n'

>System check

>++ date
+ start_time='Sat 13 Feb 11:12:37 GMT 2016'
++ pwd
+ Start_Directory=/home/pi
++ pwd
+ Working_Directory=/home/pi/Arduino/build
+ echo -e '\n\nChecking for root .. \n'

>Checking for root ..

>++ id -u
+ '[' 0 '!=' 0 ']'
+ echo 'Yuppers .. :)~'
Yuppers .. :)~
+ [[ yes == \y\e\s ]]
+ echo -e '\n\nChecking to see if I'\''m update\n'

>Checking to see if I'm update

>+ git remote update
fatal: Not a git repository (or any of the parent directories): .git

body: Instead of manually downloading a file from the github repository, check out the repository properly with `git clone 《repository》`


message:
Arduino and hard drive

So in a laptop you have a CPU and a hard drive. The hard drive feeds data to the CPU and the CPU executes it. In Arduino you flash the CPU and the "hard drive" is built into it. Is it possible to have a hard drive or SD card feed data into the Arduino to be executed and then feed more data in and so on? If it is possible how is it done?

body:
> Is it possible to have a harddrive or sd card feed data into the Arduino to be executed and then feed more data in and so on. If it is possible how is it done?

A harddrive would be difficult to connect, but an SD card will work just fine.

You can write a sketch that reads data from an SD card. There is library support for both SD and FAT16/32 file systems.

Another interpretation of your question is; is it possible to load a sketch from an SD card. The answer is yes; there are a number of projects that have done that.

Cheers!


message:
Dimmer on Due: digitalWrite on one pin affects digital value of another

I'm trying to make dimmer for heater using Arduino Due. I'm using a variant of this very common scheme: [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/pOmnJ.jpg
My scheme has MOC3043 with zero-crossing detection.

I use two pins to control the dimmer: **detectorPin** to analyse input voltage wave and **controlPin** to drive optocoupler. The program is very simple thanks to zero-crossing MOC.

I attached an `interrupt` to the input **detectorPin** on `CHANGE` event. And **controlPin** is used as digital output. When I test detection with **controlPin** unplugged everything works fine. But when **controlPin** is connected, value which is read inside the interrupt becomes wrong! So my dimmer cannot detect any half-wave and reports errors. This happens at the moment when **controlPin** value is set to `HIGH` with help of `digitalWrite()` func. After nearly 40-50 milliseconds detected values go back to normal, so most of time my dimmer work as expected.

I measured current on the **controlPin**, it's only 3.2mA, which is lower than maximum possible current for Arduino Due.

I tested this with **detectorPin** = 51, and different **controlPins**: 52, 36, 31.

So, how do you think, what is the problem? Is my Arduino broken?

body:
There are a few issues with your circuit.

<s>First, you need to add a diode to your 4N25 circuit.</s>  *See EDIT below*.     You should still put a diode across your 4N25 LED.  <s>Right now, your 4N25 diode (LED) gets a high voltage across it 1/2 of the time.</s>  Because you have 60K (30K+30K) in the circuit, the LED is likely not damaged, however the LED isn't really designed to handle reverse voltage more than 6 volts. Depending upon the reverse characteristics of the Bridge diodes (leakage current), your 4N25 LED could be experiencing greater than 6 volts.  Using devices beyond their "maximum specification" can produce unusual side effects.

Place the new diode (1N4007 is good, almost any diode will work) across the LED on your 4N25. Wire the new diode with new diode anode to the LEd cathode. Now, the LED will turn on during 1/2 cycle of the AC,  and be protected against overvoltage during the other half of the cycle.

Second,  rearrange your circuit for the Triac.  The data sheet for your [MOC3043 triac driver](http://www.mouser.com/ds/2/149/MOC3043M-195994.pdf) shows a typical schematic.

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

Notice the 39 ohm resistor and the 0.01 uf capacitor in the circuit.  This is called a snubber and will reduce interference and voltage spikes. This type of interference is famous for disrupting low voltage circuits such as micro-controllers.

Without seeing your code, I can't say much on that.  However, I presume that you are trying to detect the zero cross, and then waiting a certain amount of time AFTER the zero cross to turn on the Triac.

> I measured current on the controlPin, it's only 3.2mA

Your 3.2mA may not be enough to drive the LED in your dimmer circuit. You will likely need 10mA to assure proper operation.  You can reduce the resistor to achieve higher current to the MOC3043.

EDIT  :  I just realized that your bridge rectifier protects the LED (4N25) from reverse voltage.

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


body:
The problem with wrong input was caused by floating base of optocoupler:
[![enter image description here][1]][1]

100k pull-down will fix it.

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


message:
Timer/Counter programming Arduino

I'm trying to blink an LED on an ATMega328P (same MCU as Arduino I think..) using the internal timer but I'm stuck since it doesn't seem to light the LED at all....

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

    void delay(void);

    void delay_long(void);

    int main(void) {

      DDRB = 0xFF;                   // port B is configured as output   DDRB : 0b11111111
      DDRB &= ~(1<<PB1);             // pin 1 of port B is configured as input  DDRB : 0b11111101
      PORTB = 0x00;                  // pins of port B are low (output) and with no pull-up resistor (input)
      PORTB |= (1<<PB0)|(1<<PB1);    // pin 0 is high (output) and pin 1 is pulled high (input)    PORTB : 0b00000011

      while(1) {
        PORTB &= ~(1<<PB0);
        delay();
        PORTB |= 1<<PB0;
        delay();
        PORTB = ~(1<<PB0);
        delay_long();
        PORTB = 1<<PB0;
        delay_long();
      }

      return 1;

    }

    void delay(void) {
      TCNT0 = 0x00;
      TCCR0B = 0x05;
      while ( (TIFR0 & TOV0) == 0 )
        ;
      TCCR0B = 0x00;
      TIFR0 |= 1<<TOV0;
    }

    void delay_long(void) {
      TCNT0 = 0x00;
      TCCR0B = 0x05;
      while ( (TIFR0 & TOV0) == 0 )
        ;
      TCCR0B = 0x00;
      TIFR0 |= 1<<TOV0;
      TCCR0B = 0x05;
      while ( (TIFR0 & TOV0) == 0 )
        ;
      TCCR0B = 0x00;
      TIFR0 |= 1<<TOV0;
    }

if I remove the body of the event loop it lights up... so I think I must be missing something in the delay functions...

body:
It seems that the offending line is:

    while ( (TIFR0 & TOV0) == 0 )

`TOV0` by itself equals 0, so the above loop will never end.

You should use:

     while ( (TIFR0 & (1<<TOV0)) == 0 )

instead.


message:
Is the Uno Vin pin protected by the voltage regulator?

I guess it's all in the title. When using Vin as input, does it go through voltage regulator, or must I feed it precisely 5V?

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

If you look at the [schematic](https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf) you'll see Vin is connected to the input of the voltage regulator. Just like the barrel-jack (except for the diode).

So the same input-voltage of   7-12V applies to Vin.

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


body: when you connect you regulated 5V at Vin port your 5V output will be lower than 5V as it have to pass through the 5V regulator. The input voltage should range from 7-12V.


message:
Error uploading to ATtiny

I followed Great Scott's video on YouTube for uploading to an ATtiny85. When I tried I got the following error messages:

>Arduino: 1.6.7 (Windows Vista), Board: "ATtiny85 (internal 8 MHz clock)"
>
>Board attiny-master:attiny:attiny85-20 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-20
>
>Board attiny-master:attiny:attiny45-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY45-8
>
>Board attiny-master:attiny:attiny85-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-8
>
>Board attiny-master:attiny:attiny44 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY44

etc. etc. ...

>exec: "-w": executable file not found in %PATH%
>Error compiling.`
>
>  This report would have more information with
>  "Show verbose output during compilation"
>  enabled in File > Preferences.

When I unplug  my ATtiny85 and restart Arduino, I have no problems uploading, though I get about 8 error messages saying something like:

>Board attiny-master:attiny:attiny84 doesn't define a 'build.board' preference. Auto-set to: ATTINY_ATTINY84

body:
It's likely that a compiler's file name is missing from a command line the IDE is trying to execute.  To find out more about what the command looks like (which will let you figure out what name is missing), turn on verbose output during compilation.  That is, click File, Preferences in the IDE, then click the box in front of “compilation”.  After you find out what's missing, you can then turn off verbose output and fix `platform.txt`, which is the file the IDE looks at to find out what commands to execute when compiling sketches.

To get rid of the warnings about undefined `build.board` values, add lines like the following to the `boards.txt` file in the `tiny/avr/` directory (or whereever you installed it).  (Your 1.6 IDE wants `build.board` definitions, which IIRC weren't needed by 1.5 and earlier IDEs.)

    attiny85-20.build.board=ATTINY_ATTINY85-20

Each of the lines you add will contain the Auto-set value, prefaced by a string made up of a board-type and `.build.board=` concatenated together.  Add each line just before or after other `.build.`-containing lines.


message:
BLE Python with GUI on OSX

Has anyone connected BLE devices with Python + GUI on OSX? I've looked into a few libraries (most are old), but one that has the most success if Adafruit's BlueFruit library. However, this library works poorly with GUI's since it requires use of the main event loop (which GUI's usually use). After doing a bunch of Google searches, I couldn't find any good examples of using a GUI with Python + BLE. There seems to be no good BLE libraries for Python either.

Specifically looking for help integrating BLE with Kivy, but other GUI toolkit examples should be fine.

Also trying to gauge interest in this to see if I can do development to solve this (if it really is a problem).

body:
If you are still searching for a lib check out:
https://github.com/adafruit/Adafruit_Python_BluefruitLE

Its specifically made for BLE communication on OS X or Linux by wrapping the corebluetooth and its Linux equivalent bluez in a python lib. Windows is not supported at this moment.

Unfortunately there is no documentation to it. You will have to read the examples and search for specific functions in the lib manually.


message:
Convert UNIX Timestamp

I have an UNIX Timestamp in my Arduino Sketch and would like to get the day of the week of this timestamp (1-7).

How can I convert the timestamp to get the day of the week?

body:
The simplest solution to that problem is to download the [Time][1] library and use the [weekday()][2] function:

    int weekday(time_t t); // the weekday for the given time

Cheers!

  [1]: https://github.com/PaulStoffregen/Time
  [2]: https://github.com/PaulStoffregen/Time/blob/master/TimeLib.h#L114


message:
Distance sensor

I am adding a distance sensor to existing project that uses Arduino due, do I connect the trigger pin and the echo pin of the HC-SR04 ultrasonic sensor directly to  Arduino due which uses 3.3V   while HC-SR04 ultrasonic sensor uses 5V or do I need to use a voltage divider?

body:
Well, it depends on the sensor itself. Some sensors run on both 5V and 3.3V. There's a similar question here on StackExchange: [How to connect 5V sensors to 3.3V digital input (Due)?][1]

But, in short, if the sensor can't operate in 3.3V, you'll need a level converter /shifter.

  [1]: https://arduino.stackexchange.com/questions/795/how-to-connect-5v-sensors-to-3-3v-digital-input-due


body:
The trigger pin is an input, so you can connect that directly to the Due.

The echo pin will however output 5v. You could use a voltage divider to bring that down to 3.3v or a bit lower.


body:
As suggested in previous answers, you can directly use a Due output to drive the HC-SR04's Trig pin; according to the HC-SR04 spec sheet, that pin operates at TTL levels.  It will see 0 V as a 0-input and will see 3.3 V as a 1-input since it exceeds 2.4 V.  Also see  [3.3v input to Arduino digital pin](https://electronics.stackexchange.com/q/58498) in electronics.stackexchange.

However, the Due's inputs are not 5 V tolerant, so you will need to use a voltage divider between the Echo pin and a Due input.  See second paragraph of arduino.cc's [ArduinoBoardDue](https://www.arduino.cc/en/Main/ArduinoBoardDue) article:
>Warning: Unlike most Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board.


message:
Is it possible to upload previously compiled binary?

I have a number of sketches that I keep wanting to load into the Arduino but I don't necessarily need to recompile them because I haven't changed anything since the last compile. Since the compile takes a minute or 2 each time, this would save me some waiting.

I can see that the IDE has the option to "Export Compiled Binary", but doesn't seem to have the converse option of Uploading a previously compiled binary. Is there any way to do this?

body:
Yes!
Its possible that you can upload a previously complied binary, using

AVRDUDE - a command line utility which is actually used to upload binaries, behind the arduino IDE.

You can find AVRDUDE in
Arduino folder > hardware  > tools > avr > bin

This some documentation for AVRDUDE
http://www.nongnu.org/avrdude/user-manual/avrdude.html

else simplest thing you can do is turn on verbose output during upload and watch for a command in the end with AVRDUDE in it along with the path of hex file, just copy paste &  run the same command in CommandLine; your task is accomplished.


message:
FTDI stdk 500k not responding

I programming atmega328P bootloaded with an FTDI.

Some tutorial mentions that you have to connect the DTR to the reset pin:

http://electronics-diy.com/FT232RL_USB_to_Serial_Adapter_for_PIC_AVR_ATMEGA_ARDUINO_MCUs.php

Is that so? Because some don't, they just say rx,tx is enough. I still can't program the chip with the error:

     avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

    avrdude: Version 5.11.1, compiled on Oct 18 2011 at 21:17:35
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/etc/avrdude.conf"
             User configuration file is "/root/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : avrisp
             Overriding Baud Rate          : 9600
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding

    avrdude done.  Thank you.

I tried different baud rates, no matter what it's not responding. Linux recognizes the FTDI as:

    Sat Feb 13 22:52:14 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
    [Sat Feb 13 22:52:14 2016] ftdi_sio 1-2.1:1.0: device disconnected
    [Sat Feb 13 22:52:19 2016] usb 1-2.1: new full-speed USB device number 73 using uhci_hcd
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device found, idVendor=0403, idProduct=6001
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: Product: FT232R USB UART
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: Manufacturer: FTDI
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: SerialNumber: A6004mhS
    [Sat Feb 13 22:52:20 2016] ftdi_sio 1-2.1:1.0: FTDI USB Serial Device converter detected
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: Detected FT232RL
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
    [Sat Feb 13 22:56:25 2016] usb 1-2.1: USB disconnect, device number 73
    [Sat Feb 13 22:56:25 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
    [Sat Feb 13 22:56:25 2016] ftdi_sio 1-2.1:1.0: device disconnected

Well my questions now are:

1, When I use the Arduino IDE to program a barebone 328P with this FTDI what should be the **BOARD** and what should be the **PROGRAMMER**?

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Although I tried almost all... I think something else is wrong.

2, Should I be able to get any result with doing the previous:

     avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

command WITHOUT connecting the barebone chip? I think not, since this doesn't act like a fully fledged MCU just like a serial converter.

Thanks

body:
You need to connect DTR to the reset pin because the Arduino IDE (really avrdude) needs to be able to reset the processor in order to return control to the bootloader, which will then receive the new program. When an Arduino board is running your sketch, the serial port is available for use by the sketch; it can't be used to upload a new program.

To answer your first question, you should set the board to whatever your board actually is. You don't have to worry about the programmer. It's only used if you use the "upload with programmer" function. The normal "upload" function uses the serial port to send the sketch to the board via the bootloader. That's what you want. Note that while you don't have to set the programmer, you do have to set the port.

You can use avrdude to program the Arduino through the serial port via the bootloader. That's exactly what the IDE does. You have to specify the port just as you do in the IDE. To determine the other settings, look up your board in the Arduino IDE's boards.txt file. Most of what boards.txt does is tell the IDE how to invoke avrdude.

I suspect that one reason why avrdude isn't working for you is that you've set the baud rate to 9600.  According to boards.txt the upload speed for the Nano with the ATmega328P is 57600.


body:
> Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?

See: [How to make an Arduino-compatible minimal board](http://www.gammon.com.au/breadboard)

From that page, this is how I hooked up my FTDI cable:

[![FTDI connections][1]][1]

And a close-up:

[![Close-up of FTDI][2]][2]

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.

  [1]: https://i.stack.imgur.com/0ymm8.jpg
  [2]: https://i.stack.imgur.com/V9wye.jpg