text:
Serial Monitor Suddenly Doesn't Work
I have had this problem a few times, it seems the Arduino IDE and the serial monitor is incredibly unstable, unless it's user error but judging from the fact that I hadn't even touched anything before it broke, I would say it's not me.
It was working the night before but this morning it just wouldn't print anything to the serial monitor from my code, however if I start one of the communication example codes like the ASCII example, it prints fine...I'm using the arduino uno, but I have a couple of dues too, so I tried the script on the due and it printed fine to the serial monitor.
Here is my code, could someone check my code and see if they can print to the serial monitor or not?
/*
   Pins:

   RTC:
   5V to VCC
   GND to GDN
   A4 to SDA
   A5 to SLC
*/

#include <Wire.h>
#include "RTClib.h"

#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

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

//Words     //0      //1     //2    //3     //4     //5     //6    //7      //8      //9     //10   //11      //12      //13        //14        //15       //16       //17         //18        //19        //20      //21       //22    //23     //24                    //25//26 //27
char* w[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", "Keeg Jo And Mat 2016", "", " ", "Good",
             //28       //29         //30       //31     //32    //33  //34       //35    //36       //37  //38
             "Morning", "Afternoon", "Evening", "It Is", "Past", "To", "Quarter", "Half", "O'Clock", "AM", "PM"
            };

//End Words

int timeType = 0;
int _hour = 0;

int dayInput = 0;
int hourInput = 0;
int minuteInput = 0;

int iDay = 0;
int iHour = 0;
int iMinute = 0;

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(57600);
  pinMode(11, INPUT);//Minutes
  pinMode(12, INPUT);//Hours
  pinMode(13, INPUT);//Day

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    //rtc.adjust(DateTime(2016, 3, 11, 10, 51, 0));
  }

  //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop () {
  DateTime now = rtc.now();

  minuteInput = digitalRead(11);
  hourInput = digitalRead(12);
  dayInput = digitalRead(13);

  if (minuteInput == HIGH) {
    Serial.println("Minute");
  } else if (hourInput == HIGH) {
    Serial.println("Hour");
  } else if (dayInput == HIGH) {
    Serial.println("Day");
  }

  Line();

  if (now.minute() == 0) {
    timeType = 0;
  } else if (now.minute() > 0 && now.minute() <= 20) {
    timeType = 1;
  } else if (now.minute() > 20 && now.minute() < 50 && now.minute() != 30 && now.minute() != 45) {
    timeType = 0;
  } else if (now.minute() >= 50 && now.minute() < 60) {
    timeType = 2;
  } else if (now.minute() == 30) {
    timeType = 3;
  } else if (now.minute() == 45) {
    timeType = 4;
  }

  ps("Time Type: ");
  pi(timeType);

  Line();
  Line();

  //Greeting
  p(27);
  Space();
  if (now.hour() >= 0 && now.hour() < 12) {
    p(28);
  } else if (now.hour() >= 12 && now.hour() < 18) {
    p(29);
  } else if (now.hour() >= 18 && now.hour() < 24) {
    p(30);
  }

  Line();
  Line();

  //Time (It Is) Time Type 0
  if (timeType == 0) {
    Itis();
    hours(0);
    Space();
    _minutes();
    OClock();
  }

  //Time (Past) Time Type 1
  if (timeType == 1) {
    Itis();
    _minutes();
    Past();
    hours(0);
    OClock();
  }

  //Time (To) Time Type 2
  if (timeType == 2) {
    Itis();
    _minutes();
    To();
    hours(0);
    OClock();
  }

  //Time (Half Past) Time Type 3
  if (timeType == 3) {
    Itis();
    p(35);
    Past();
    hours(0);
  }

  //Time (Quarter To) Time Type 4
  if (timeType == 4) {
    Itis();
    p(34);
    To();
    hours(1);
  }

  //AM/PM
  AMPM();

  Line();
  Line();

  //Day
  //Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  ps(daysOfTheWeek[now.dayOfTheWeek()]);

  Line();
  Line();

  pl(24);

  Serial.println("--------------------------------------------------");
  Serial.println("--------------------------------------------------");

  delay(1000);

}

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

void Line() {
  pl(25);
}

void Itis() {
  p(31);
  Space();
}

void Past() {
  Space();
  p(32);
  Space();
}

void To() {
  Space();
  p(33);
  Space();
}

void Space() {
  p(26);
}

void OClock() {
  DateTime now = rtc.now();
  if (now.minute() == 0 || now.minute() == 60) {
    Space();
    p(36);
  }
}

void AMPM() {
  Space();

  DateTime now = rtc.now();

  bool am = false;

  if (now.hour() > 12) {
    am = false;
  } else {
    am = true;
  }

  if (am) {
    p(37);
  } else {
    p(38);
  }
}

void p(int i) {
  Serial.print(w[i]);
}

void pl(int i) {
  Serial.println(w[i]);
}

void ps(char* i) {
  Serial.print(i);
}

void pi(int i) {
  Serial.print(i);
}

void _minutes() {
  DateTime now = rtc.now();
  int minutes = 0;

  if (timeType == 2) {
    minutes = 60 - now.minute();
  } else {
    minutes = now.minute();
  }

  int i = minutes;

  if (i <= 20 && i != 0) {
    p(i);
  } else if (i > 20 && i < 30) {
    p(20);
    Space();
    p(i - 20);
  } else if (i > 30 && i < 40) {
    p(21);
    Space();
    p(i - 30);
  } else if (i > 40 && i < 50 && i != 45) {
    p(22);
    Space();
    p(i - 40);
  } else if (i > 50 && i < 60) {
    p(23);
    Space();
    p(i - 50);
  } else if (i == 30) {
    p(35);
  } else if (i == 40) {
    p(22);
  } else if (i == 50) {
    p(23);
  }

}

void hours(int m) {
  DateTime now = rtc.now();

  if (now.hour() > 12) {
    _hour = now.hour() - 12;
  } else {
    _hour = now.hour();
  }

  _hour = _hour + m;

  p(_hour);
}

  //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

Every time you reset the Arduino, the RTC clock will be set back to the date/time you compiled the sketch. Surely you don't want that?

The serial monitor is not at all unstable, as you agree when you try a different sketch. Therefore your sketch has a bug, which you need to find.
One possible issue is hardware. The default Wire library will hang if communications are lost when doing a read. Can you describe your clock hardware? Is it a chip you soldered yourself? A board? If so, which one? Do you have pull-up resistors on SDA/SCL?
There is an alternate I2C library that you could try.

Your method of printing is certainly unusual. You call, for example:
Line ();

When you could just as easily (and a lot more readably) call:
Serial.println ();

Similarly for Space and so on.

Still, despite the very hard-to-read code, I can't see any loops that might cause printing to fail. I suggest you comment out the calls to rtc.now() and test it. If it works, that confirms you have a clock issue, not a printing issue.
I note that you have multiple calls to:
DateTime now = rtc.now();

... sprinkled throughout your code. Surely you only need to read the time once, per loop?
Put the now variable outside loop, and call it once only, like this:
DateTime now;

void loop () {
  now = rtc.now();

Then remove the other calls to rtc.now().

I found when I tested (without a RTC connected) that it did indeed hang. But that was the rtc.now() call failing. If you comment that out, it prints fine.
eg.
Minute

Time Type: 0

Good Morning

It Is Six Twenty Eight AM

Keeg Jo And Mat 2016
--------------------------------------------------
--------------------------------------------------
Minute

Time Type: 0

Good Morning

It Is Six Twenty Eight AM

Keeg Jo And Mat 2016
--------------------------------------------------
--------------------------------------------------

That shows it is definitely a clock issue, not a serial printing issue.

Hi Nick, I just noticed something, when I pulled the clock module out of the board to get the name of the board it started printing again the serial monitor...then when I put it back in it started printing the same as what you put in above, however it's printing 'It Is Zero O'Clock AM'...

Think I may have found the problem, one of the pins has come loose from the board, the solder has come right off, I'll try re soldering it and see if that fixes it

Oh and as for those unusual printing methods, I'm just trying to keep my code as simple as possible, I'm working with some inexperienced coders, not that I'm particularly experienced though, besides, I actually quite like it!

All fine now, must have been the soldering...


text:
Serial Monitor not displaying anything
I have a very basic script that is supposed to display something to the serial monitor but no matter what I try the serial monitor won't display anything...I;ve watched about 5 tutorials now and each one has failed to display anything. Any ideas what I'm doing wrong?
Here is my code:
char rx_byte;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

Are you typing anything into the serial monitor? What baud rate is the serial monitor set to?

I'm typing just the number 1 and 0, according to the tutorial I watched that should turn the LED on/off. The baud rate is set the same as what is in my code.

I'm typing just the number 1 and 0 - and then you pressed the Send button? Please add Serial.println ("Hello, world"); after the Serial.begin line and see if that appears in the serial monitor.

Yes then I pressed the send button. I tried putting that line in after Serial.begin and still nothing...

Well, solve that first. No point typing and pressing Send if nothing appears. What Arduino do you have? What version of the IDE?

I've got the arduino due, I can't find the version of the IDE, where would I find it? (I'm using osx)

Found it, its 1.6.6

I've got the arduino due - you might have mentioned that earlier. That has two USB ports. Which one are you using?

The one closest to the reset button, I believe its the native...

See: Getting started with the Arduino Due

Interesting, I'll try the programming port then!

Bingo, that did it, working perfectly now!

I've summarized this discussion, and my findings, in a new answer below.

Which one are you using?
The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

Programming port
For programming, the programming port is easiest to use. And you can "talk" to the serial port using Serial, like this:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Hello, world!");
  }  // end of setup

void loop ()
  {
  }  // end of loop

Native USB port
This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class SerialUSB like this:
void setup ()
  {
  SerialUSB.begin(115200);
  while (!SerialUSB) ; // wait for it to become ready
  SerialUSB.println ("Starting ...");
  }  // end of setup

unsigned long i;

void loop ()
  {
  SerialUSB.print ("Hello, world! Count = ");
  SerialUSB.println (++i);
  delay (1000);
  }  // end of loop

It also helps to wait for the serial port to become ready, as I did in setup. Otherwise you may miss the first 10 lines or so of serial output.

You have to change the baud rate at the right bottom corner of the serial monitor to 115200 which you have assigned initially.
I have tested it  and
It doesn't matter if its int/char

I have done that, still no luck.

Try replacing the line char rx_byte; with int rx_byte=0;. Use Serial.println(rx_byte,DEC);
int rx_byte=0;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available() > 0){
    rx_byte = Serial.read();
    Serial.print("You typed: ");
    Serial.println(rx_byte,DEC);
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
  }
}

