text:
Communicate between NodeMCU ESP8266 gateway and multiple sensor nodes
What is the best wired way to communicate between multiple NodeMCU ESP8266 boards for home automation.
Every room should get at least a light, temp, PIR and xx relay modules to switch things on and off.
To connect all these sensors the GPIOs from one NodeMCU are sometimes not enough.
To reach this goal I planned to install in every room one NodeMCU as gateway and multiple NodeMCU as nodes for my sensors. The gateway will receive and forward information from/to my openHAB center via MQTT messaging.
I thought to use an RS-485 2-Wire connection between my sensor nodes and the room gateway. The gateway from my room will be connected via wifi or wired cable to my network.
I2C seems more to be for communication directly on PCBs or only short wiring.
Do you have any suggestions for me, is my plan possible? Any better ideas?

If you really wanted wired communication then yes, RS-485 is the way to go.
In any installation where you will be running cables in the vicinity of mains wiring you will have noise. I2C is very bad with noise and not a good choice for any off-board wiring. RS-485, however, owing to the balanced line nature of the signalling, is designed to reject common mode noise such as is induced by mains wiring.
I would ask, though, why use ESP8266 as remote wired nodes? It seems a real waste to use a WiFi module for wired communication - a smaller, simpler, lower powered board (Arduino Micro / Mini maybe [3.3V, 8MHz version for simplicity of interfacing]) would be far more suitable for such a role.

Many thx for reply. What is about the speed from RS-485, is it faster or slower than I2C and could I ran into problems if multiple nodes try to submit their values at the same time to the gateway? I'd like to use the ESP8266 because of the more memory and faster cpu. Or do you know similar device without wifi module? During my research the ESP was the fastest and cheapest one...?

You shouldn't need much power and memory for simple sensor data acquisition and transfer. To prevent collisions have the ESP8266 request data from the remote nodes rather than have them send blindly. RS-485 can be as fast as your UART will go. 1 Mbps is certainly possible, though as with all comms, the higher your baud rate the shorter your maximum distance.


text:
Splitting DOUBLE in byte for save on EEPROM
I'm trying to save in memory (FRAM in this case) DOUBLE value, i try the same method with use of UNION for save FLOAT value, but don't go over the 2nd number after dot, why? Where I'm wrong? thank's for help .
 //---------------------------------------------------------

  union Scomp_double  // si utilizza union x double
  {
    double temp;
    char byte_s[8];
  } S_double;

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

double mioDouble = 1234567.12345678;

//-------------------------DOUBLE--------------------------------

  Serial.println("DOUBLE");
  byte d0 = 0;  // contengono i byte del float
  byte d1 = 0;
  byte d2 = 0;
  byte d3 = 0;
  byte d4 = 0;
  byte d5 = 0;
  byte d6 = 0;
  byte d7 = 0;

  S_double.temp = mioDouble;
  d0 = S_double.byte_s[0];
  d1 = S_double.byte_s[1];
  d2 = S_double.byte_s[2];
  d3 = S_double.byte_s[3];
  d4 = S_double.byte_s[4];
  d5 = S_double.byte_s[5];
  d6 = S_double.byte_s[6];
  d7 = S_double.byte_s[7];

  Serial.println(d0);
  Serial.println(d1);
  Serial.println(d2);
  Serial.println(d3);
  Serial.println(d4);
  Serial.println(d5);
  Serial.println(d6);
  Serial.println(d7);

  fram.writeEnable(true);
  fram.write8(11, d0);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(12, d1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(13, d2);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(14, d3);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(15, d4);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(16, d5);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(17, d6);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(18, d7);
  fram.writeEnable(false);

  S_double.byte_s[0] = fram.read8(11); // si ricompone il double
  S_double.byte_s[1] = fram.read8(12);
  S_double.byte_s[2] = fram.read8(13);
  S_double.byte_s[3] = fram.read8(14);
  S_double.byte_s[4] = fram.read8(15);
  S_double.byte_s[5] = fram.read8(16);
  S_double.byte_s[6] = fram.read8(17);
  S_double.byte_s[7] = fram.read8(18);

  double masterDouble = S_double.temp;
  Serial.println(masterDouble);
  //-------------------------DOUBLE-------------------------------

expected result 1234567.12345678 , result taken 1234567,12

double on Arduino is 4 bytes. The same as a float.

no way for have 4 digit after dot ,nice :) tnks for reply

Why not simple use "fram.write(&aFloatVar, sizeof(aFloatVar));"??

and what for read? tnks

The problem here is the serial output, which by default only outputs 2 decimal places. Solution: Serial.println(masterDouble,8);

how suggest in the comments, and on Arduino reference DOUBLE website
only on arduino 2 float it's 8 byte.

If you mean on the Due, yes, but readers who don't speak Italian will not automatically map the actual name of the product "Arduino Due" to "Arduino 2" and understand that you are talking about an ARM-based board rather than a traditional AVR-based one where float and double are 4-byte types.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
After update via ICSP can't use usb for Serial Reading and Usb for programming board
after update software on my arduino Nano board via ICSP i can't use USB for serial monitor and update software, why?

Update the software that runs on the PC?  Update the Arduino boot loader?  Update some driver or library you are using?  Or, did you just reprogram the Atmel processor directly and erased the Arduino boot loader?

If you did the last, you no longer have an Arduino.  You just have an Atmel processor with some hardware around it.

As stated, it is very difficult for someone to answer this question.  Could you clarify what you have uploaded through ICSP? Mentioning the avrdude command line would already be better (we want to see if you changed fuses, for instances). Showing the output of avrdude might help as well. Also what program did you upload?

Assuming you have reprogrammed the Arduino Nano's Atmel processor (an ATmega328) directly using the processor's ICSP pins, you may have erased the Arduino boot loader from the processor.  In such a case you no longer have an Arduino.  Rather you have an ATmega328 processor surrounded by some hardware.
To recover you need to reprogram the ATmega328 processor with the Arduino boot loader.

I'd agree...
Bootloader has been overwritten by your 'update'..

Not "may" - but "have" - because the ATmega family ISP only supports full chip erase, the only way there is still a bootloader in there is if the ISP operation did no erasing, or if the ISP process happened to re-write a functional bootloader in the proper place alongside any application program it wrote.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
decomposition long number to byte and recomposition With FRAM
I'm using Adafruit FRAM for my little project and have some trouble with recomposition of LONG Variable , right now the recomposition on INTEGER it's fine.
Where I'm wrong with recomposition of LONG number? Thank's for reply :D
#include <SPI.h>
#include "Adafruit_FRAM_SPI.h"

/* Example code for the Adafruit SPI FRAM breakout */
uint8_t FRAM_CS = 10;

//Adafruit_FRAM_SPI fram = Adafruit_FRAM_SPI(FRAM_CS);  // use hardware SPI

uint8_t FRAM_SCK = 13;
uint8_t FRAM_MISO = 12;
uint8_t FRAM_MOSI = 11;
//Or use software SPI, any pins!
Adafruit_FRAM_SPI fram = Adafruit_FRAM_SPI(FRAM_SCK, FRAM_MISO, FRAM_MOSI, FRAM_CS);