Same again, nothing...

source: Stack Exchange

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

sort: votes


text:
Working with Wire core library
I'm studying the Wire library code driver utility/twi.h to learn how twi buffering and ISR management work.
What I did actually, is that I copied the header/source files from the Arduino path F:\Program Files\Arduino\hardware\arduino\avr\libraries\Wire\src\utility and put them in the Arduino custom libraries and changed the .c to .cpp and it worked.
I actually ran through different i2c libraries for avr and this code library is one of the best IMHO.
My test code is to initialize the HMC5883L, and read back those configuration setting from the first SFRs of the HMC5883L.
I'm using Serial.prints inside/outside the ISR to debug my coding. It is working pretty much OK. I'm not sure if this could cause some problems.
But, because I don't have a complete understanding of how twi works, I'm trying to understand things now as displaying the content that is going in the ISR.
I think the initialize is working ok, but the read procedure may not as it should be.
Here's my code, for application code in the Arduino IDE, and the code in the library.
Arduino IDE code:
#include "twi.h"
////////////////////////////////////////////////////////////////////////////
// HMC5883L
#define HMC5883L                    0x1E
#define CONFIG_REG_A                0x00  //Read/Write
#define CONFIG_REG_B                0x01  //Read/Write
#define MODE_REGISTER               0x02  //Read/Write
#define DATA_OUTPUT_X_MSB_REGISTER  0x03  //Read
#define DATA_OUTPUT_X_LSB_REGISTER  0x04  //Read
#define DATA_OUTPUT_Z_MSB_REGISTER  0x05  //Read
#define DATA_OUTPUT_Z_LSB_REGISTER  0x06  //Read
#define DATA_OUTPUT_Y_MSB_REGISTER  0x07  //Read
#define DATA_OUTPUT_Y_LSB_REGISTER  0x08  //Read
#define STATUS_REGISTER             0x09  //Read
#define IDENTIFICATION_REGISTER_A   0x10  //Read
#define IDENTIFICATION_REGISTER_B   0x11  //Read
#define IDENTIFICATION_REGISTER_C   0x12  //Read
#define DECLINATION_ANGLE 3.46

void hmc5883l_init(void);
void init_read(void);
void hmc5883l_print_serial(void);

void setup() {
  Serial.begin(9600);
  twi_init();
  hmc5883l_init();
  init_read();
}

void loop() {
  hmc5883l_print_serial();
}

void hmc5883l_init(void){
  uint8_t err,HMC5883L_ini[] = {CONFIG_REG_A,0x78,0x20,0x00};//
    err = twi_writeTo(HMC5883L,HMC5883L_ini,4,1,1);
    if(err != 0){Serial.print("error of init is");Serial.println(err);}
    Serial.println();
}

void init_read(void){
    uint8_t err,len,dat[3];
    err = twi_writeTo(HMC5883L,0x00,1,0,1);
    if(err != 0){Serial.print("error of init is");Serial.println(err);}
    Serial.println();

    len = twi_readFrom(HMC5883L,dat,3,1);
    Serial.print("length of read op:              ");
    Serial.println(len);
    Serial.println();

    Serial.print("config settings:                ");
    Serial.print(dat[0],HEX);Serial.print("\t");
    Serial.print(dat[1],HEX);Serial.print("\t");
    Serial.println(dat[2],HEX);
}

void hmc5883l_print_serial(void){
  int16_t x,z,y;
  uint8_t data[6],len,err, dst_reg[] = {0x03};
  float heading,heading_in_degrees,declination_angle_YANBU;

  err = twi_writeTo(HMC5883L,dst_reg,1,0,1);
  if(err != 0){Serial.print("error of init is");Serial.println(err);}
  Serial.println();

  len = twi_readFrom(HMC5883L,data,6,1);
  Serial.print("len is: ");Serial.println(len);
  x = data[0] << 8 | data[1];
  z = data[2] << 8 | data[3];
  y = data[4] << 8 | data[5];

  heading = atan2(y,x);
  declination_angle_YANBU = ((3.0 + (52.0 / 60.0)) / (180 / M_PI));  // in yanbu city it's
  heading += declination_angle_YANBU;

  if (heading < 0){heading += 2 * PI;}
  if (heading > 2 * PI){heading -= 2 * PI;}

  heading_in_degrees = heading * 180 / M_PI;
  Serial.println(heading_in_degrees);

  //Serial.print("x-axis\t");Serial.print("z-axis\t");Serial.println("y-axis");
  Serial.print(x);Serial.print("\t");
  Serial.print(z);Serial.print("\t");
  Serial.println(y);
}

And this is the core library:
In this part, I've put Serial.prints inside the ISR cases to display what's going from the start of the tx/rx buffers. Also, I've cut the slave half of the code because it's not necessary in this problem, as I'm only dealing with HMC5883L as a slave and I'm the master.
#include <math.h>
#include <stdlib.h>
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <compat/twi.h>
#include "Arduino.h" // for digitalWrite

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif

#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#include "pins_arduino.h"
#include "twi.h"

static volatile uint8_t twi_state;
static volatile uint8_t twi_slarw;
static volatile uint8_t twi_sendStop;           // should the transaction end with a stop
static volatile uint8_t twi_inRepStart;         // in the middle of a repeated start

static void (*twi_onSlaveTransmit)(void);
static void (*twi_onSlaveReceive)(uint8_t*, int);

static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static volatile uint8_t twi_masterBufferLength;

static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_txBufferIndex;
static volatile uint8_t twi_txBufferLength;

static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_rxBufferIndex;

static volatile uint8_t twi_error;

void twi_init(void)
{
  // initialize state
  twi_state = TWI_READY;
  twi_sendStop = true;      // default value
  twi_inRepStart = false;

  // activate internal pullups for twi.
  digitalWrite(SDA, 1);
  digitalWrite(SCL, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);
  TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

  // enable twi module, acks, and twi interrupt
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
}

void twi_disable(void)
{
  // disable twi module, acks, and twi interrupt
  TWCR &= ~(_BV(TWEN) | _BV(TWIE) | _BV(TWEA));

  // deactivate internal pullups for twi.
  digitalWrite(SDA, 0);
  digitalWrite(SCL, 0);
}

uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length, uint8_t sendStop)
{
  uint8_t i;

  // ensure data will fit into buffer
  if(TWI_BUFFER_LENGTH < length){
    return 0;
  }

  // wait until twi is ready, become master receiver
  while(TWI_READY != twi_state){
    continue;
  }
  twi_state = TWI_MRX;
  twi_sendStop = sendStop;
  // reset error state (0xFF.. no error occured)
  twi_error = 0xFF;

  // initialize buffer iteration vars
  twi_masterBufferIndex = 0;
  twi_masterBufferLength = length-1;  // This is not intuitive, read on...

  twi_slarw = TW_READ;
  twi_slarw |= address << 1;

  if (true == twi_inRepStart) {
    twi_inRepStart = false;         // remember, we're dealing with an ASYNC ISR
    do {
      TWDR = twi_slarw;
    } while(TWCR & _BV(TWWC));
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);  // enable INTs, but not START
  }
  else
    // send start condition
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);

  // wait for read operation to complete
  while(TWI_MRX == twi_state){
    continue;
  }

  if (twi_masterBufferIndex < length)
    length = twi_masterBufferIndex;

  // copy twi buffer to data
  for(i = 0; i < length; ++i){
    data[i] = twi_masterBuffer[i];
  }

  return length;
}

uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait, uint8_t sendStop)
{
  uint8_t i;

  // ensure data will fit into buffer
  if(TWI_BUFFER_LENGTH < length){
    return 1;
  }

  // wait until twi is ready, become master transmitter
  while(TWI_READY != twi_state){
    continue;
  }
  twi_state = TWI_MTX;
  twi_sendStop = sendStop;
  // reset error state (0xFF.. no error occured)
  twi_error = 0xFF;

  // initialize buffer iteration vars
  twi_masterBufferIndex = 0;
  twi_masterBufferLength = length;

  // copy data to twi buffer
  for(i = 0; i < length; ++i){
    twi_masterBuffer[i] = data[i];
  }

  // build sla+w, slave device address + w bit
  twi_slarw = TW_WRITE;
  twi_slarw |= address << 1;

  // if we're in a repeated start, then we've already sent the START
  // in the ISR. Don't do it again.
  //
  if (true == twi_inRepStart) {
    // if we're in the repeated start state, then we've already sent the start,
    // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
    // We need to remove ourselves from the repeated start state before we enable interrupts,
    // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
    // up. Also, don't enable the START interrupt. There may be one pending from the
    // repeated start that we sent outselves, and that would really confuse things.
    twi_inRepStart = false;         // remember, we're dealing with an ASYNC ISR
    do {
      TWDR = twi_slarw;
    } while(TWCR & _BV(TWWC));
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);  // enable INTs, but not START
  }
  else
    // send start condition
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA); // enable INTs

  // wait for write operation to complete
  while(wait && (TWI_MTX == twi_state)){
    continue;
  }

  if (twi_error == 0xFF)
    return 0;   // success
  else if (twi_error == TW_MT_SLA_NACK)
    return 2;   // error: address send, nack received
  else if (twi_error == TW_MT_DATA_NACK)
    return 3;   // error: data send, nack received
  else
    return 4;   // other twi error
}

void twi_reply(uint8_t ack)
{
  if(ack){
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
  }else{
      TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
  }
}

void twi_stop(void)
{
  // send stop condition
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);

  while(TWCR & _BV(TWSTO)){
    continue;
  }

  // update twi state
  twi_state = TWI_READY;
}

/*
 * Function twi_releaseBus
 * Desc     releases bus control
 * Input    none
 * Output   none
 */
void twi_releaseBus(void)
{
  // release bus
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);

  // update twi state
  twi_state = TWI_READY;
}

ISR(TWI_vect)
{
  switch(TW_STATUS){
    // All Master
    case TW_START:     // sent start condition
    case TW_REP_START: // sent repeated start condition
      // copy device address and r/w bit to output register and ack
      TWDR = twi_slarw;
      Serial.print("mt add sent is:                 0x");
      Serial.println(twi_slarw, HEX);
      twi_reply(1);
      break;

    // Master Transmitter
    case TW_MT_SLA_ACK:  // slave receiver acked address
    case TW_MT_DATA_ACK: // slave receiver acked data
      // if there is data to send, send it, otherwise stop
      if(twi_masterBufferIndex < twi_masterBufferLength){
        // copy data to output register and ack
        Serial.print("mt byte transmitted no:         ");
        Serial.println(twi_masterBufferIndex);
        Serial.print("content of tx byte:             0x");
        Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
        TWDR = twi_masterBuffer[twi_masterBufferIndex++];
        twi_reply(1);
      }else{
    if (twi_sendStop){
        Serial.println("mt stop");
        twi_stop();
    }

    else {
      Serial.println("mt repst");
      twi_inRepStart = true;    // we're gonna send the START
      TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
      twi_state = TWI_READY;
    }
      }
      break;
    case TW_MT_SLA_NACK:  // address sent, nack received
    Serial.println("mt add sent nack");
      twi_error = TW_MT_SLA_NACK;
      twi_stop();
      break;
    case TW_MT_DATA_NACK: // data sent, nack received
      twi_error = TW_MT_DATA_NACK;
      twi_stop();
      break;
    case TW_MT_ARB_LOST: // lost bus arbitration
      twi_error = TW_MT_ARB_LOST;
      twi_releaseBus();
      break;

    // Master Receiver
    case TW_MR_DATA_ACK: // data received, ack sent
      // put byte into buffer
        Serial.print("mr byte received no:            ");
        Serial.println(twi_masterBufferIndex);
        Serial.print("content of rx byte:             0x");
        Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
    case TW_MR_SLA_ACK:  // address sent, ack received
      // ack if more bytes are expected, otherwise nack
      if(twi_masterBufferIndex < twi_masterBufferLength){
        twi_reply(1);
      }else{
        twi_reply(0);
      }
      break;
    case TW_MR_DATA_NACK: // data received, nack sent
      // put final byte into buffer
        Serial.print("mr last received byte:          ");
        Serial.println(twi_masterBufferIndex);
        Serial.print("content of last rx byte:        0x");
        Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
    if (twi_sendStop)
          twi_stop();
    else {
      twi_inRepStart = true;
      TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
      twi_state = TWI_READY;
    }
    break;
    case TW_MR_SLA_NACK:
      twi_stop();
      break;
}

The problem now is:
I get these readings on the Arduino serial monitor.
Note: I've wrote my notes on each section.
// initialization
// I think this process is done just fine, the exact bytes are sent
// but each time I open the serial monitor I get like garbage at the first
// of the window, like this flipped question mark I get it most the time
// Is there something like flush function to clear things?
⸮mt add sent is:                 0x3C
mt byte transmitted no:         0
content of tx byte:             0x0
mt byte transmitted no:         1
content of tx byte:             0x78
mt byte transmitted no:         2
content of tx byte:             0x20
mt byte transmitted no:         3
content of tx byte:             0x0
mt stop

// writing target register which is 0x00, but I get 0xA3 ??!
m
mt byte transmitted no:         0
content of tx byte:             0xA3
mt stop

// Here requesting the 6 bytes data, I send read of HMC5883L which is 0x3D
// but 1st byte should be 0x78 then 2nd should be 0x20, 3rd 0x00
// but the result is different ! it's like they are shifted somehow

// At the end I'm trying to read back the passed array to the function, but
// I get 0s!!
mt add sent is:                 0x3D
mr byte received no:            0
content of rx byte:             0xA3
mr byte received no:            1
content of rx byte:             0x78
mr last received byte:          2
content of last rx byte:        0x20
length of read op:              3

config settings:                0   0   0

That is not the core library, those lower level functions are part of the Wire library.

Aaah, OK, I then didn't differentiate between core/lower functions. OK, so what could be like core library? Is Arduino.h and other related libraries that are within Arduino folder in installation folder, are the core libraries for Arduino ?

There is no "core" library. There are a number of Wire libraries (official and other compatible libraries) for different processors. It just happens that the Wire library for the avr microcontrollers has two layers.

Yes, thanks for the clarification. Absolutely, I think one library can't cover all the mcu families, it can focus on one particular family or group of microcontrollers.

The second parameter to twi_writeTo should be a pointer to a buffer. You have now
twi_writeTo(HMC5883L,0x00,1,0,1);

which sends a byte read at address 0x00.
change it to
uint8_t b = 0x00;
twi_writeTo(HMC5883L,&b,1,0,1);

(C arrays are a pointer to first item)

Yeah, I did that. It's ok. But the problem is reading the config registers. I can read data registers automatically, but I can't read the configuration registers automatically! I have to do it one by one.

that is a very different question. the original was about the twi (sub)library. the new is about the specific device. the automatic register increment is to speed up the common use case. with configuration you don't need to hurry

Yeah, sorry, it's actually connected to a device, but maybe the principle is common on i2c devices. Is the problem I'm trying to understand is this feature of communicating with i2c devices. I think there are two types of communication with i2c devices; at least to the HMC5883L. I think if I want to deal with reading configuration registers then I have to do it one by one, if reading data registers, then I can do it automatically.

it is device specific, not a feature of I2C

Ah, OK, it's clear that I really don't have that much of information :) Thanks dude for the help, I really appreciate it. First I posted all this lengthy post, and I really don't know what I'm trying to get because there are so much related problems I have to be aware of. I'm thinking of deleting the thread ! What you think ? Do you agree ? and then I arrange my self again and consider on one more beneficial thread. Any recommendations?

You mean the last update to the post?

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


text:
Reading HMC5883L hex values in 2's compliment C code
I want to develop my C code for HMC5883L.
I have 2 questions for my current code development.
My first question is:
But what I found in the datasheet is that the values are in the 2's compliment, so I don't know how to deal with them?! Do I have to take the values as they are in the data registers and convert them to decimal values and that's it? Or I have to convert them from 2's compliment to the original hex values?
This is a quote from the datasheet:

Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain)
  Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.

My second question:
How o read the data registers? What is the procedure?
I saw in the datasheet the following method but I didn't understand it.

Loop
  Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain)
  Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.
  Send 0x3C 0x03 (point to first data register 03)
  Wait about 67 ms (if 15 Hz rate) or monitor status register or DRDY hardware interrupt pin
  End_loop

So, I didn't understand that I send read command then I send write command, so how HMC5883L would return the value to me?
Regards,

2's complement is the normal signed values in any modern system, including Arduino.
Just place the bytes into a signed variable of the right size in the right positions and there is your value.
In I2C, to read a register, you typically have to make two transactions. The first is a write to set the register number you want to access, the you follow that with a read transaction to get the data.

Comments are not for extended discussion; this conversation has been moved to chat.

Any comments that amplify on the answer should be merged into the answer. Anyone with sufficient reputation can do that.

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


text:
Not clear code procedure in Arduino wire library
The application code of sparkFun, has the following line which is difficult to understand.
It's requested 6, because it's requesting 6 bytes for HMC5883L module.
Wire.requestFrom(address, 6);
if(6<=Wire.available())

Where:
int TwoWire::available(void)
{
  return rxBufferLength - rxBufferIndex;
}

So, the available function should return return rxBufferLength - rxBufferIndex; where rxBufferIndex is modified in read function:
int TwoWire::read(void)
{
  int value = -1;

  // get each successive byte on each call
  if(rxBufferIndex < rxBufferLength){
    value = rxBuffer[rxBufferIndex];
    ++rxBufferIndex;
  }

  return value;
}

But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

6 according to HMC5883L 6 bytes data.