uint16_t          addr = 0;

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup(void) {
#ifndef ESP8266
  while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600);

  if (fram.begin()) {
    Serial.println("Found SPI FRAM");
  } else {
    Serial.println("No SPI FRAM found ... check your connections\r\n");
    while (1);
  }
  int interoDaScrivere = 12345;
  long longDaScrivere = 123456789;
  byte a1 = 0;
  byte a2 = 0;
  byte intPt0 = 0;
  byte intPt1 = 0;
  byte longPt1 = 0;
  byte longPt2 = 0;
  byte longPt3 = 0;
  byte longPt4 = 0;
  a1 = byte(interoDaScrivere);        // si scompone l'intero in 2 byte
  a2 = byte( interoDaScrivere >> 8);
  //decomposition Long

  byte b1 = (longDaScrivere);
  byte b2 = (longDaScrivere >> 8);
  byte b3 = (longDaScrivere >> 16);
  byte b4 = (longDaScrivere >> 24);

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

  // Read the first byte
  uint8_t test = fram.read8(0x0);
  Serial.print("Restarted "); Serial.print(test); Serial.println(" times");

  // Test write ++
  fram.writeEnable(true);
  fram.write8(0x0, test + 1);
  fram.writeEnable(false);
  /*
    fram.writeEnable(true);
    fram.write(0x1, (uint8_t *)"FTW!", 5);
    fram.writeEnable(false);
  */

  fram.writeEnable(true);
  fram.write8(1, a1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(2, a2);
  fram.writeEnable(false);

  fram.writeEnable(true);
  fram.write8(3, b1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(4, b2);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(5, b3);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(6, b4);
  fram.writeEnable(false);

  //ricomposizione INT
  int interoRicomposto = 0;
  intPt0 = fram.read8(1);
  intPt1 = fram.read8(2);
  //INT RECOMPOSITION
  interoRicomposto =  ((intPt1 << 8) | intPt0);
  // ricomposizione LONG
  long longRicomposto = 0;
  longPt1 = fram.read8(3);
  longPt2 = fram.read8(4);
  longPt3 = fram.read8(5);
  longPt4 = fram.read8(6);
 //LONG RECOMPOSITION
  longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

  Serial.print("A1 F0 ");
  Serial.print(a1);
  Serial.print(" ");
  Serial.println(intPt0);
  Serial.print("A2  F1 ");
  Serial.print(a2);
  Serial.print(" ");
  Serial.println(intPt1);
  Serial.println(interoRicomposto);

  Serial.print("b1 LongPt1 ");
  Serial.print(b1);
  Serial.print(" ");
  Serial.println(longPt1);
  Serial.print("b2 LongPt2 ");
  Serial.print(b2);
  Serial.print(" ");
  Serial.println(longPt2);
  Serial.print("b3 LongPt3 ");
  Serial.print(b3);
  Serial.print(" ");
  Serial.println(longPt3);;
  Serial.print("b4 LongPt4 ");
  Serial.print(b4);
  Serial.print(" ");
  Serial.println(longPt4);

  Serial.println(longRicomposto);

}

void loop(void) {

}

Looks like you got your shifting backwards in the recombining?

I'm trying after decomposition in byte to recombine it in a new variable with values readed in the FRAM sorry for my english

Yes, I gathered that. Look at which portion of the long you are storing in address 3 (for example) and then look at where you are placing what you read from address 3 in the recombined long. Looks to me like you take it from the lower 8 bit, then recombine it into the uppermost 8 bits.

I'm trying in this line longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24)); but I'm doing something wrong :S thanks for reply

the arduino write to me 23303 and not 123456789

I am sorry, I think the language difference is getting in the way. I am telling you what is wrong, and you are just replying with what you have already written. I know what you have already written, I have already read it.

excuse me for that, can you write an example code I'm really sorry for boring you

There is one very obvious error in your code: You are writing the long
number LSB (least significant byte) first: the LSB goes at address 3 of
the FRAM, while the MSB (most significant byte) goes at address 6. You
reconstruct the number with
longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

which puts longPt1 (contents of address 3) as the most significant
byte. Thus you are swapping all the bytes around.
Then there is a more subtle error. longPt1 is a byte. According to the
C++ promotion rules, it is implicitly promoted to int before any
arithmetic or logical operation. But since an int is 16-bits, you are
shifting all the bits out when you do longPt1 << 24. You should cast
the numbers to a 32-bit type before shifting, as follows:
long longRicomposto = (uint32_t) longPt1 <<  0
                    | (uint32_t) longPt2 <<  8
                    | (uint32_t) longPt3 << 16
                    | (uint32_t) longPt4 << 24;

Note that I am casting to an unsigned type. Shifting a 1 into the bit
sign of an integer is undefined behavior in C++: the shift must be done
with an unsigned type, then, if needed, cast to a signed type.

You should cast the numbers to a 32-bit type before shifting, as follows: it is advisable to use brackets liberally in cases like that. don't leave any doubts there as to how you want the shifts to be done.

There is actual a member function in the Adafruit_FRAM_SPI library that solves all of this. There is no need for all this shifting.
int interoDaScrivere = 12345;
long longDaScrivere = 123456789;

fram.write(1, (const uint8_t*) &interoDaScrivere, sizeof(interoDaScrivere));
fram.write(3, (const uint8_t*) &longDaScrivere, sizeof(longDaScrivere));

And
fram.read(1, (uint8_t*) &interoDaScrivere, sizeof(interoDaScrivere));
fram.read(3, (uint8_t*) &longDaScrivere, sizeof(longDaScrivere));

Cheers!
PS: Might need to adjust depending on the number of bytes/bits and address.

Let's cut out all the rubbish from your code and just look at the relevant lines:
byte b1 = (longDaScrivere);
byte b2 = (longDaScrivere >> 8);
byte b3 = (longDaScrivere >> 16);
byte b4 = (longDaScrivere >> 24);

fram.write8(3, b1);
fram.write8(4, b2);
fram.write8(5, b3);
fram.write8(6, b4);

longPt1 = fram.read8(3);
longPt2 = fram.read8(4);
longPt3 = fram.read8(5);
longPt4 = fram.read8(6);

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

If we now compress it even more by removing the fram stuff and just assigning direct from b? to the equivalent longPt? you can see even better what is happening:
byte b1 = (longDaScrivere);
byte b2 = (longDaScrivere >> 8);
byte b3 = (longDaScrivere >> 16);
byte b4 = (longDaScrivere >> 24);

longPt1 = b1;
longPt2 = b2;
longPt3 = b3;
longPt4 = b4;

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

Now if we remove the b? variables completely and just assign direct to longPt? we get:
longPt1 = (longDaScrivere);
longPt2 = (longDaScrivere >> 8);
longPt3 = (longDaScrivere >> 16);
longPt4 = (longDaScrivere >> 24);

longRicomposto = ((longPt4 << 0) + (longPt3 << 8) + (longPt2 << 16) + (longPt1 << 24));

And if we then split the last line up so it looks more like the first block:
longPt1 = (longDaScrivere);
longPt2 = (longDaScrivere >> 8);
longPt3 = (longDaScrivere >> 16);
longPt4 = (longDaScrivere >> 24);

longRicomposto  = (longPt4 << 0);
longRicomposto |= (longPt3 << 8);
longRicomposto |= (longPt2 << 16);
longRicomposto |= (longPt1 << 24);

Hopefully from that it is now clear where you have gone wrong.
You take the lowest 8 bits (longDaScrivere) and shift them 24 places to the left ((longPt1 << 24)), and apply that to the recombined long.
In effect, you start with 4 bytes ABCD and reverse them through bit shifting - 0 goes to 24, 8 to 16, 16 to 8 and 24 to 0, to end up with DCBA.


text:
How can I make my Arduino Esplora program start on the press of a button and then continue to run without me having to hold the button down?
I am trying to create a program where the main code starts on the press of a button.
I am using an Arduino Esplora, and I want to have the built-in LED be blue when I plug in the power until I press Switch 1 (or any of them), upon which the program starts.
I have had no problem in making the main part of my program, but I would like to find a way to have my program by just pressing the button once, as currently it only works while I am holding the button down continuously - something that is not possible in the situation I am using it for. I can't use any components apart from the Esplora itself, which rules out the option of using switches, etc. which probably would have made my life easier .
I would appreciate any suggestions. I'm pretty new to Arduino, so I'm sorry if I ask any dumb questions, or don't understand some of the concepts you are talking about, but I'll try my best. Thank you!

please show us your code

You could simulate the switch with the button by using a state variable that hold the state of the "switch". I don't know your code, so I can only give you an example on how to do that:
// the includes are here, if you need any

int flagActive = -1;

// ...

setup()
{
   // ... set the internal LED to blue
}

loop()
{
   if ( < switch pressed > )
   {
     flagActive = 1;
   }

   if ( flagActive > 0 )
   {
     // .... your program
   }
}

You could also toggle the flag if you intend to deactivate you program by pressing the button again.
   if ( < switch pressed > )
   {
     flagActive = flagActive * -1;
   }

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
real-time reading of a quadrature encoder at full resolution with only one interrupt on ATmega328
I want to read a quadrature rotary encoders at full resolution with only one interrupt on Arduino Nano (ATmega328). So I found out that we can use XOR to reach a full resolution:

Where pin 3 is interruptable but 4 and 5 are not.
Our requirements are:

Full resolution: for example, the solution offered in this answer works at a half-resolution only, not detecting all the edges.
Real-time: being as fast as possible up to the level that this hardware allows and safe in terms of not missing any of the signal edges.
using only one interrupt. We need the other one for other purposes.

So far, I have developed two different codes, one aiming for safety and the other for performance:
Preamble:
#include "digitalWriteFast.h"

#define pinT 3 // trigger pin comming from XOR

#define pinA 4 // channel A
#define pinB 5 // channel B

volatile long counter = 0;
long counter_ = counter;

where the digitalWriteFast library can be downloaded from here.
Performant:
volatile short int increment = 0;
volatile bool tmpA;
volatile bool tmpB;
volatile bool lastA;

ISR(trigger) {
  tmpA = digitalReadFast(pinA);
  tmpB = digitalReadFast(pinB);
  counter += (1 - 2 * tmpA) * (1 - 2 * tmpB) * (1 - 2 * (lastA != tmpA));
  lastA = tmpA;
}

void setup() {
  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);
  lastA = digitalReadFast(pinA);
  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.println(counter);
    counter_ = counter;
  }
}

Safe:
volatile unsigned long error = 0;
unsigned long error_ = 0;

volatile bool inputA;
volatile bool inputB;

volatile short state; // 100 110 101 111
volatile short state_;

void detectState() {
  inputA = digitalReadFast(pinA);
  inputB = digitalReadFast(pinB);

  if (inputA) {
    if (inputB) {
      state = 111;
    } else {
      state = 110;
    }
  } else {
    if (inputB) {
      state = 101;
    } else {
      state = 100;
    }
  }
}