rxBufferLength is the number of bytes that have been received. rxBufferIndex is the byte you would next be handed with a read() function call.
So if you have received 6 bytes from the slave (which you will, since that is how many you requested) but not read any the available would be 6. Ergo, 6 <= 6. I.e., you asked for 6, it collected 6, and you are checking that it got at least 6 (it can never be >6 since you only asked for 6, so why they look for at least 6 I don't know).
rxBufferIndex is never decremented. It is incremented when you read a byte, up until rxBufferLength == rxBufferIndex at which point there is 0 bytes available.

But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where  rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

The way that Wire.h works is that available() will always return the number of bytes you requested if the call to requestFrom() succeeded until you first read some of that data. If you request 6 and the call worked then you have 6. The if could just as well be written as:
if (Wire.available()) {...

since it will always be 6 immediately after a successful call. However, that makes assumptions about how the Wire API works and could be subject to change in the future or operate differently on different platforms.
So it checks that, right after the call to requestFrom() for 6 bytes it actually got at least 6 bytes. Without seeing what is inside the conditional if, all I can do is make assumptions, but I would assume that it is then reading those 6 bytes, and so it wouldn't care if there happened to be more for some reason. But it doesn't want there to be 5 or fewer bytes available when it is reading 6 of them.
An if statement doesn't "terminate" if its condition becomes false once it has been executed. It's not like a while that keeps running until it's false - it's a single decision made at a single point in time. If anything changes in the future that would have caused a difference decision to be made (e.g., you read() a byte, so available() would now return 5), the decision that has been made still stands.
An analogy for you:
You want to go out for a good healthy walk - but only if it's not raining.
if (!raining) {
    walk_to_shop();
    walk_to_cafe();
    drink_coffee();
    walk_to_shop();
    walk_home();
}

You go out for your walk to the shops, get a coffee, do some more shopping, and then walk home - but you only start doing that if it's not raining. If it starts raining while you're out you don't suddenly teleport back home.  You could make the decision, when you come out of the cafe and see it's raining, to cut your shopping trip short, but you have to actively make that decision. Just because raining becomes true doesn't affect the fact that you are outside and walking.

I edited the  question.

I think you're getting confused about what n if is.

What confused me is if(6<=Wire.available()) because available returns rxBufferLength - rxBufferIndex; so if rxBufferLength is 6 and  rxBufferIndex is 0, then available returns 6, which is true in this case. But, if rxBufferIndex is 1 or 2, then available returns 5 or 4, which is false. So, how's that if statement is working? Does if(6<=Wire.available()) returns the value one time, or it returns with all rxBufferIndex increments inside wire library?

@PerchEagle At the moment the if() executes Wire.available() will equal 6. That is the only time the if() executes, and it can only ever give 6, since nothing has been read at that point.

OK, I understand now, it runs only one time and the function every time returns 6. Thank you :) but I have another problem, the good news I succeeded accomplishing my I2C code, and that was amazing, but I have a new problem passing an array to I2C_tx function, I don't know why it's not working. I should ask about it in a new post.


text:
Accidentally shorted 5V to GND on Arduino Nano, can I reuse the ATmega328p?
I've shorted 5V to GND and the Arduino Nano (CH340 clone) stopped working (power LED light is dimming). The board had a burning smell, and I also checked if other Arduini on the same USB port worked and they did, so I'm quite sure the Arduino is dead.
After the incident, I de-soldered the TQFP Atmega328p (plus the crystal) to reuse. I'm thinking that if it's only the external circuitry that's damaged, then the chip should be OK. Can I reuse the chip if I solder onto a new board? What components could have been damaged?

It always depends where you created the short circuit. If it was the VCC and GND pin of the ATmega, then you fried everything else but the MCU.

The short circuit was near a class D amplifier which I had misplaced on a breadboard. The amplifier and other components survived, only the arduino stopped working.

Can you show the schematics?

I don't have the schematics for this, I was just testing a few things. It's was a simple circuit though, just a mp3 player module, some LEDs and the PAM8403 amp.

Just draw a picture, how you wired up all the things.

The wiring was fine, I've done the same many times. I just put the amp module in the wrong position and realised the 5V and G input to the module were in the same row, it stayed like that for about 30 seconds until I realised.

If you shorted VCC with Ground and not Pin with Ground it's possible that just the voltage regulator let out the magic smoke. Did you power the Arduino via USB?

Yes, it was powered by USB.

I think the USB connection doesn't use the voltage regulator. I think the easiest for you would be to connect the Nano to USB, take multimeter and check voltage on the Atmega328p pads. If the VCC and GND have 5V they you have 100% certainty that the power circuit works, and MCU is fried. Use datasheet to check pinout http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

I just did that without the atmega328p (because I already de-soldered it), it's giving me 3V between the 5v pin and Gnd pin...and the LED power led flashes weakly, dimming. So the power circuit is broken.

This means that there is a chance that power circuit failing prevented MCU from burning up. It's impossible to verify that without extensive tests of the ATmega. It's also possible that there is "some" damage that will decrease its lifespan. It's a 50cent part. IMHO it's easier/safer to get a new one.

Great, it's good to know that, thanks Filip. I will keep the MCU in a drawer anyway as spare, but separated from the new ones then.

Think about preparing yourself an overcurrent protection circuit to put between Arduino and breadboard when you prototype.

That is a good suggestion, I will check what I can do for this. Thanks.

is it worth your time to spend hours fixing a part you can replace for $2us?

Try checking the pcb and components for damage. The only thing I can think of that could get damaged in the situation you described would be a PCB trace that’s blown up.

I just had the exact same problem (shorting 5V and ground - not even for long) on two nano clones, and strangely but consistently, both nano's still seemed to work. However, I wasn't able to flash them through USB anymore. Flashing them through ISP still worked, though.

On a Arduino Nano, there is a diode that prevents an external 5V source from back feeding into the USB source. If your clone equivalent has that as well, I suspect that is the part that got fried.

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


text:
MFRC522 Module Won't Read Multiple PICCs Consecutively
I recently bought an MFRC522 RFID module to use with my Arduino Uno, which came as a kit with a couple of MiFare 1K cards.
The issue I've been having is that, I cannot scan cards consecutively (the same card or two different ones) without resetting the Sketch.  I hold a card in front of the reader and it is scanned, but when I hold another card in front of the reader it just doesn't recognize it as being there in the mfrc522.PICC_IsNewCardPresent() function.  It does however work when using the example sketch "DumpInfo".
Here is the code I've written (please excuse any of my bad practices/untidiness).
/* Include Required Libraries */
#include <MFRC522.h>
#include <SPI.h>

/* Define Values for MFRC522 */
#define RST_PIN 9
#define SS_PIN 10

/* Instantiate the MFRC522 Object */
MFRC522 mfrc522(SS_PIN, RST_PIN);

/* Initialize Variables */
byte resultBuffer[18];
MFRC522::MIFARE_Key key;
unsigned int integerValue = 0;
char incomingByte;

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  Serial.println(F("Ready to scan card..."));

  for (byte i = 0; i < 6; i++)
  {
    key.keyByte[i] = 0xFF;
  }
}

void loop()
{
  if (!mfrc522.PICC_IsNewCardPresent())
  {
    if (Serial.available() <= 0)
    {
      return;
    }

    integerValue = 0;
    while(true)
    {
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;
      if (incomingByte == -1) continue;
      integerValue *= 10;
      integerValue = ((incomingByte - 48) + integerValue);
    }

    printHeader();
    Serial.println("NEW BLOCK READ VALUE :");
    Serial.println(integerValue);
  }

  if (!mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

  readAndPrint(integerValue);
}

void printHeader()
{
  Serial.println(" ");
  Serial.println("----------------------------------------");
}

int authenticateKeyA(int blockNumber)
{
  printHeader();
  Serial.println("Authenticating with key A...");

  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3;

  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));

  if (status != MFRC522::STATUS_OK)
  {
    Serial.println("ERROR : Authentication was unsuccessful.");
    return 0;
  }
  else
  {
    Serial.println("SUCCESS : Authentication was successful.");
    return 1;
  }
}

int authenticateKeyB(int blockNumber)
{
  printHeader();
  Serial.println("Authenticating with key B...");

  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3;

  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));

  if (status != MFRC522::STATUS_OK)
  {
    Serial.println("ERROR : Authentication was unsuccessful.");
    return 0;
  }
  else
  {
    Serial.println("SUCCESS : Authentication was successful.");
    return 1;
  }
}

int readBlock(int blockNumber, byte *resultBuffer)
{
  printHeader();
  Serial.println("Starting read block function...");

  int authSuccess = authenticateKeyA(blockNumber);
  Serial.println(" ");

  if (!authSuccess)
  {
    Serial.println("ERROR : Terminating function.");
    return 0;
  }

  byte bufferSize = 18;

  byte status = mfrc522.MIFARE_Read(blockNumber, resultBuffer, &bufferSize);

  if (status != MFRC522::STATUS_OK)
  {
    Serial.println("ERROR : Read failed.");
    return 0;
  }
  else
  {
    Serial.print("SUCCESS : Block ");
    Serial.print(blockNumber);
    Serial.print(" was read successfully.");
    return 1;
  }

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

void readAndPrint(int blockNumber)
{
  readBlock(blockNumber, resultBuffer);

  printHeader();
  Serial.println("RESULT :");
  for (int j=0 ; j<16 ; j++)
  {
   Serial.print(resultBuffer[j], HEX);
   Serial.print(" ");
  }
  Serial.println(" ");

  delay(2000);
  printHeader();
  Serial.println("Ready to scan card...");
}

Before scanning the card for the first time, the serial output looks like this :

After scanning the card for the first time, the serial output looks like this :

After scanning the card for the second time, the serial output doesn't change from image 2.  I tried running Serial.println("no card detected"); when the code inside if (!mfrc522.PICC_IsNewCardPresent()) is ran, just to check if the program was frozen (I'd heard someone else had an issue where the program froze after scanning the first card) - it wasn't frozen, both before and after scanning the first card, it printed out 'no card detected' repeatedly.
I would greatly appreciate any help as I have no clue as to how I should proceed.
Cheers,

What is printed in the serial monitor? Post the image in your question.

@TisteAndii Images have been added to the question.  Cheers

Do not return from 'loop()', it should loop forever.

If you return it still loops.

The correct condition, for what you intend, should be if (mfrc522.PICC_IsNewCardPresent()), so that the code in the IF block is run when a card is present, though this isn't the best structure. Like you discovered, your program isn't frozen. One of the 2 return statements (I'm not sure which) is causing it to abort loop() before calling readAndPrint(). With your current code:

the first return will always be executed whenever no card is detected. Since you don't seem to be sending anything with the Serial monitor,  Serial.available() will return 0 and so loop() returns.
The second return will be executed if the reader fails to obtain the UID of the card with a SELECT. The SELECT will fail only if you don't first call PICC_RequestA() for 'new' cards (just coming within range), or PICC_WakeupA() for HALTed cards (cards already within range but sleeping).

I don't know if you're trying different cards or just one. If its just one card, you may have to take it out of range and then bring it within range again for the reader to detect it a second time. But, if you want to read the card's data more than once, without taking it out of range, you have to call PICC_WakeupA() instead of PICC_IsNewCardPresent() since, as the names indicate, you're waking a sleeping card, not detecting a new card entirely. Also structure your loop() like this:
void loop(){
  if (!mfrc522.PICC_IsNewCardPresent()) {  // replace the condition with PICC_WakeupA()
    return;  // if you dont want the card to leave the reader's range
  }

  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  // all the code that should be executed if a card has been detected and its UID read

}

However, there's usually little sense in HALTing a card and then waking it in the very next iteration, so you might want to do all the sector reading and writing at once, HALT the card, and then wait for a new card to enter the field; at least that's what's desired in most applications.


text:
Detecting which pin called the ISR Uno
I need an answer fast.I want to make a keyboard class to handle a few buttons attached to my arduino. I want to use interrupts.The problem is I have to use the same interrupt function for all my buttons(it would beimpractical to create a routine for each button).So inside the routine I must know at least what pin fired the interrupt. How can I solve this?(I belive it can be solved by changing some registers but that would be too complicated).PS:there are only two buttons(pins 2 and 3 are enough)
Edit:
   Isn't possible to create/call an interrupt routine inside a class? (I know that the routine actually doesn't exist initially because the object of the class type wasn't created). Can this be done?
class Keyboard{
  private:
    struct btn{
      boolean pressed;
      uint32_t pressTime;
    };
    btn button1;

  public:
    void int_handler(){

    }
    Keyboard(){
      attachInterrupt(digitalPinToInterrupt(2),this->int_handler,RISING);
      attachInterrupt(digitalPinToInterrupt(3),this->int_handler,RISING);
    }
};

Keyboard::int_handler() must be static.

I solved this in a more..compressed way.
I already store the state of the buttons(pushed down or up-that is if they set their connected pin to 0 or 1).So I can have a single routine called by the microcontroller and then inside it decide what pin changed states(clever):
#define btn1Pin 2
#define btn2Pin 3

class Timer{
  //....
};
uint32_t Timer::start_time;
class KeyboardBtn{
  private:
    const static byte clicksDelay=255;
    struct btn{
      byte state=1;   //(0-keyDown / 1-keyUp) 2-Click
      byte pin;
      Timer clickLapse;
    };
    volatile static btn buttons[2];

  public:
    KeyboardBtn(){
      buttons[0].pin=btn1Pin;
      buttons[1].pin=btn2Pin;
      attachInterrupt(digitalPinToInterrupt(btn1Pin),keyPress,CHANGE );
      attachInterrupt(digitalPinToInterrupt(btn2Pin),keyPress,CHANGE );
    }
    static void keyPress(){
      //digitalRead ==1 then button up
      for(int i=0;i<2;i++){
        if(bitRead(buttons[i].state,0)==digitalRead(buttons[i].pin)) continue;
        //i is the switched button
      }
    }
    byte stateChanged(byte key){
      //code
    }
};
volatile KeyboardBtn::btn KeyboardBtn::buttons[2];

KeyboardBtn btn;
void setup() {
  pinMode(btn1Pin,INPUT_PULLUP);
  pinMode(btn2Pin,INPUT_PULLUP);
}

void loop(){
}

You only have two external interrupts on the Uno, so a simple solution would be to call an "intermediate" routine, which remembers the button number. eg.
  attachInterrupt(digitalPinToInterrupt(2),this->int_handler2,RISING);
  attachInterrupt(digitalPinToInterrupt(3),this->int_handler3,RISING);

Those two functions could then call your main function passing down 2 or 3 depending on which one was called.
eg.
void int_handler2 ()
  {
  int_handler (2);
  }

void int_handler3 ()
  {
  int_handler (3);
  }

If you have more switches than that you can use pin-change interrupts. The typical way of detecting which one fired is to see which bits are different this time, compared to last time.
See my page about interrupts.

Yes.I believe I'm gonna use the same old-functions to handle the interrupts.Thanks for the link!


text:
Compiling error:passing as 'this' argument
I am trying to make a small keyboard class to handle two buttons(in the future >2)  that are connected to my arduino UNO. The buttons being pressed are detected using interrupts. Here is the code:
Timer
class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark(){
      start_time=millis();
    }
    uint32_t lapsed(){
      return millis()-start_time;
    }
};

Keyboard
class KeyboardBtn{
  private:
    const static byte clicksDelay=255;      //255 ms max
    struct btn{
      byte state=0;   //0->nothing;1-click;2-dblClick
      Timer clickDelay;
    };
    volatile static btn buttons[2];         //only two buttons for now

  public:
    KeyboardBtn(){
      attachInterrupt(digitalPinToInterrupt(2),this->int_handler_btn0,FALLING);       //Initially the pins are set to HIGH(pullup behaviour)
      attachInterrupt(digitalPinToInterrupt(3),this->int_handler_btn1,FALLING);
    }

    static void int_handler_btn0(){
      btns_handler(0);
    }
    static void int_handler_btn1(){
      btns_handler(1);
    }
    static void btns_handler(byte key){
        if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){
          buttons[key].state=2;
        }else{
          buttons[key].state=1;
          buttons[key].clickDelay.mark(); //Pressed one time? mark this and wait for second press
        }
    }
    byte stateChanged(byte key){
      //Function called to get key status
      byte temp_state=buttons[key].state;
      if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){
        return 0; //We still wait:don't know if it's a dblClick or single
      }else{
        buttons[key].state=0;
        return temp_state;
      }
    }
};
volatile KeyboardBtn::btn KeyboardBtn::buttons[2];

But the compiler gives me headaches(of course my code is wrong somewhere but he could just have kept quite about it):

C:\Users....\Humidity.ino:
  In static member function 'static void
  KeyboardBtn::btns_handler(byte)':
C:\Users...\Humidity\Humidity.ino:74:68: warning: passing 'volatile Timer' as
  'this' argument of 'uint32_t Timer::lapsed()' discards qualifiers
  [-fpermissive]
     if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){

                                                                ^

C:\Users...\Humidity\Humidity.ino:78:40: warning: passing 'volatile Timer' as
  'this' argument of 'void Timer::mark()' discards qualifiers
  [-fpermissive]
       buttons[key].clickDelay.mark();

                                    ^

C:\Users....\Humidity\Humidity.ino:
  In member function 'byte KeyboardBtn::stateChanged(byte)':
C:\Users....\Humidity\Humidity.ino:83:58: warning: passing 'volatile Timer' as
  'this' argument of 'uint32_t Timer::lapsed()' discards qualifiers
  [-fpermissive]
   if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){

                                                      ^

What is the problem?
Note:It does allow me to upload the code but I am almost certain it will generate some errors while running...

If you want to use an instantiated object as volatile then the functions within it also have to be marked as volatile. That tells the compiler that the instance pointer you will be passing to the function (the auto-inserted this parameter) is volatile:
class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark() volatile {
      start_time=millis();
    }
    uint32_t lapsed() volatile {
      return millis()-start_time;
    }
};


text:
Error: `nullptr` was not declared in this scope. Arduino IDE
I try to use this ArduinoThread library. In the Arduino I go Sketch->Import Library->ArduinoThread. After that I have the following line in the beginning of the sketch:
#include <ThreadController.h>
#include <Thread.h>
#include <StaticThreadController.h>

I leave setup() and loop() empty and try to verify or upload the sketch on my Arduino board. But I get the following errors:

Is this about the library or I do something wrong?

How old is your Arduino setup?  Maybe https://stackoverflow.com/questions/24845127/error-constexpr-does-not-name-a-type-m-arduino-ide would help

I am using Arduino 1.8.5. I think it is pretty recent, isn't it?

It works with 1.6.8 and 1.6.9 those are the ones I have and it compiles without errors.

What do you have selected in the Tools > Board menu? You should always post text as text, not a picture of text.

Sorry for that. It turned out I was using old version of Arduino IDE indeed. Seemingly, I have installed IDE twice. Two different versions. One manually and other is by apt-get. arduino command, of course, was for the old version. Now it works. Thank you.

Please write an answer to your question to help out anyone else who also encounters this issue.

I installed Arduino IDE in two different ways (only god knows why). The first one was via using of manager apt-get and other was manually via downloading, unzipping and installation through the install.sh file.
It seems that on Ubuntu 14.04 the
sudo apt-get install arduino

command provides an installation of an old version of Arduino IDE.
So eventually I was launching Arduino IDE by arduino command in my terminal (actually I was using d-menu in i3). No surprise it ran the old one installed by apt-get. I just removed that version by
sudo apt-get remove arduino

And now I am using executable arduino inside unzipped folder. Actually, I am not using Arduino IDE explicitly at all. I am using a Makefile from here.


text:
Help: Using if-else on two switch state
Problem
I'm stuck on triggering different switch. I'll explain what each of  my switch should do. Output of this setup : No output from relayPin
mainPin

Main power of the switch to control relayPin — keeps on/off
Override reedPin state
Let SecondState

reedPin

Secondary power switch to control relayPin — depends on mainPin on/off state
Overridden by mainPin
Let FirstState

*another explanation in comment
Is it caused by coding or hardware? Pardon my ignorance, it is my beginner code. I would appreciate any help, thank you.
Code
const int reedPin = 8; // Reed Switch
const int mainPin = 9; // Main Switch
const int relayPin = 6; // Relay

int FirstState = 0;
int SecondState = 0;

void setup() {
    pinMode(relayPin, OUTPUT);
    pinMode(reedPin, INPUT);
    pinMode(mainPin, INPUT);

}

void loop() {
    FirstState = digitalRead(reedPin);
    SecondState = digitalRead(mainPin);
    if (FirstState == HIGH) {
        digitalWrite(relayPin, LOW);
    }
    else if (SecondState == HIGH) {
        digitalWrite(relayPin, HIGH);
    }
    else {
        digitalWrite(relayPin, HIGH);
    }
}