ISR(trigger) {

  detectState();

  if (state_ != state) {
    switch (state_) {
      case 100:
        if (state == 110) {
          counter++;
        } else if (state == 101) {
          counter--;
        } else {
          error++;
        }
        break;
      case 110:
        if (state == 100) {
          counter--;
        } else if (state == 111) {
          counter++;
        } else {
          error++;
        }
        break;
      case 101:
        if (state == 100) {
          counter++;
        } else if (state == 111) {
          counter--;
        } else {
          error++;
        }
        break;
      case 111:
        if (state == 110) {
          counter--;
        } else if (state == 101) {
          counter++;
        } else {
          error++;
        }
        break;
      default:
        error++;
        break;
    }

    state_ = state;
  } else {
    error++;
  }
}

void setup() {
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);

  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);

  detectState();
  state_ = state;

  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.print("counter: ");
    Serial.println(counter);
    counter_ = counter;
  }

  if (error != error_) {
    Serial.print(error);
    Serial.println(" errors");
    error_ = error;
  }
}

Now my questions are:

Is there any way to improve the speed/safety of the performant/safe code? Any way to improve this code is appreciated.
Is it possible to have maximum speed and safety together or some trade-off in between?
What is the maximum frequency we can get out of this configuration?

Thanks for your help in advance.

Note that, instead of a XOR gate, you could use a single pin change interrupt on both channels.

@EdgarBonet Do you mean connecting two channels to two interrupts? that we can't do. The Arduino Uno/Nano has only two interrupts and we need one for other things. Is that what you meant?

No, I mean connecting the two channels to a single pin change interrupt. The Arduino has three pin change interrupts in addition to the two external interrupts.

I'm not sure what "pin change interrupts" is, but if you connect two channels to a single interruptable pin (i.e, 3 or 4)  then it works like an AND.

No, it doesn't. Do a web search for “Arduino pin change interrupt”, or “AVR pin change interrupt”.

@EdgarBonet OK. Reading this page, I don't think using pin/port change interrupts are a better solution. Unless I haven't understood your point and you may be kind to elaborate.

The MCU has pin change interrupts so that you don't need to add a XOR gate and use one of the external interrupt pins. You don't need a library for using them, and you probably don't want the overhead of a library anyway. Read Arduino Pin Change Interrupts.

@EdgarBonet please consider that the rest of the pins are not free. there are reading and writing other stuff. So if I use on the 3 available blocks of PinChangeInterrupts  (0-7, 8-13, A0-A5). I receive lots of unnecessary interrupts. The XOR helps to read both channels in "real-time" with just one interrupt pin and one normal one. See this image.

No, you don't receive unnecessary interrupts if you don't activate PCINT on the other pins.

@EdgarBonet what is the correct syntax for reading pins 4 and 5 (which are not interruptable) using the pin/port change interrupt? what binary/hexadecimal values should be assigned to the PCICR and PCMSK0/PCMSK1/PCMSK2?

This is just a partial, rushed answer.
You should be able to get a significant speed-up if you define your own
ISR for handling the interrupt, as in:
ISR(INT1_vect) { ... }

The Arduino way of using interrupts is instead
void trigger() { ...}

void setup() {
    attachInterrupt(int_number, trigger, CHANGE);
    ...
}

but this is slow, as it involves the ISR provided by the Arduino core,
which has to locate and call your interrupt handler. The way you wrote
the handler is wrong: either you define a regular function, without the
ISR macro, and go the Arduino way, or you go the plain AVR path and
define the ISR yourself, which should be named INTERRUPT_NAME_vect, in
which case you don't use attachInterrupt(). The way you did it is
probably the slowest you can get, as the compiler will needlessly add an
ISR-type prologue and epilogue to your handler.
As for the maximum frequency, that's hard to assess without testing, but
you may get some idea by reading this answer on interrupt
latency.

Edit: As I stated in my first comment to the question, a pin change
interrupt can be used instead of an external logic gate. Here is how to
do it.
First, one should look at the Arduino Uno pinout and see that:

digital 4 = PD4 = PCINT20
digital 5 = PD5 = PCINT21

Both pins are tied to the pin change interrupt request 2 (PCINT2_vect).
This interrupt can be configured in setup() as follows:
PCMSK2 = _BV(PCINT20)   // enable interrupt on pin PCINT20 = PD4
       | _BV(PCINT21);  // enable interrupt on pin PCINT21 = PD5
PCIFR  = _BV(PCIF2);    // clear interrupt flag
PCICR  = _BV(PCIE2);    // enable pin change interrupt request 2

Now, the interrupt will fire on every change of the logic levels of
inputs 4 and 5.
Then, in the ISR, the whole port D can be read in a single cycle by
just evaluating the corresponding pin input register, i.e. PIND. With
some shifting and masking, one can get a phase between 0 and 3
(the count is in Gray code: 0, 1, 3, 2, 0...). From the previous and the
current phase, one can compute the change that needs to be applied to
the counter:
// Handle pin change interrupt request 2.
ISR(PCINT2_vect) {
    static uint8_t previous_phase;
    uint8_t phase = (PIND >> 4) & 0x03;  // read input pins
    counter += encoder_delta(previous_phase, phase);
    previous_phase = phase;
}

The implementation of encoder_delta() is left as an exercise to the
reader. ;-)

Thanks. I will go through the new edits and will bother you if I had further questions.


text:
Can I power arduino uno R3 with 9v battery through Vin?
I want to power up arduino through Vin port , what should be the input voltage ?

Here is the answer - https://arduino.stackexchange.com/questions/39041/powering-an-arduino-with-more-than-5-v/39043#39043

Does this answer your question? Powering an Arduino with more than 5 V

About 7.5V to 9V is best. A 9V battery is often not capable to supply enough current for an Arduino. Do you have a multimeter to measure the battery voltage drop when the Arduino is connected ?

Are you really sure? I must search for mine, but what i remember, that over the pins....
ok I looked, sry, Jot was right :D... on the Input Pins, you find three kinds right? 3.3, 5 an Vin, which will be a range of V for sure ;)

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review


text:
Run two Loops Simultaneously on Arduino
I am not able to combine the below two sketches. What I require is to either run both the loops together or find a way to run both the functions inside a single loop.
Sketch 1
#include <SevSeg.h>
#include <DS1307RTC.h>
#include <Time.h>
#include <TimeLib.h>
#include <Wire.h>

// Create an instance of the object
SevSeg sevseg;
bool militaryTime = false; // true for 24 hour clock

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default. Recommended
  bool leadingZeros = true; // Use 'true' if you'd like to keep the leading zeros

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros);
  sevseg.setBrightness(90);
}

void loop() {
  tmElements_t tm;
  int time;
  int dot;

  if (RTC.read(tm)) {
    time = tm.Hour * 100;
    if (time > 1200 && militaryTime == false) {
      time = time - 1200;
    }
    if (time == 0 && militaryTime == false) {
      time = 1200;
    }
    time += tm.Minute;
  }

  if ((tm.Second % 2) == 0) {
    dot = 4;
  } else {
    dot = 2;
  }

  //Produce an output on the display
  sevseg.refreshDisplay();
  sevseg.setNumber(time, dot);
}

Sketch 2
// Change this to the output pin you are using
#define TICK_PIN A0

void setup()
{
  pinMode(TICK_PIN,OUTPUT);
  while (1) {
    tone(TICK_PIN,1000,2);
    delay(1000);
  }
}

void loop()
{
}

@LookAlterno Actually, the 2nd loop never executes because of the while in setup.

The second loop can actually be in the loop function as well. Either way, I am unable to combine the two to make it work.

Basically you need to get rid of the delay and any other blocking loops. Here is a way to do it.
Define this variable globally.
unsigned long lastTime = 0;

Then in your first loop, add the following code either to the beginning or the end:
if (millis() - lastTime >= 1000 || !lastTime) {
    lastTime = millis();
    tone(TICK_PIN,1000,2);
}

What is the !lastTime for ?

This worked very well

That looks familiar....just like my answer that was posted 3 hours before yours.

@JohnnyMopp Well, this is a common trick to emulate multitasking on arduino. After looking at yours, it doesn't solve the first execution problem which is done above. You can find this answer almost everywhere, it's not a rocket science.

That's OK, even though I didn't read your answer beforehand but I can delete my answer if that will make you happy ;)

Let it go. I've moved on......and the right thing to do is remove your unjustified DV on my answer.

Not a problem. Waiting for the edit to be approved before I can upvote you again. Also, I couldn't delete this answer because it was accepted.

@LookAlterno, I never used !lastTime. Perhaps I never needed to run something in the first execution of loop. After 50 days it could cause a glitch.