Only else if (SecondState == HIGH) { works in output.
Schematics

Your problem statement is very hard to understand. A pair of switches can be in four different states (off/off, off/on, on/off, on/on): please clearly state what the program should do in each of these four cases. 2. Do not connect the relay directly to the Arduino: first search the Web for “connect relay to Arduino”, then use a suitable transistor.

Thank you for your response, actually I'm using relay alone on schematics because I'm using module instead. There is 2 switch, first one acts like normal and override second switch which are reed switch. IF first one is on, then second one has a function to on/off. IF the first one is off, then second one has NO function

Only you know what “first one acts like normal and override second switch” means. Again, please, tell us what the Arduino should do in each of the four possible situations. If you are unable to tell us what your Arduino should do, then you will never be able to program it to do what you want.

Alright, first switch SW1 is main switch - referred as firstState in code.
when this is off, U1 (referred as secondState in code) has no function
What U1 does is simple on/off (reed switch).
What SW1 does enables U1 function
Sorry for confusion.

The first one "enables" the second one ? You are missing a pinMode(switchMain, INPUT). Please use 'relayPin' instead of 'relaySwitch'. Use consistant names for everything. Please use always the same name for the first one, second one, and so on. Both in your sketch and in your explanation. Update your question and the sketch as well.

Draw a truth table and look at it from there.  From your words, it is confusing.  From your code it looks like this:
mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     HIGH

So:
void loop() {
      digitalWrite(relayPin, !digitalRead(mainPin));
}

If you want:
mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     LOW

then:
void loop() {
      digitalWrite(relayPin, !(digitalRead(mainPin) || digitalRead(reedPin)));
}


text:
memory game arduino
so I have a project which is to make a simple memory game using Arduino where the LEDs have to blink in a certain pattern and the player has to imitate the same pattern
but unfortunately I'm having so much trouble with the code
I want to make an if statement to check whether the button was pressed or not if it was it continues to check on the second button and if it wasn't the red led (which means wrong) has to  turn on
this is how i started:
enter code here

const int button1 = 2;          // 1st button controls Blue LED
const int button2 = 3;          // 2nd button controls Yellow LED
const int button3 = 4;          // 3rd button controls Green LED
const int button4 = 5;          // 4th button controls Red LED
const int led1 = 7;             // Blue LED
const int led2 = 8;             // Yellow LED
const int led3 = 9;             // Green LED
const int led4 = 10;            // Red LED
const int correctLED = 6;
const int wrongLED = 11;
int val = 0;

// Variables
int buttonState[] = {0,0,0,0};         // current state of the button
int lastButtonState[] = {0,0,0,0};     // previous state of the button
int buttonPushCounter[] = {0,0,0,0};

void setup() {
  // initialize inputs :
  randomSeed(analogRead(0));
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);

  // initialize outputs:
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  // initialize serial communication for debugging:
  Serial.begin(9600);
        }
  }

 void loop() {
       digitalWrite(7, HIGH);
       digitalWrite(8, HIGH);
       digitalWrite(9, HIGH);
       digitalWrite(10, HIGH);
       digitalWrite(7, LOW);
       digitalWrite(8, LOW);
       digitalWrite(9, LOW);
       digitalWrite(10, LOW);

       digitalWrite(7, HIGH);
       delay(500);
       digitalWrite(7,LOW);
       delay(500);
       digitalWrite(8, HIGH);
       delay(500);
       digitalWrite(8,LOW);
       delay(500);
       digitalWrite(9, HIGH);
       delay(500);
       digitalWrite(9,LOW);
       delay(500);
       digitalWrite(10, HIGH);
       delay(500);
       digitalWrite(10,LOW);
       delay(500);

       val = digitalRead(2);  // read input value
       if (val == HIGH) {         // check if the input is HIGH            (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
       digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(3);  // read input value
       if (val == HIGH) {         // check if the input is HIGH           (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
        digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(4);  // read input value
         if (val == HIGH) {         // check if the input is HIGH (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
       digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(5);  // read input value
       if (val == HIGH) {         // check if the input is HIGH (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
         digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       digitalWrite(correctLED, HIGH);

       }
       }

Do yourself a favour and learn how to indent your code properly.

As for your problem: think passwords.

You can automatically format your code in the Arduino IDE by going into the "Tools" menu and selecting "Auto Format."

You have too many closing braces.

Downvoted because you didn't say what problem you're having.

For this kind of thing you don't really want to be worrying about "is this button and then this button pressed" etc. That thinking is very much "of the moment" in that it is all about what is happening now - not what has gone on in the past.
You need to be thinking about the sequence of button presses that you have seen so far - not what is happening right now.
Say you have three buttons.  Let's assign a number to each of them - say they are buttons 1, 2 and 3.
And you have 3 LEDs - let's call them A, B and C.
So you light and extinguish the LEDs in a specific order, say BAC, and you expect the buttons to be pressed in the same order - 213.
You can't be checking all the time for "If 2 is pressed then 1 is pressed then 3 is pressed" because, basically, where are you in that sequence at any one instance in time?  Instead you need to go:  "A button has been pressed. I'll store that fact." And then: "Have three buttons been pressed? Yes. Do their numbers match?"
Basically like a PIN code for your bank card, or a password for your computer. It's not what you are pressing now, it's what it remembers you pressing in the past.
And the simplest way of doing that is to literally allocate numbers to the buttons. When a button is pressed you assign a number representing that button to a variable. Then append that number to the list of numbers you have seen recently. When that list is the right length you compare it. Just like entering a password.
You can even compare what you have so far with a portion of what you expect to catch incorrect presses early.
So say you have an expected value of "213" stored in a string. You also have an empty string. When you press a button you append that number to the string - so say you press "212" you could then append and compare the string like this:
Button  Input  Expected
2       2      2         Correct
1       21     21        Correct
2       212    213       Incorrect - erase input content
2       2      2         Correct
1       21     21        Correct
3       213    213       Correct - next round please.

Format and extra braces aside there are other issues with your code, too many to fit in a comment.

You have used led1, led2 etc in the setup routine and the resorted to numbers in the loop function.
At the start of loop() you turn the leds high then low, you won't see this because the processor is faster than your eye, you need a delay statement after the last high and last low.
You can make you code more elegant by writing a function that takes the pin as a parameter and toggles the led high then low and call this rather than repeating 4 lines of code.

void togglePin(int pinNumber, int interval)
{
   digitalWrite(pin, HIGH);
   delay(interval);
   digitalWrite(pin, LOW);
   delay(interval);
}

When it comes to reading values you have blocks of repeated code, again these could be a separate function, which will make your code easier to read and understand.

When you have done that you might want to so a bit of research on 'switch debouncing' because I'm guessing you might have issues with that too.

Your code as written will have both the wrongLED and correctLED on. It will also continuously loop showing the sequence.
Showing the Sequence
To show the sequence once at the start, put it in the setup function.
Read more about the setup function here: http://www.arduino.cc/en/Reference/Setup
Detecting the Button Presses
You want to detect each press of the buttons. For this you will need edge detection code. There is an Arduino example built into the IDE and information describing the function here: http://www.arduino.cc/en/Tutorial/StateChangeDetection
To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge:
if ( (lastButtonState == LOW) && (buttonState == HIGH) )

where buttonState would be assigned by a digitalRead and lastButtonState would record the value of buttonState at the end of the loop function (ie. just before it reads in the button states again).
Using your global arrays you could write:
buttonState[0] = digitalRead(button1);
buttonState[1] = digitalRead(button2);
buttonState[2] = digitalRead(button3);
buttonState[3] = digitalRead(button4);

if ( (lastButtonState[i] == LOW) && (buttonState[i] == HIGH) )

where i is a number between 0 and 3. You could use a for loop to cycle through the 4 available buttons.
Recording the Button Presses
The StateChangeDetection example above counts the number of button presses. Instead, you want to record 4 button presses. To do this create a global variable called pressNumber. Create it with the initial value of 0.
Create an integer array of 4 elements called `userSequence'.
Every time the if statement detects a rising edge, store the button number in the userSequence' at positionpressNumberand then increment thepressNumber`.
When pressNumber reaches 4, the user has entered his/her guess.
Evaluating the Guess
This only occurs once the user has entered the guess. Start off by creating a boolean variable and assign it TRUE. Cycle through the elements in the userSequence array and compare the users guess to the correct answer. If the user gets one wrong set the boolean variable to false. At the end, turn on the red LED or green LED depending on the state of the boolean variable (ie. if it is true turn on the green LED, otherwise turn on the red).
Final Notes

As Matt suggests, try refactoring portions of code into functions. It makes the code more readable and reduces the complexity of the code.
You can use the variables for the pin numbers of the buttons and LEDs in the digitalWrite and digitalRead functions. Eg:
digitalRead(button1);
digitalWrite(led1);


text:
Measuring .7 volts on pin 2 and 0.0 on the rest when setting all pins low
Having my Arduino Nano 328P disconnected from any circuitry and setting all pins to pinMode(OUTPUT) and writing LOW to (almost) all the pins, when I connect my multimeter to every output pin and the Arduino ground, I measure 0.7 volts on pin 2 and 0.0 volts on 3 to 19. Here I mean the pin numbers on the edge of the Nano, not the processor pins.
For my project it worked out fine because I needed those 0.0 and not the 0.7, but I'm afraid it suddenly might not be pin 2 that's 0.7 in the future and my circuit would fail.

Why is there this one pin giving 0.7 instead of 0.0 and how can I make sure or argue that it will only be pin 2 that gives 0.7?

EDIT as per request, the full test code is below.
void setup() {
  for (int i=1;i<20;i++){
  pinMode(i, OUTPUT);
  }
}

void loop() {
  for (int i=1;i<20;i++){
    digitalWrite(i, HIGH);
  }
    delay(3000);
    for (int i=1;i<20;i++){
    digitalWrite(i, LOW);
    }
    delay(3000);
}

What voltage is your 328P running at? At 5V, 0.7V is still perfectly within specification (0.9V max V[OL]).

@Majenko I'm not sure exactly, I'm running it via a phone wall adapter which outputs 5V/1A which I think should be enough, how could I check if it really is? If you think it's the voltage provided, I'll check when powering it via my laptop.

No, you misunderstand. There are two options for running the boards like the Micro / Nano, etc - 5V or 3.3V. The V[OL] specification changes depending on supply voltage, and that is fixed by the board, not the PSU. It sounds like you have a 5V version anyway, so the output is within specification.

@Majenko Ah yeah I knew about the 5V-3.3V difference, but I have the 5V one. I confirmed that V[OH] is 4.7V for every pin. But where did you find the maximum V[OL] is 0.9? I had googled before asking the question to find that value but didn't find results. Do I understand correctly that that means you just know the voltage output is between 0 and 0.9 and you cannot guess the exact value?

The value is in the datasheet, page 313, table 30-1.

@Majenko I'm a bit confused which datasheet, I mean there is no Nano datasheet right? I looked into the ATMega 328P sheet but can't find it there.

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

@Majenko Oh that's curious, I was looking at a 328P datasheet but a different one. Anyway, I see what you mean, the 0.0 or 0.7 is just some kind of stable noise. Thanks for pointing that out, I'll think of a way to adapt my circuit to that.

You were probably looking at the summary sheet.

@Majenko To summarize 660 pages into 444 seems weird to me, haha. http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf

@Majenko I think you should post your comments as one answer.

Can you post your code please? I personally like to see code, not a description of it.

@NickGammon Of course, I'll do that immediately next time. I included it now.

writing LOW to all the pins - all pins except pin D0, eh? Your question is a bit non-specific. Do you mean pin D2 on the edge of an Arduino Uno? Or pin 2 on the actual Atmega328P chip? Pin 2 on the chip itself is D0 in the IDE, which you have not written LOW to.

@NickGammon Ah I didn't know those number differed, I meant pin 2 on the edge of the Nano (not Uno) all the time, that I didnt include pin 0 shouldnt matter as I skipped pin 0 and 1 alltogether. I'll edit the question.

For future reference, thanks to Majenko: these values fall within the expected voltage output range of 0-0.9V, and you cannot be certain it will stay this way. See the datasheet page 313.


text:
not getting proper bitstream output in serial monitor using digitalRead
I am producing a  data stream and feeding to a gpio pin. THe data is sampled at 2kbps. i want to dump this data into a file after a certain length of reading . how should i proceed with this ?

Not without seeing your code we can't.

My guess is that you are reading the port to often and not a multiple of the frequency of the wave.  So if your wave is 1Hz and you want to see 101010 then read at 1Hz not 4.25Hz.

You could clarify your question by describing the frequency of your test signal, and the sampling frequency. Unless you have an accurate reference clock (connecting the source and the sampling), you will need to oversample the signal, at least twice the toggle frequency, otherwise you will get a misleading result.

Without seeing your code it's impossible to tell just what is happening, but I would guess you are reading and printing the level of the wave, not the transitions from one level to another.
For instance:

As you can see, just reading regularly and printing it (which itself is quite slow) results in 11001101 rather than the 10101 that you want. That's because the speed of your reading/printing and the frequency of your wave are completely separate things and out of step with each other. There's nothing to tie one to the other.
Instead you need to look for the transitions from LOW to HIGH and from HIGH to LOW. Only when the input changes should you look to see what the new level is and print that.

As you can see the 1 and 0 are just after the change in level, since it's impossible to do anything during a change, only once the change has happened.
You might code that as something like:
void setup() {
    Serial.begin(115200);
    pinMode(3, INPUT);
}

void loop() {
    static byte oldValue = LOW;     // Place to store the previous level
    byte newValue = digitalRead(3); // Read the current level
    if (newValue != oldValue) {     // The input has changed
        oldValue = newValue;        // Save the current level
        Serial.print(newValue);     // Print it.
    }
}


text:
Receiver Module Second Data Pin
Many of the receiver modules (MX-05V) working with the Virtual Wire library (I would like to add a link here but it requires 10 reputation, so I'll do that later) have two data pins. However only one of them is used in the examples I have seen so far.
This picture shows a transmitter (top left) and a receiver (bottom right). Apparently the receiver has four pins - two of them are data pins.

Image source
What is the purpose of the second data pin on the receiver module and how to use it?

you can still put the part number of the module in your question.  Someone might then edit your post and put in the data sheet.

I would expect only one data line output from the receiver.
Looks like the manufacturer might have just connected the 2 data pins together. You could try using either pin to confirm that the two data output pins are simply connected together.


text:
Creating String Arrays and passing each index value to a variable after a given period
Is there a way to take an input string, store it into a array and then pass each index of that array to a variable to hold  before being overwritten by the next array index value?
For example:
A number of input values which are of type:String are being created
String 1 is given as "Value: 7.93 22-10-2017 10:33:32"
String 2  is given as "Value: 8.93 22-10-2017 12:10:15"
.
.
.
String 10  is given as "Value: 6.93 22-10-2017 18:03:04"

The string structure is known but its contents as such will vary
After a time period of say 60sec. The contents of array[0] which will be String 1 will be assigned to a given variable "output"
After the next 60sec time period .The contents of array[1]  Which will be String 2 will be stored into  the same "Output" variable in which the previous value will be now overwritten
This continues until array[9] i.e String 10 in which the array will begin over and start to populate "output" with newly presented string values

http://idownvotedbecau.se/imageofcode

Also, please tell us what you are trying to achieve. Passing an index to a variable is not the real goal, but only the means to an end. What is your real goal?

Originally I was attempting to pass the characters of each string using the toCharArray() function. The solution was much simpler and straight forward in the end. I've posted it below.

Solution Used Below:
// Input 1-3 represents input string

String Input1 ="Value: 7.93 22-10-2017 10:33:32";
String Input2 ="Value: 8.93 22-10-2017 12:10:15";
String Input3 ="Value: 8.93 22-10-2017 12:10:15";
String message[] ={Input1,Input2,Input3};

// Assigned 'Output' Variable will be populated by each index of the array
String Output;

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

// Each index of the array will be stepped through and passed to 'Output'
//delay() will control period between each index value

void loop()
     {
         for (int i = 0; i < 3; i++)
            {
                  Output=message[i];
                  Serial.println(Output);
                  delay(5000);
            }

     }


text:
NodeMCU code that both display OLED and control WS2812 LED Ring
I'm trying to make a project using NodeMCU that show pictures in small OLED screen and also controlling WS2812 LED Ring.
I manage to do each of them separately but I'm not sure how to mix them together. The problem lies in the fact that most code examples for both the screen and the LED use sleep and that will of course only work for one of the other but not both.
This is the first project I've looked at to display bitmaps with SSD1306  screen and nodemcu.
This is the second project I've looked at to control NeoPixel WS2812 ring.
The main project was that both of them use delay as a way to wait for some amount of time to "progress". But, I couldn't just wait because then it will mess up both the screen and the NeoPixel.
One more thing is I have to also take reading input into account. I still not 100% sure about the input but it will probably be potentiometer and maybe a button.
I think I have found the solution which is to break the large "tasks" of reading input, controlling screen and controlling leds into smaller parts and do the waiting in a cooperative way.
I've found this instructable which both explain how to do it and also provide code example.
I'll be glad to know if people how other ways to implement this.

I'm not sure how to mix them together ... how do you drink some water while eating dinner?

Why don't you post your code? We can take a look at it and probably suggest something to get you started.

There is an example called BlinkWithoutDelay (you can find that in the Arduino IDE by going to Files->Examples->02.Digital). That gives you an idea of how you can do your things without using delay(). The third link you added uses that concept.

You need to stop using delay and instead keep track of elapsed time. One of the comments under your question suggests looking at the BlinkWithoutDelay example, which is part of the Arduino IDE.
The jocular comment "how do you drink some water while eating dinner" suggests the solution. You do one thing for a moment, and then do another thing. When eating dinner you don't wait for the entire meal to be consumed before you can drink a glass of water.
Here's some example code that blinks two LEDs at different rates:
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop


text:
Arduino SPI - MOSI not writing any data but clock works
I am trying to iterate over an int array and writing those values to a chip. Here is my code.
#include <SPI.h>

int sine[] = {0x7fc ,0x868 ,0x8d4 ,0x93c ,0x9a8 ,0xa10 ,0xa78 ,0xadc
,0xb3c ,0xba0 ,0xbfc ,0xc58 ,0xcb0 ,0xd04 ,0xd58 ,0xda4 ,0xdf0 ,0xe34 ,0xe74
,0xeb0 ,0xee8 ,0xf1c ,0xf4c ,0xf74 ,0xf98 ,0xfb8 ,0xfd0 ,0xfe4 ,0xff0 ,0xff8
,0xffc ,0xff8 ,0xff0 ,0xfe4 ,0xfd0 ,0xfb8 ,0xf98 ,0xf74 ,0xf4c ,0xf1c ,0xee8
,0xeb0 ,0xe74 ,0xe34 ,0xdf0 ,0xda4 ,0xd58 ,0xd04 ,0xcb0 ,0xc58 ,0xbfc ,0xba0
,0xb3c ,0xadc ,0xa78 ,0xa10 ,0x9a8 ,0x93c ,0x8d4 ,0x868 ,0x7fc ,0x794 ,0x728
,0x6bc ,0x654 ,0x5ec ,0x584 ,0x520 ,0x4bc ,0x45c ,0x400 ,0x3a4 ,0x34c ,0x2f4
,0x2a4 ,0x258 ,0x20c ,0x1c8 ,0x188 ,0x148 ,0x110 ,0xe0 ,0xb0 ,0x88 ,0x64 ,0x44
,0x2c ,0x18 ,0xc ,0x0 ,0x0 ,0x0 ,0xc ,0x18 ,0x2c ,0x44 ,0x64 ,0x88 ,0xb0 ,0xe0
,0x110 ,0x148 ,0x188 ,0x1c8 ,0x20c ,0x258 ,0x2a4 ,0x2f4 ,0x34c ,0x3a4 ,0x400
,0x45c ,0x4bc ,0x520 ,0x584 ,0x5ec ,0x654 ,0x6bc ,0x728 ,0x794};

#define samples 120

const int cs = 9;

int counter = 0;

const int chipSelectPin = 10;

void setup()
{
  pinMode(cs,OUTPUT);
  pinMode(chipSelectPin, OUTPUT);

 SPI.beginTransaction(SPISettings(20000,LSBFIRST,SPI_MODE3));
}

void loop()
{

  digitalWrite(cs,LOW);

  SPI.transfer(sine[counter]);

  digitalWrite(cs,HIGH);

  counter += 1;

  if(counter >= samples)
  {
    counter = 0;
  }

}

Very simple, I am using an Arduino nano and according to this reference the clock pin is 13 and MOSI is 11. I am seeing the clock signal for pin 13 but pin 11 is inactive.

You need to use SPI.begin() before the beginTransaction().
The documentation is not 100% clear but beginTransaction does not replace SPI.Begin to setup the SPI hardware.
Documentation not very clear: https://www.arduino.cc/en/Reference/SPIbeginTransaction

In addition to @Talk2's answer SPI.transfer(...) transfers one byte of data. Your array is made of int which means each entry is 2 bytes long.
Instead you should use SPI.transfer16(...) to transfer 16-bit values.

This is something I also wanted to address thank you for pointing it out.


text:
Arduino program does not start when plugged in
I am having trouble with my Arduino Mega with getting the program to start when the Arduino is plugged into a computer via USB.  All that happens is the LED turns on and stays on.  The device does not initialize, and only when I press the reset button does it begin the setup.  How can I make the Arduino start the program when it is first plugged into the computer?
EDIT: my code
void setup() {
  Serial.begin(115200);
}

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

very simple, which is why i don't understand why this is happening

The arduino will start executing immediately, unless you have serial statements looking for a connection holding up execution. can you share your code?

As said by @sspence65, the Arduino starts as soon as you power it. You are simply missing the startup message because it is sent before you open the serial connection on the PC end.

Actually the message is sent repeatedly but the arduino will probably reset a second time when the virtual serial port is opened.

@ChrisStratton, actually it doesn't reset and that is another problem I am having.  For some reason when the connection is established, the Arduino does not reset and sometimes there is already data in the buffer and it confuses the program and often I have to restart the program one the buffer has been read empty

Try explicitly toggling RTS and DTR via your computer's serial api.  At some point you may need to look into details of the USB serial implementation on your specific "mega".

I would recommend you to follow the following instructions step by step to verify your Arduino Mega.

Reboot your computer
Connect the Arduino using the USB cable to PC and check the Arduino itself if there is any jumper wires connected/grounded. If there are then remove them all.
Upload a blank sketch first. Go to File -> New
Verify the Arduino has accepted the blank sketch and resetted.
Upload the Blink sketch from the File -> Examples -> 0.1Basics -> Blink
Verify if the Pin 13/onboard LED is blinking. If yes then go to uploading your sketch, if no then there is a hardware/bootloader problem with your Arduino. Watch this video on how to burn bootloader here. https://www.youtube.com/watch?v=X5achE10rCI


text:
Arduino uno unexpected void loop stop
I have a trouble with following, few lines code.
For some reason after few seconds Arduino uno stops responding into void loop section of code.
I tried to remove serial communication, all print and println without any success. Is the problem comming from MMA_7455.h?
#include <MMA_7455.h>
#include <Servo.h>

int servoPin = 9;
int servoAngle = 0;

Servo servo;

MMA_7455 accel = MMA_7455();
char yVal;
char yVal_bkp;

void setup() {
    servo.attach(servoPin);
    accel.initSensitivity(2);
    accel.calibrateOffset(1.0, 26.0, -69.0);
}

void loop() {
    yVal = accel.readAxis('y'); //Read out the 'y' Axis

    if(yVal_bkp != yVal + 2 || yVal_bkp != yVal -2)
    {
        servo.write(90 + yVal);
        yVal_bkp = yVal;
    }
}

P.S. Servo is normal G90

accel.readAxis() returns unsigned char. You are using char which is signed in AVR GCC https://gcc.gnu.org/wiki/avr-gcc

Yes, it returns only positive values, I alredy verified, but if you assign this value to char yVal it returns signed value (ex -12) in Serial.print(yVal, DEC);

Have you checked that MMA_7455 can handle this many reads?
I had sensors that stop working because I asked to often for feedback.
As the servo needs a 20ms to adjust its location I would add a delay(20) to the loop.

Thanks for reply. After delay(20); add, correct execution is going for much more time, but anyway stops after. Increased also to 40, same result...


text:
Simple IR Receiver code
Can I know a code for simple IR receiver. I using external trasmitter, and when the receiver (on arduino board) get the input (detect signal from transmitter), LED will be HIGH.

This isn't a code-writing service. I suggest you ask a more specific question. There are plenty of examples of code that detects IR codes. It would be simple to turn an LED on if a certain code was received.

Here is a library that might be able to help you out: https://github.com/cyborg5/IRLib/. Also a specific example of controlling a server from a sony remote control. https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino
I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.
#include <IRLib.h>

#define MY_PROTOCOL SONY
#define BUTTON_0 0x90bca  //LED ON
#define BUTTON_1 0x00bca  //LED OFF

#define LED_PIN 13 //Pin to LED

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;

void setup() { //Code to run once
  My_Receiver.No_Output();//Turn off any unused IR LED output circuit
  My_Receiver.enableIRIn(); // Start the receiver

  pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
  digitalWrite(LED_PIN, LOW); //Start off in the off position
}

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode(); //Convert the values into types
       if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
          switch(My_Decoder.value) {
            case BUTTON_0:      digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
            case BUTTON_1:      digitalWrite(LED_PIN, LOW); break; //Turn the LED off
          }
       }
     My_Receiver.resume(); //Wait for next input
    }
}

This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this
void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
        My_Decoder.decode();
        digitalWrite(LED_PIN, HIGH); //Turn the LED on
    }
    My_Receiver.resume(); //Wait for next input
}

Edit:
A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: https://github.com/z3t0/Arduino-IRremote
    #include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote

#define IR_PIN = 11; //The data pin to the IR recv
#define LED_DATA = 13; //Either the builtin LED or plug one in

IRrecv irrecv(IR_PIN); //Start recv obj
decode_results results;

void setup()
{
  Serial.begin(9600); //Start Serial at 9600 baud
  pinMode(LED_DATA, OUTPUT); //Set LED pin to out
  digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    //We have recieved something... lets print it and turn on the LED
    digitalWrite(LED_DATA, HIGH);
    Serial.println(results.value, HEX); //Send line in ascii hex format
    delay(200); //Make the LED visible
    digitalWrite(LED_DATA, LOW); //Turn off data led
    irrecv.resume(); // Receive the next value
  }
}

Edit #2
Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.
    #include <avr/interrupt.h>
#include <avr/io.h>

#define TIMER_RESET  TCNT1 = 0
#define SAMPLE_SIZE  64
#defome LED_PIN 13

int IRpin = 2;
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time;

void setup() {
  Serial.begin(115200);
  Serial.println("Analyze IR Remote");
  TCCR1A = 0x00;          // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
  // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
  // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
  TCCR1B = 0x03;          // 16MHz clock with prescaler means TCNT1 increments every 4uS
  // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
  // TOIE1=0 => Timer 1 Overflow Interrupt Enable
  TIMSK1 = 0x00;
  pinMode(IRpin, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

void loop()
{
  Serial.println("Waiting...");
  change_count = 0;
  while(digitalRead(IRpin) == HIGH) {}
  TIMER_RESET;
  TimerValue[change_count] = TCNT1;
  direction[change_count++] = '0';
  while (change_count < SAMPLE_SIZE) {
    if (direction[change_count-1] == '0') {
      while(digitalRead(IRpin) == LOW) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '1';
      digitalWrite(LED_PIN, LOW);
    } else {
      while(digitalRead(IRpin) == HIGH) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '0';
      digitalWrite(LED_PIN, HIGH);
    }
  }
  Serial.println("Bit stream detected!");
  change_count = 0;
  time = (long) TimerValue[change_count] * 4;
  digitalWrite(LED_PIN, LOW)
  Serial.print(time);
  Serial.print("\t");
  Serial.println(direction[change_count++]);
  while (change_count < SAMPLE_SIZE) {
    time = (long) TimerValue[change_count] * 4;
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count-1]);
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count++]);
  }
  Serial.println("Bit stream end!");
  delay(2000);
}