I fund the easiest way to work on this challenge when you have to deal with a long delay and think you need a second loop, is to make make a counter in the main loop using centiseconds (10 milliseconds) and then trigger your required response when the counter reaches your time like
void loop(void) {
counter=counter +1;
if (counter==100){
tone(TICK_PIN, 1000, 2);
counter =0;
}
....rest of code

One way is to use a timer callback.
// Include the timer1 library
#include "TimerOne.h"

// Other code here...

void setup()
{
    // Other setup code here....

    // Setup timer
    Timer1.initialize(1000000);          // 1 second
    Timer1.attachInterrupt(callback);    // Set callback
}

void callback()
{
    tone(TICK_PIN, 1000, 2);
}

void loop()
{
    // Code from 1st loop here...
}

If that doesn't work (if something else is using timer1) you could just keep track of the time between beeps:
uint32_t last_beep = 0;
const int beep_timeout = 1000;

void loop() {
    // Code from first loop here

    uint32_t now = millis();
    if (now - last_beep >= beep_timeout) {
        tone(TICK_PIN, 1000, 2);
        last_beep = now;
    }
}

Would the downvoters care to explain?

You actually read and understood my question better than the accepted answerer. The reason why I did not accept this was simply due to complexity. I upvoted your answer.

Run two Loops Simultaneously on Arduino

in general, the answer depends on your definition of "simultaneously".
But in this case, the answer is "definitively yes", as the other loop is empty.
a generic approach to this kind of questions is:
void setup(void) {
  setup1();  //run setup 1
  setup2();  //run setup 2
  ...
}

void loop(void) {
  loop1();  //run loop1
  loop2();  //run loop2
  ...
}

this approach would only fail if the original setup() and loop() are written poorly.

This might work in some cases, but not even closely for my case.


text:
Arduino and ESP8266 Two-way Communication
I've searched the internet quite a bit and all I find is how to make two esp8266 communicate. What I am trying to do is connect a single esp8266 to the arduino and have a two-way communication between them.
I want to send and receive data on both the Arduino and ESP8266. The concept is to send data to the esp8266 over WiFi connection and then send that data to the Arduino. The Arduino will manipulate it and send it back over WiFi.
I feel like this would be a common beginner example to have a two-way communication over a TX/RX connection, but I can't seem to find any. All examples I find are strictly one as sender and other as receiver.

Are you using the AIThinker AT firmware for the ESP8266?

See How can I verify that my ESP8266 is working? asked 2 hours before.
use something like https://www.sparkfun.com/products/12009 or https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion
Usual way is let the Arduino direct the ESP, but if you are able to program ESP too, then any communication can work the same way as between twou ESPs or two Arduinos (with the level shift in mind)


text:
Error: Cannot find module 'serialport'. node.js, Arduino Yun
I carefully followed Andy Sigler's tutorial on how to setup node.js on Arduino Yun. But I'm getting this error "Cannot find module 'serialport'". my node.js file is in mnt/sda1/arduino/node folder. and I have installed node-serialport successfully through ssh. Kindly helpc

Did you check that post "cannot find module 'serialport' using Node.js and Johnny-Five" ?

@J. Piquard I'm trying to use node.js in Arduino Yun. The post you mentioned is regarding installing node.js on a computer. It's not helpful..Thanks anyways.

I solved the problem by following these steps:
Make a folder node_modules in mnt/sda1/
cd /mnt/sda1
wget http://wiki.linino.org/lib/exe/fetch.php?media=wiki:serialport-1.6.1_mips-25-ubuntu.tar.gz -O serialport-1.6.1_mips-25-ubuntu.tar.gz
run $ tar xvf serialport-1.6.1_mips-25-ubuntu.tar.gz -C /mnt/sda1/node_modules


text:
Create a library without a class?
I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions.
I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE:  sizeof(), etc..
Is this possible?  If so, can anyone point me in the direction of a template?  I've been searching, but haven't found anything.
Thanks!

Have you tried creating a library like you've done before but not putting any classes in it?

Although this is not directly relevant to your question, sizeof(), like if() is NOT a function (although its syntax looks like one), it is an operator evaluated at compile time.

Ok, I was hoping this was possible, I read here that it wasn't possible: http://stackoverflow.com/questions/1735990/using-classes-with-the-arduino A few points down the page, someone wrote: > On Arduino you can use classes, but there are a few restrictions:

No new and delete keywords
No exceptions
No libstdc++, hence no standard functions, templates or classes
You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE. No standard

No new and delete keywords 2. No exceptions 3. No libstdc++, hence no standard functions, templates or classes - most of that is nonsense. You can use new and delete these days. You can use templates and classes. You can get the STL (standard template library) from StandardCplusplus. You have standard functions like malloc, memcpy, strcpy, etc.

You also will need to close the Arduino IDE when recompiling a library - when I am developing a library I use a standalone editor for editing the library. I don't need to close the IDE to test it.

May I suggest the use of static class methods?

Yeah, I use Notepad++ when I'm editing libraries with the Arduino IDE open to a sketch that includes those libraries.. seems to work ok.

Yes, it's possible.
Just don't make a class. Just make functions instead.
Like a class-based one, have a .cpp and a .h file. In the .cpp file (or .c file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.
In the .h file place prototypes for them. I am in the habit of adding the extern keyword, but you don't actually need to for functions.
For example:
foo.cpp:

void doSomething() {
    // whatever
}

foo.h:

extern void doSomething();

Then you can include your .h file and call your functions:
#include <foo.h>

// ...

doSomething();


text:
How to connect the 3.3v pin of arduino mega to multiple sensors
I am connecting 3 accelerometers to an arduino mega. I have everything except how to connect them to the 3.3v pin. I know that I can just connect the 3 of them to the same ground pin but I have been told I can't do the same with 3.3v pin. Can anyone tell me what is the best way to power them from the arduino mega?

You can connect all of them as long as the total current draw is not over 50mA as described here. If you need more than 50mA, you need to create your own 3.3v supply or use something like a breadboard power supply for instance (keep in mind to make a shared ground line).

Yes sorry, that's what I meant by connecting the 3 ground wires to the same ground pin. Can I do the same with the 3.3v pin then? Is that what you're saying? Just use a shared 3.3v line?

yes, take a look at the datasheet of your sensors. There should be a Max current field in the specs. If the sum of total max current in each sensor is less than 50mA you can use the 3.3v of arduino mega.


text:
Arduino, 74HC595N, magic
Good day
I'm playing with Arduino and shift register chip 74HC595N and already tried many different ways to solve my problem, but still to luck :(
So that is my current simple scheme:

Arduino 2,3,4 ports connected to data, clock and latch pins of 74HC595N. I've connected only first two output pins of chip to make minimum power consumption and to simplify this example as much as possible.
That is my sketch:
const int latchPin = 4; //Pin connected to ST_CP of 74HC595
const int clockPin = 3; //Pin connected to SH_CP of 74HC595
const int dataPin = 2;  //Pin connected to DS of 74HC595

void setup()
{
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  Serial.println("ON");
  digitalWrite(13, HIGH);
  send(B10000001);
  Serial.println("OFF");
  digitalWrite(13, LOW);
  send(B01000010);
}

void send(byte d) {
  Serial.println(d);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, d);
  delay(1000);
  digitalWrite(latchPin, HIGH);
}

And the problem is: sometimes leds are blinking but very unstable. Sometimes it's not working at all, sometimes only first led is blinking, but second one is not. Sometimes opposite - second led is blinking, first one is not. Sometimes one of led is blink very fast (just flash instead of 1 second delay).
If I touch wires and elements on breadboard - something changing. Even without touching anything - situation changing. It seems like problem is somewhere in connection or power supply and I've already tried to except it: tried few different breadboard, two different 595 chips, different wires and resistors, tried Arduino Uno, Mega and nano. Even tried atmega328p standalone, tried power it from USB, from 9v battery, old mobile charger (5.4V, 650 mA), tried to power arduino with external source (12V, 1A). In all cases the problem still exists.
I've already read a lot about power supply for Arduino, but I think at least few of the ways I've already tried to supply power is good enough for 595 chip and two LEDs - isn't it?
Please, advice me what else can I try?

Try moving the "delay(1000)" in send() to the loop() instead.

You haven't tied the OE pin (13) to ground.

@MikaelPatel: I've tried many different variants and nothing helped except Gerben's advice :)

@Gerben, Thanks a lot - seems like OE and MR pins was the reason. I'm still experimenting, but seems like that it helps!

Even this is quite old, to help others as well:
As you already did, pin 13 (output enable, active low) to ground and pin 10 (master reset, active LOW) to HIGH, to disable reset.


text:
Adafruit Motor Shield and Bridge Library for Yun Shield
I am using the Leonardo board with the Adafruit Motor Shield v2, 2 steppers and the Yun Shield. The yun shield and steppers all run harmoniously, however, as soon as I do Bridge.begin() and anything that accesses the Yun shield Bridge library to access the console, the steppers stop running. Is this to be expected and are there any solutions?
Thanks

Looking at Bridge.begin() description here
 you can see this is blocking function.

begin() is a blocking function. Once you call Bridge.begin(), nothing else will happen in your sketch until it has completed. This process takes approximately three seconds.


text:
Are there any electro-chemical sensors available to measure nutrient contents of soil?
I want to develop a soil fertility testing device and need an electro chemical sensor to do so.
I searched the online available sensors but didn't get any source. Does anyone knows anybody in development of such sensors ?

I think you would be better getting this question moved to SE EE.  They know more about general electronics.


text:
Burn bootloader finishes with "avrdude done. Thank you." but bootloader didn't actually get flashed
I've built a a stripped down version of the Arduino Nano that has some peripherals removed and three connectors for analog sensors I want to use. I'm trying to burn the Arduino Nano bootloader onto this custom board using the sparkFun AVR Pocket Programmer and from the Arduino IDE console it seems to say that it was burned successfully. But when I plug the board back into the computer it still shows up as a COM port instead of an Arduino device. This is the output I get in the console after I press burn bootloader with "USBtinyISP" selected as programmer and Arduino Nano as the board.

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbtiny
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x1781-0x0c9f
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, https://learn.adafruit.com/usbtinyisp
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% -0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: load data flash data from input file C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: input file C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.01s

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

Reading | ################################################## | 100% 0.00s

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

The burning is pretty much over instantly and you can see the reading and writing take 0.00s, it should be closer to a minute rather than an instantly. It's faster than uploading a simple sketch to the Arduino. When I unplug the programmer and plug the device back via USB, it just shows up as a COM port instead of "Arduino Nano" - which doesn't allow me to program it via the Arduino IDE.
What is very strange to me is that I can program the device over the command line. If I follow the AVR Pock Programmer instructions "Using AVRDUDE via Command Line" and use a hex file generated from the Arduino IDE, the code uploads fine and runs fine. I wrote a sketch that prints the ADC values over the command line and after flashing via command line it's running as expected.
I've tried to upload the Arduino booatloader via command line as shown in this tutorial under "Uploading Code - Hard Way" and this time it takes over 43 seconds to write to flash and 30 seconds to read from flash so I thought it worked. However when I plug it back in, it STILL just comes up on my computer and the Arduino IDE as COM9.
This is the output I get when trying to flash the bootloader via command line:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot
λ avrdude -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m

avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : lpt1
         Using Programmer              : usbtiny
         Overriding Baud Rate          : 19200
         AVR Part                      : ATMEGA328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65     5     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as 5
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

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

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

Reading | ################################################## | 100% 0.02s

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

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

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

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

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

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

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

Reading | ################################################## | 100% 0.02s

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

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot
λ avrdude -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328.hex -U lock:w:0x0F:m

avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : lpt1
         Using Programmer              : usbtiny
         Overriding Baud Rate          : 19200
         AVR Part                      : ATMEGA328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65     5     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "optiboot_atmega328.hex"
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 43.63s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328.hex:
avrdude: load data flash data from input file optiboot_atmega328.hex:
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 30.69s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

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

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

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

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

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

I've reviewed my schematic multiple times, comparing it to the actual Nano schematic but I can't see anything that would cause it to fail - it's almost identical ! I've built two of these boards and they behave the same exact same way. Schematic shown below.

your post does not make sense ... you are using an FTDI chip, which presents itself as a serial port

But the FR32RL is the same chip that the Arduino Nano uses - and the Nano shows up as an Arduino Device when it is plugged in. You can program it directly using the Arduino IDE.

Would I need to do that to use the Arduino IDE for flashing ?

I'm not quite clear on what that means - could you explain a little more?

old PCs had a DB25 parallel port used for printers ... also called Centronics port ... it had 8 bi-directional data pins and some handshaking pins ... LPT1 is usually the name for the parallel port as opposed to serial port COM1

Why does it find the device and read/write to flash if the port is wrong ?

I do not know ... it is just that lpt1 leaped out when i looked at the printout

The short flash time makes sense if you think about the size of the bootloader. It should not occupy all of the 32KB! Commonly it is much smaller than the typical sketch. If avrdude tells you that 32KB are flashed, then most of the contents should be 0xFF - please check this. Since 0xFF is the erased byte value of a flash memory, there is nothing to do for these bytes, resulting in very short flash times.

try a manual reset while avrdude attempts to upload

The Arduino 'device' is identified by the USB device code of the USB to TTL Serial on Arduino or by core code in case of MCU with native USB. The USB ids are written to the USB chip in factory or are part of the firmware/core and they are listed in boards.txt file so that the IDE then knows what Arduino is attached. If you use a common FTDI it doesn't have this Arduino vid and pid codes, which identifies the device as Arduino.
Note: I think you asked a different question then your real problem is, because you assumed that the name of the port not showing Arduino is the reason why the upload doesn't work. It is so called X->Y problem. You have a problem X but asked about problem Y. I answered the question asked.

I see. Does that mean it won't be possible to flash this board via the Arduino IDE ? I'll just need to keep flashing through the command line ?

@VanGo, if you have the right COM port in Tools menu, you can upload. it doesn't have to say 'Arduino'

I've tried this, but I end up with a bunch of these messages "avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00" and then it fails. I've tried pressing the reset while it's uploading but no difference...

There are different bootloaders implementing different protocols. You might need to select another protocol/bootloader.

@VanGo, that is a different question

@Juraj thanks for the pointers. It was indeed another issue - I had the Arduino Tx/Rx plugged into another device. When I tried uploading code via the Arduino IDE with the Rx/Tx pins unplugged from the other device - it let me upload successfully even though the device still just shows up as a COM port. Thanks !


text:
Can a video game potentially detect arduino leonardo?
If I automated an action in a video game through arduino leonardo, can it be detected? Things like autohotkey can be easily detected, however i would expect an arduino would be far more difficult. How easy/difficult would it be detect?

it all depends on the game, and on the controller that you are emulating ..... for example  if the game is a first person shooter and the arduino is pulling the trigger exactly every 95 ms then the game may be able to determine that you are not pressing the keyboard manually

It would be little use to only check for Arduino's. You would in some way have to check the player's behaviour and estimate if it's 'human', which works for any type of automation.

Nigh on impossible. True the game could look to see if there is a specific VID/PID combination visible to the computer, but that is probably not going to happen (and anyway you can change it).  As far as the game is concerned, input from a keyboard is input from a keyboard, whether that keyboard has buttons or a piece of code it really can't tell.

Yes.
First you'll need to define how you plan to inject the new input signal, into the data "packets" as a spoof of controller signals, or just jumping the switches?
In the context of any modern gaming console, it could be detected. Easily. Consoles and controllers use any number of proprietary protocols which sync.commands to improve response and reduce controller lag. If you're just jumping the switches, then no, you could simulate hadouken and probably get away with it just fine.
If you're referencing PC gaming, then that would be hard if not impossible with the variance of input control available.  The best deterrent would be the security of the game software itself and the genre of the gaming. Some games actively encourage Hotkeys.


text:
Correct position for buttonState in my FSM
I wrote a FSM with the help of some tutorials through out the world wide web and so far it does what I want to do with it.
But one thing that is not the way I want to be, is to exit the state noLightPause during the non blocking delay with the button to enter the yellowLight state again.
I cannot figure out where to put the buttonState inside my code, if it should be that simple to exit that state, because it was hard enought for me to get my machine going to that point :D.
Do not get confused, I soldered the button from ground to the pin, so LOW gets the input :).
Hope you guys can help me with that problem to get me further with my machine.
Thanks in advance for all your help, here is my code:
#include <FastLED.h>

#define NUM_LEDS 16

CRGB ledStrip [NUM_LEDS];

const int buttonPin = 4;
const int ledStripPin = 8;
const int ledOnBoard = 13;
const int interval = 100;

int buttonState = 0;
int lastButtonState = 0;

int ledOnBoardState = LOW;

unsigned long previousMillis = 0;
static unsigned long noDelayPause;

enum statusType {whiteLight, yellowLight, noLightPause, noLight};

statusType currentStatus = whiteLight;

void setup() {

  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledStrip, OUTPUT);
  pinMode(ledOnBoard, OUTPUT);

  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS).setCorrection(DirectSunlight);
  FastLED.show();
}

void loop() {

  //----------------------------------------
  // just to see if the machine is blocking something

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    if (ledOnBoardState == LOW) {
      ledOnBoardState = HIGH;
    } else {
      ledOnBoardState = LOW;
    }
    digitalWrite(ledOnBoard, ledOnBoardState);
  }

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

  switch (currentStatus) {

    case whiteLight:
      currentStatus = whiteLightFunction();
      break;

    case yellowLight:
      currentStatus = yellowLightFunction();
      break;

    case noLightPause:
      noDelayPause = millis();
      currentStatus = noLightPauseFunction();
      break;

    case noLight:
      if (millis() - noDelayPause > 1000) {
        currentStatus = noLightFunction();
        break;
      }
  }
}

statusType whiteLightFunction() {

  if (digitalRead(buttonPin) == LOW) {

    return (yellowLight);

  } else {

    fill_solid(ledStrip, NUM_LEDS, CRGB::White);
    FastLED.setBrightness(100);
    FastLED.show();

    return (whiteLight);
  }
}

statusType yellowLightFunction() {

  if (digitalRead(buttonPin) == LOW) {

    fill_solid(ledStrip, NUM_LEDS, CRGB::Yellow);
    FastLED.setBrightness(100);
    FastLED.show();

    return (yellowLight);

  } else {

    return (noLightPause);
  }
}

statusType noLightPauseFunction() {

  fill_solid(ledStrip, NUM_LEDS, CRGB::Black);
  FastLED.show();

  if (digitalRead(buttonPin) == LOW) {

    return (yellowLight);

  } else {

    if (digitalRead(buttonPin) == HIGH) {

      return (noLight);
    }
  }
}

statusType noLightFunction() {

  if (digitalRead(buttonPin) == LOW) {

    return (yellowLight);

  } else {

    return (whiteLight);
  }
}

I'm not sure I follow the question, "Where do I put the buttonState".  You are reading the button inside the function and letting that decide which status to take next.  That sounds perfectly reasonable.  What is happening or not happening right now that doesn't meet your expectations?  Compare and contrast the symptom and expected behavior a little.