If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.
best regards, David

I mean "get the input" is receiver get signal from transmitter

I've added the new sample with getting data and printing it, and a library that seems slightly easier to use.

I know you want code.  However your question is how to light up an LED when an external remote control is transmitting.  This can be done with the following hardware:
Many ASK sensors integrate an IR photo sensor, AGC & PLL into a 3 pin package that has an appearance of a transistor.  Supply power and get back a signal when an ASK IR transmitter is detected.  Check the current capabilities of the ASK receiver, you might have to add a transistor to drive an LED.  No Arduino needed for detection.
Here is an example found on the web:


text:
Error when using buzzer and IR sensor
I am doing code for IR sensor. My problem is when I put this code (below) for buzzer, there will be error.
C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of `__vector_7'
IRremote\IRremote.cpp.o:
C:\Program Files\Arduino\libraries\IRremote/IRremote.cpp:312: first defined here
collect2: error: ld returned 1 exit status
  tone(buzzer, 4000); // Send 1KHz sound signal...
  delay(500);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  delay(500);        // ...for 1sec

Both the IRRemote library and the tone command use the same timer. You can't use them both together without modifying one of them to use a different timer. And that means looking at the source code for them both.

can I know how to solve it?

I already found the solution. Thanks for your advise. :)


text:
Can I read using an analog pin on an arduino Mega whether or not there is a high (5v) voltage on a wire from another board's digital pin?
I am making a peer-to-peer network of initiating devices and a common hub, which controls most of the hardware. It sends a number over Serial to Mega's Serial1 (Mega's Serial is used for communicating to the computer), but as a fallback it initiates a general alarm by sending a 5v signal (using digitalWrite(pin, HIGH)) to the main board. In order to complete the circuit and get the read, how would I do this?
Thanks!

what you ask is purpose of a digital pin. to read a state of a digital pin of some other device

5V is a value of voltage, not a value of current .... please edit the title of your post

Yes of course you can. Better to use digitalRead() than analogRead() however.
You just need to tie the grounds of the 2 Arduinos together, and set up the pin on the Arduino you want to sense the input as INPUT or INPUT_PULLUP. Then do a digitalRead on the pin. It will return LOW if the other Arduino is setting the pin LOW, and HIGH if the other Arduino is setting it HIGH.
And, as Juraj points out in their comment, CMOS devices like Arduinos respond to voltage, not current. Their inputs are capacitive. They react to a voltage potential, not current. (When you initially change a CMOS input from one state to another a small amount of current flows in to change the state of the capacitor and after that the only current that flows is a very tiny amount of leakage current through the capacitor on the input.)

Thanks a bunch, I would not have thought of this myself. I'd have gone to the ends of the Earth over-engineering some code to beam signals off the moon and back just to say "HEY" to the other board lmao.

@duncan-c, you should not suggest in an answer on Arduino SE that LOW is  false and HIGH is true.

@Juraj, why shouldn't you suggest this? In my experience, we use switches that are normally open when in normal state, so closing them and closing a HIGH voltage would signify the change.

@WinterfromSYGMAH  HIGH / true, and LOW / false are different constants, and should not be used interchangeably. Juarj is correct. I edited my post.

@DuncanC and Juraj, thank you for the clarification and the help

formally, you should always write digitalRead(pin) == LOW or digitalRead(pin) == HIGH to check the state. there is no warranty that the value of LOW is 0 on all Arduino architectures. there could be some strange MCU package somewhere :-)


text:
Arduino Lego Robot
I'm currently developing a Lego Robot, the mindstorm series to be specific. I want to replace the lego NXT brick with an arduino, maybe an intel galileo in the future. How do I establish connections from the arduino with the lego sensors? Also, I would like some input on any cool features that I can add to this robot. This robot is to be seen as a human companion. Thanks in advance.
An example of a sensor i would like to use is here : http://www.hitechnic.com/cgi-bin/commerce.cgi?preadd=action&key=NIS1070
How do I interface this with an arduino?

Looks like they use I2C so you just have to look at the pinout and then hook it up to the I2C pins on the Arduino. http://www.dexterindustries.com/howto/connect-the-arduino-and-the-lego-mindstorms-together/

Doing a quick search on google you can find a couple of shields designed for that purpose:

NXShield-Dx
Bricktronics shield

Second one is allows less motor connections but it's cheaper and has a book written by the designers