You should also introduce a button state to have the FSM working as a FSM
 bool buttonState = false;

in the loop you check for the press/release and change the state:
if (digitalRead(buttonPin) == LOW && buttonState == true) buttonState == false;
if (digitalRead(buttonPin) == HIGH && buttonState == false) buttonState == true;

inside your function you only go for buttonState eg
statusType noLightFunction() {
if (buttonState == false) {  // Button is NOT pressed

    return (yellowLight);

  } else {       // Button is pressed

    return (whiteLight);
  }
}

The button acts as a toogle switch as long as you keep it pressed (or released) nothing will change only the state changes caise an action to happen. I personally use "speaking" vars I still know years later so instead of
buttonState I use buttonIsPressed but thats flavour

Thanks for your advice Codebreaker. I will do that to complete my FSM and I found a solution that kinda does what you describe here. The yellowLight state returns with a simple: if (millis() - noDelayPause > 1000 || digitalRead(buttonPin) == LOW). Or after the time has passed it goes into the whiteLight state.

Be aware that the solution with going directly to read the pin in the function wont work in more complex scenarios due to processing time and other issues. Please close the question as solved/accepted

when comparing boolean values, do not use if (buttonState == true) ... use if ( buttonState ) or  if ( !buttonState )


text:
Error messages while verifying code with Visual Studio Code
I move recently to use Visual Studio Code to develop for arduino. But I'm receiving some error messages while I'm trying to verify my code that confuse me. The messages are:
2020-04-12T13:53:40.409Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=20892E5EE7E84976
2020-04-12T13:53:40.926Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=20892E5EE7E84976, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:40.926Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
2020-04-12T13:53:40.937Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=D8C082A90BB14CDF
2020-04-12T13:53:41.044Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=D8C082A90BB14CDF, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:41.044Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404

Based on this output it seems something is happening with these URLs but when I try to do the same in the same computer with Arduino IDE there is no such error messages.
Does anybody know how to get rid of these messages?
Thank you very much.

Downgrade your Arduino IDE to a version below 1.8.10.

It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

You have to downgrade to January release 1.42 AND
Then turn off automatic updates for the moment.

How to get the release: Click here
Before installing /downgrade
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino_debug.l4j.ini fixes it for now.

Thank you corebreaker007. I was aware of the debug logging problem as that was the first issue I ran into and after some research, I was able to work it out. I'm using Arduino ide 1.8.12, Visual studio code 1.44 and Arduino extension 0.3.0. I will try to downgrade following your advice. After trying to find a replacement for Arduino IDE as the editor is far from being perfect, I thought that Visual Code could be a fit as it's simple but complete. It's a pity because it seems there are many minor mistakes that are time-consuming to have a platform you can rely on. Thank you for your help.

Also check out the PlatformIO extension for VSCode!


text:
How to assign a string-variable to a StackString based on the StackString-library?
I'm trying to use the StackString-library which offers not to eat up RAM over time by re-assigning values to strings. I started from scratch and wrote a very basic democode which works.
Then I added an assignment to a STackString-variable from a normal string or a function with return-value string
See code below
If I try to compile
I get a compiler-error saying
no matching function for call to 'Stack::StackString<50>::append(String&)'
here is the code
#include <StackString.hpp>
using namespace Stack;  // it is very important to have this line of code. Otherwise the code won't compile

StackString<50> myString = StackString<50>("Hello, World!");

String NormalString = "1234Test";

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println(myString.c_str());

  myString.prepend("Everybody say: ");
  Serial.println(myString.c_str());

  myString.append(" How are you doing?");
  Serial.println(myString.c_str());
  Serial.println();

  //myString = NormalString;
  myString.append(NormalString);

}

void loop()
{ // put your main code here, to run repeatedly:

}

Do I have to do some typecasting? and if yes how does it look like?
WHat I want to do is assigning a StackString a new value. This means the STackString is on the left side of the "="  assigning operator. I have tried different variants to no avail.
Could this be a problem of the special construction as a "namespace" ?
No idea no clue
you find the STackString-library here:
https://gitlab.com/arduino-libraries/stackstring
best regards
Stefan

Are char arrays really so daunting that people go to this length to avoid them?  Why struggle with this when you could just write a char array and be done with it?

You are writing this from a position of beeing an expert about arrays of char, c-strings etc. This does explain nothing to come nearer to the point of enough knowledge to use your preferred way of using "strings". So a much more productive comment would be to explain how it works. Not with a most short and elegant single line of code but with a thoroughly explained example with lots of comments or additional text.

StackString doesn't know what a String is.  The append function only accepts a const char *, a const char or an int:
void append(const char* string);
void append(const char character);
void append(int number);

You can get a const char * from a String easily enough with .c_str(), so use that in the append:
myString.append(NormalString.c_str());

There is also no simple assignment (or complete content replacement) with StackString - you have to "clear" the string first.  So to replace the content with what is in NormalString you would:
myString.clear();
myString.append(NormalString.c_str());


text:
Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?
I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.
Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?
I have tried that name and know it probably isn't that.  Still poking around.

Various limits.h files in the avr-gcc hierarchy define ULONG_MAX, which may be the value you want.  For example, on my system such files have paths ending with hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h or with hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h and contain definitions like the following.
/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, LONG_MAX also is defined in limits.h.
Note, arithmetic done in a form like
timeDelta = micros() - prevTime;

will be correct (regardless of whether micros() overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.

You don't need "to compensate for a roll over condition".
See my answer: https://arduino.stackexchange.com/a/33577/10794

in an Arduino compiler?

The "Arduino" compiler is a C++ compiler. That is the starting point for most questions. If you Google for:
maximum unsigned long in c++

You will find the first link leads to:
http://www.cplusplus.com/reference/climits/
In that it says:
ULONG_MAX   Maximum value for an object of type unsigned long int

Did you try to do this?:
unsigned long maxUnsignedLong = 0UL - 1UL;

or:
const unsigned long ULONG_MAX = 0UL - 1UL;


text:
How to logically tell than an UNO is being, or about to be programmed
I have an MIDI application that uses the RX and TX serial interface.  When I program the UNO there is a collision between the on board programmer and the MIDI application RX serial port.  The MIDI shield provides a jumper to disconnect to prevent the collision during programming.
I would like to add a FET switch to open and close if I am programming, but it's not clear to me that there is a signal I can tap into on the UNO that indicates programming is about to start or that it has just finished.
I was thinking about using a pull up on a digital pin on the UNO that drives low when the program starts up. That might be the way to go, but I assumed that this must be a common issue with a common solution that I am just not finding on stack exchange.
Is there a standard logical way to tell that UNO is about to be programmed via the onboard USB port?

Your proposed solution is the normal method. A GPIO pin which is an "Activate Device" signal. It's pulled in one direction, the "inactive" direction, and you actively drive it in the other "active" direction in your program.


text:
Arduino MIDI Program Change to Voodoo Labs GCX Converter
To define the problem, the L6 Helix can generate 6 immediate MIDI messages. These messages are pretty flexible as to what you want, but the Voodoo Labs GCX needs at least 8 CC messages to properly configure it worst case. Also, I don't want to burn all of my immediate commands to control most of the GCX. So I had the idea to create a Arduino project that would take MIDI PC and MIDI Bank Select to produce a 8 bit value which I could then convert into 8 CC messages between CC#80 and CC#87.

To solve this problem I used an Arduino UNO and a Olimex MIDI shield. I also want to use MIDI PC messages and Bank Selects.
For reference:

A Channel 16 PC 77 with Bank select 0 converts to binary 0x4D => Binary 01001101
A Channel 16 PC 77 with Bank Select 1 converts to binary 0xCD => Binary 11001101

Just to point out, the Bank Select value basically controls bit 8 and the PC value represents bits 6 down to 0
Based on the binary output, I scroll through bits 0 to 7 and send messages on CC 80 to CC 87. If a bit is a 1, I turn the loop on by setting the corresponding CC value to 127 and if it is a zero, I set the CC value to 0.
The Helix can generate a Bank Select and PC as one message, so for the price of one message, this project will make me 8 CC#'s effectively. ;)
It should allow other messages through, with the Arduino's SW loop latency. There maybe some other side effects to, but those should be limited to channel 16 only.
I have tested this on a Arduino UNO board with an Olimex MIDI Shield.
// GCX Editor
// By Rich Maes
// Converts MIDI PC's on channel 16 to GCX CC's starting at 0x80
// Allows everything else to pass.

#define MIDI_PC_CH16 0xCF
#define MIDI_CC_CH16 0xBF
#define MIDI_SYSEX 0xF0
#define MIDI_SYSRT_CLK 0xF8

boolean byteReady;
boolean sendCCMessage;
int ccMsgsToSend;
unsigned char midiByte;
unsigned char capturePCByte;
unsigned char captureCCByte;

// Queue Logic for storing messages
int headQ = 0;
int tailQ = 0;
unsigned char tx_queue[128];

int getQDepth();
void addQueue(unsigned char myByte);
void addCCQueue(unsigned char captureCCByte, unsigned char capturePCByte);
unsigned char deQueue();

static enum {
    STATE_UNKNOWN,
    STATE_1PARAM,
    STATE_1PARAM_CONTINUE,
    STATE_2PARAM_1,
    STATE_2PARAM_2,
    STATE_2PARAM_1_CONTINUE,
    STATE_PASSTHRU
  } state = STATE_UNKNOWN;

void setup() {
  // put your setup code here, to run once:
  //  Set MIDI baud rate:
  Serial.begin(31250);
  sendCCMessage = false;
  byteReady = false;
  midiByte = 0x00;
  state = STATE_UNKNOWN;
  captureCCByte = 0;
  capturePCByte = 0;
  ccMsgsToSend = 0;
}

int getQDepth() {
int depth = 0;
    if (headQ < tailQ) {
        depth = 128 - (tailQ - headQ);
    } else {
        depth = headQ - tailQ;
    }
    return depth;
}

void addQueue (unsigned char myByte) {
    int depth = 0;
    depth = getQDepth();

    if (depth < 126) {
        tx_queue[headQ] = myByte;
        headQ++;
        headQ = headQ % 128; // Always keep the headQ limited between 0 and 127
    }
}

void addCCQueue(unsigned char myCaptureCCByte, unsigned char myCapturePCByte) {
    int i;
    if (getQDepth() < 80) {
        // There is enough space to add our CC messages
        for (i = 0; i < 8; i++) {
            addQueue(0xBF);
            addQueue(80 + i);
            addQueue(127 * ((((myCaptureCCByte * 128) + myCapturePCByte) >> i) % 2));
        }
    } else {
        // This is an error condition.  So reset the queue and pointers
        headQ = 0;
        tailQ = 0;
        byteReady = false;
        for (i = 0; i < 128; i++) {
            tx_queue[i] = 0;
        }
    }
}

unsigned char deQueue() {
    unsigned char myByte;
    myByte = tx_queue[tailQ];
    tailQ++;
    tailQ = tailQ % 128;  // Keep this tailQ contained within a limit
    // Now that we dequeed the byte, it must be sent.
    return myByte;
}

void loop() {
    if (byteReady) {
        if (midiByte >= 0xF0) {
            // This automatically passes all clocks and System Realtime Messages
            state = STATE_PASSTHRU;
        } else if (midiByte >= 0x80) {
            switch (midiByte) {
            case MIDI_PC_CH16:
                state = STATE_1PARAM;
                break;
            case MIDI_CC_CH16:
                state = STATE_2PARAM_1;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }  else {
            switch (state) {
            case  STATE_1PARAM:
                capturePCByte = midiByte;
                state = STATE_1PARAM_CONTINUE;
                addCCQueue(captureCCByte, capturePCByte);
                break;
            case STATE_2PARAM_1:
                if (midiByte == 32) state = STATE_2PARAM_2;
                else state = STATE_2PARAM_1_CONTINUE;
                break;
            case STATE_2PARAM_2:
                state = STATE_2PARAM_1_CONTINUE;
                captureCCByte = midiByte;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }
    }

    if ((state == STATE_PASSTHRU) && byteReady) {
        // Just pass messages unaltered.  Also don't let any of our modified message through if
        // we are passing though.  Our burst of modified CC# can wait.
        // Serial.write(midiByte);
        addQueue(midiByte);
        // state = STATE_UNKNOWN;
    }
    byteReady = false;

    if (getQDepth() > 0) {
        // We have a byte to send, dequeu and send it
        Serial.write(deQueue());
    }
}

// The little function that gets called each time loop is called.
// This is automated somwhere in the Arduino code.
void serialEvent() {
  if (Serial.available()) {
    // get the new byte:
    midiByte = (unsigned char)Serial.read();
    byteReady = true;
  }
}


text:
Send sensor information to processing
I am currently working on an Arduino project where the Arduino will send data to a processing program via bluetooth and processing will draw the data. However, my code doesn't seem to work.
Here is my Arduino code:
#include <SoftwareSerial.h>

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
  Serial.println("Hello");
}

And here is my Processing code:
import processing.serial.*;
Serial myPort;

void setup() {
  myPort = new Serial(this, "COM42", 9600);
  myPort.bufferUntil('\n');
}

void serialEvent( Serial myPort) {
  String data = myPort.readStringUntil('\n');
  println(data);
}

I identified that the incoming port from the HC-05 module is "COM42" from my Bluetooth settings. I am expecting to see several "Hello" lines being printed on the processing console but this does not happen

Your whole sending program is a complete mess, sorry to say:
First you create a SoftwareSerial port using the HardwareSerial pins. (Why on earth would you do that?)
Then you "begin" that SoftwareSerial port.
Finally you try and print Hello through the HardwareSerial port!
Either use SoftwareSerial OR use the hardware UART. You can't mix and match both. And since you are using the hardware UART pins, why even consider using SoftwareSerial?
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println("Hello");
}

OR, to use other pins than 0 and 1:
#include <SoftwareSerial.h>

const int bluetoothTx = 2;
const int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
    bluetooth.println("Hello");
}

This worked! But can you please explain why it didn't work at the first place? Also, the modified code didn't work till after I modified the COM port to be the "outgoing" one as seen in my Bluetooth settings, why is that?

Before you had turned on the hot tap on the bath and were wondering why the toilet hadn't flushed. You had created and configured a software "bit banged" serial interface, but then proceeded to attempt to send the data down the unconfigured and disabled hardware UART.


text:
9V Vin powered Mega - 3V instead of 5V
I'm experiencing an issue with an Arduino Mega 2560 :
I powered the board through the Vin using a +24 --> 9V voltage regulator. When I power the board and measure the 5V output from the board, the voltage quickly drops from 5 to ~3V within seconds.
However, while powering with USB, the 5V output from the board gives us a clear 4.8V.
I have checked the 9V Voltage regulator (connected to the Vin), and it has a +24V input which remains stable (as should the 9V).
Any thoughts ?

How much current are you drawing from the regulator? In other words, what is connected to the regulator (if any) other than the Mega? Also, what is powered by the Mega?

Much more essential question is what 24V -> 9V voltage regulator. Even 100mA means 1.5Watts turned into the heat on it if it's simple 7809 linear voltage regulator.

And what are the specs, esp. max output current, of the 24v - 9v regulator?

Roberto Lo Giacco > The Arduino board is the only component connected to the 9V regulator. I measured only 2mA from the +9V to the Vin. The mega powers two Leds, 1 TFT (1,8"), and 1 SD card reader.

KIIV > The Voltage regulator is made using a LM7809C. Two capacitors are used both from input to ground and from output to ground (as specified in the spec).
JRobert > The voltage regulator is designed to handle up to 1A.

Well, "designed to handle up to 1A" - yes and no. Yes if you have huge heat-sink on it at this voltage drop. So if you can carry it's safe operating area, it can deliver 1A (with 15Watts of power dissipation P = (24V - 9V) * 1A ).

All right, thank you.
I noticed that after 20" or so, the heatsink becomes very hot (burning when touching), and this is the time when the voltage drops. I think there is some sort of overheating issue (although only 2mA are running through the 9V connector).

Power consumption about 2mA is highly unlikely as ATMega2560's consumption should be about 1mA per 1MHz so at least 16mA and add another for voltage regulator, LCD, LEDs...

So, according to the comments the main problem should be a thermal protection in LM7809C regulator.
The voltage drop between regulator's input and output is about 15 Volts and even with current consumption about 150mA it means 2.25W of power dissipation on it.
For such a big difference between input and output voltage switching regulator is recommended. (Or 9V power supply instead of 24V)
And it is not possible to have 2mA current consumption. I've just measured power consumption of bare Arduino Mega 2560 and it is 81mA through barrel jack input (9V) without anything on it. Not even blinking Led. So if you've measured for example 0.2A it's not 2mA but 200mA

I cannot change the power supply as it is powering another device (24V).
I will have a look at the switching regulators, ty.
However, how can the device not work with ~1% of its maximal current ? Could this be an issue related to the capacitors ? The manual I used gives a circuit at the page 18 : http://docs-europe.electrocomponents.com/webdocs/0e1f/0900766b80e1f8e6.pdf

Use DC-DC converter then. There are loads of them at ebay or so. And it's not possible to have only 2mA consuption not even with bare arduino board.

Thank you KIIV.
It seems like the voltage regulator was the cause of this issue, since providing it a +12V (instead of +24V) has given us a good and steady +9V output (connected to the Arduino Vin). I think this was an overheating problem.
We've bought another DC-DC regulator as adviced to prevent this issue.

@EtienneP. Well, then you can mark it as a solution.

"how can the device not work with ~1% of its maximal current" because your measurement is wrong, and because even with a correct current measurement, the limit being hit is the power one, where the huge voltage drop you are asking it to regulate across is a multiplier.


text:
How can I have the user instantiate an object?
So I'm building a MIDI controller. It has a 16-positions selector that lets the user select a "program": a playlist of commands to send to a MIDI instrument.
A push-switch allows the user to scroll through that playlist, running each command in sequence, one at a time.
The way I'm trying to implement this is as follows:
Playlist is a pure abstract class and each Program is derived from it. Each Program would have their own methods for each step, an array of pointers to these functions and a public playNext() method that loop() could call whenever the push-button is pressed with program.playNext()
I'm stuck at the selection of a program stage. I guess I could have an array of pointers to each program and call *arrayOfPrograms[currentProgram]->playNext()
but that would mean I would have to instantiate all the programs in setup() and keep them alive at all times...
Is there a way I could only instantiate the selected program and still call its playNext() method easily?
Sorry for the noob question. I'm fairly new to this and it gets confusing very quickly ;-) Thanks for your help.
Max

You want to be very careful using dynamic objects on such a tiny system.  Do you actually need distinct behavior from these objects?  If not, consider having just one eternal one and passing it some data.  It's not that this is impossible, but on such a tiny system there is very little tolerance for any sequence of operations that could push the memory allocator into fragmentation.  This is a world where you have to code with a mind to how things actually work, not just what is most expressive of ideas.

I could indeed have one single "command runner" and pass it data from arrays but then those arrays should exist in RAM at all time, right? I don't know how big these arrays could become, nor how many should be used. I figured that storing each one in its own object would allow for better RAM usage (provided objects get deleted appropriately of course)

Where is the data coming from?   If internal program flash, you should avoid copying it to RAM at all.  If an external source, you should try to load it only some buffering ahead of as you need it.  You only have 2K of ram, and that needs to handle everything.

You seem like you are almost there. Allocate the objects using new and free with delete.
// Abstract parent
class Playlist {
    public:
    virtual void playNext() = 0;
    // etc.
};
// Derived classes
class Something : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
class SomethingElse : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
// More derived classes......

// A pointer of the current program
Playlist *play_list = nullptr;

// A factory function to create a Playlist while also freeing previous
Playlist * create_playlist(int which_program) {
    // Important - delete old
    delete play_list;
    play_list = nullptr;
    // There are only 16 types, use a switch or if
    switch (which_program) {
        case 1:
            // Create a new one and save in global ptr
            play_list = new Something;
            break;
        case 2:
            play_list = new SomethingElse;
            break;
        // More cases here.....
    }
    return play_list;
}

[edit]--------------------------
Ok. The issue is that C++ does not have a lot of reflection options. So you can't create a class only by its name (as a string). Here's another solution I came up with. It's not completely automatic as it involves registering each class in setup. But I think it's close to what you want:
class Playlist;  //Forward declaration

// Each class will have a function to create itself
typedef Playlist * (*CreateFunc)();

// The parent class. It also holds a list of all child classes
// Could probably refactor into 2 separate classes
class Playlist{
  public:
  // Need virtual dtor
  virtual ~Playlist() {
    delete last_created;
  }

  // Put all the overridable function declarations here
  virtual void playNext() = 0;

  // This has to be called for each child. (See macro below)
  static void register_class(int id, CreateFunc f) {
    all_maps[num_maps].id = id;
    all_maps[num_maps++].f = f;
  }

  // Factory method to instantiate an object
  static Playlist * create_playlist(int id) {
      // Delete old pointer
      if (nullptr != last_created) {
          delete last_created;
          last_created = nullptr;
      }
      for (int i = 0; i < num_maps; i++) {
          // Search the list for name match
          if (id == all_maps[i].id) {
              // Call the creation func
              return all_maps[i].f();
          }
      }
      return nullptr;
  }
  protected:
  // A struct to hold the class name and a pointer to the creation function
  struct Map {
    int id;
    CreateFunc f;
  };
  static Map all_maps[32];
  static int num_maps;
  static Playlist* last_created;
};
// Static declarations
Playlist::Map Playlist::all_maps[32] = {{0, nullptr}};
int Playlist::num_maps = 0;
Playlist* Playlist::last_created = nullptr;

// Example child class
class Child1 : public Playlist{
  public:
  void playNext() {Serial.println("Child1");}

  // Must have this function and it must be static
  static Playlist * create() {return new Child1;}
};
// Another example
class Child2 : public Playlist{
  public:
  void playNext() {Serial.println("Child2");}
  static Playlist * create() {return new Child2;}
};

// Helper macro to simplify registering
#define REGISTER_PLAYLIST(id, name) Playlist::register_class(id, &name::create)

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

  // This must be done for all classes
  REGISTER_PLAYLIST(0, Child1);
  REGISTER_PLAYLIST(1, Child2);

  // Example usage
  Playlist*p = Playlist::create_playlist(0);
  p->playNext();
  p = Playlist::create_playlist(1);
  p->playNext();
}

void loop() {

}

I just whipped this up. Probably room for improvement....

Thanks Johnny! That clears it up a bit. But I'm still stuck with a switch or an if. That'll be a pita when I implement more playlists.
I'd love it if I could find something more convenient...

@Max C++ does not have much in the way of reflection (finding all classes of a certain type, for example). I've updated with another example I think is closer to what you want. Personally, I prefer the first example for its simplicity.

Great! Thx a lot. I'll investigate that.

Well your first suggestion worked great while I was toying around with it and I got to learn quite a lot in the process. Thanks for that ;-) But then I hit another roadblock: because I need the user to select playlists whenever he/she wants, I wrote the switch and therefore the object instantiation in loop()... and I can't find a way to keep the object alive longer than the loop it has been created in. I wish I could just add 'static' to the create_playlist function...

@Max Not sure I understand. The play_list should be a global variable. Once you create it, it exists until you delete it and should be accessible by all parts of your sketch.

...Maybe it is confusing because the function returns a pointer. That's just a copy of the global variable. You can ignore that, and just use the play_list global variable.

You're right, Johnny. I had messed up my code but now it's all fixed and working fine. Thanks to you and the others for your input. Learned a lot, which always a great feeling. ;

I'm not fully understanding the way your sketch should work.
However, I think what you need is some kind of Controller object.
The controller object instantiates one program. The controller also keeps a Boolean to play the next one (playNext). Once the program finishes, the controller can delete the just played program, checks if the Boolean is set to play the next, instantiate the next program to play and play it.
This results that programs are not depending on each other.

Yes that makes sense. Thanks for the idea.

But my problem is even noobier: I don't know how to code it! How do you instantiate an object when you only know which one at runtime?

I don't fully understand ... you can instantiate an object at runtime depending on the switch (or state).

I'm sure I can. I just don't know how to do it efficiently. A switch case would work for now but isn't there a better way? Later, I'll probably implement a way to select more than 16 programs (more like 99) and the switch will be cumbersome to say the least...

In that case I would need more about how it works ...  you have a 16 knob selector for the programs. And each program has commands. And the knob is to loop the current command? So e.g. suppose program 12 is selected. Program 12 has 20 commands, running command 0, than command 1, etc. When you press the button during command 10, command 10 loops until depressed and command 11 is continued? And what happens after command 19? Command 0 is started again of the same program?

Yes except that the commands don't loop. You just run them once and next you press the button, the next command runs, and so on.

The knob lets you select which 'list' of commands you want to run through with the button.


text:
Grounding for arduino, measuring phase controllled 240V
I would like to measure a phase controlled 240Vac waveform as a digital PWM input for an arduino. The signal would look something like this:

My intent was to use a zener clipping circuit to limit the positive portion of the waveform to 5V, and measure that signal. However, I want to make sure I'm properly grounding these items. This is what my proposed circuit looks like, with all components inside a metal chassis.

I feel like ideally I would isolate this waveform from the system controller/light with a 1:1 transformer, but I'm unsure if that is feasible given its irregularity. Can I safely connect the arduino ground to the system's neutral, or am I barking up the wrong tree?
Thanks!

The more I think about it, the more I think that I should tie Arduino ground to chassis ground and rely on N and G being within a few volts of each other.

How can you get current flowing around the circuit without that ground connection? However, you really want to invest in some form of galvanic isolation to keep the mains away from the Arduino.

You shouldn't really connect the mains direct to the Arduino like that - even with a zener. The potential for disaster is somewhat large.
Instead you should galvanically isolate the mains from the Arduino. I would use something as simple as an opto-isolator:

simulate this circuit – Schematic created using CircuitLab
Make sure that R1 is rated for at least 339V and can dissipate enough power (1W). The resistance of R1 needs to be small enough that the opto-isolator triggers properly, yet large enough that you don't need a great honking heater of a resistor to cope with the power. 150K seems a reasonable compromise.
D2 is needed to prevent the LED In the opto-isolator from being reverse biased with 339V in the reverse-swing portion of the waveform.
You can incorporate your zener as well if you want to "push down" the waveform to get a lower cross section of it (clip off the upper portion) instead of just reducing its amplitude:

simulate this circuit
In this R1 is the same as the resistor you were planning to use before. The added R3 resistor is to limit the current through the LED (drop the 5V to the LED forward voltage at a suitable current for the LED).

Thanks for the response, it does seem more reasonable to isolate the arduino from the mains voltage, and I didn't think about an optocoupler. Am I correct that your second circuit would effectively provide the inverted signal of my original plan? (5V until the positive portion of the waveform, when it would be 0V) Also, your recommendation is to pin the arduino to the chassis ground at the input? Thanks!

Yes the output will be active low. No need to ground the Arduino, no.

your circuit will work, and can be simplified a little bit further. But it will work.
it is safer to use isolation, however. there are multiple ways to go about doing it.
the key here is to detect zero crossing, and start counting from there.