Just a note for those who wonder the same and are in need of a vacuum: In theory, you can use Venturi effect (or Bernoulli's Principle; it's basically the same) to create a vacuum. Or go buy an Aspirator pump. Since English is not my native language it's difficult for me to explain it in my own terms, but I'll try to give you a rough idea anyway. (Google it or feel free to answer with a better explanation).

First you need some flow of a fluid or gas (air from a compressor or water from a household outlet are fine). You pass that flow through left-to-right in a T-pipe (I'll call that the "flow pipe"). This will result in a weak vacuum in the orthogonal pipe (I'll call this the "vacuum pipe"), which you can connect to your suction cup.

The strength of the vacuum depends on the pressure in the "flow pipe". That means a higher velocity of your matter in the "flow pipe" is good (either a stronger compressor or smaller diameter of your flow pipe).

If I understand my physics book correctly, a higher density of the matter in your flow pipe will also produce a stronger vacuum. If you need a really strong vacuum, you could even use a water compressor, i.e. high pressure cleaner; but I suppose even a small air compressor will outperform a household water outlet (and you could toggle it from an Arduino with a relay board).

Since the air in the vacuum pipe expands more than many other materials, you could try to replace it with i.e. oil (be aware you'll pull out some of the air/replacement material at the intersection in aspirator!). This optimization is dangerous with a normal vacuum pump, since these usually break when sucking up fluids into their internals.

Also using an aspirator has the upside of not needing to buy a vacuum pump if you already own a compressor. On the other hand, that setup might be even louder (and possibly less efficient) than a dedicated vacuum pump.


You have bad Unicode characters in your code. All your semicolons are something completely different and need replacing with real semicolons.


How Should I Send Data to My Laptop from Multiple Arduinos?

There are multiple solutions but the simplest one is probably to use Software serial, I2C, or SPI. The idea is basically the same for any of the protocols. You select one Arduino which is gonna be the master and be connected to the laptop. Than using any of those interfaces you connect the Arduino boards in to a chain. Than you can ask the slave Arduino boards if they have new data one by one. If they do they send it and the master forwards it to the laptop. In this way all the slave boards will wait until they are asked for data and thus avoid collisions of data streams.


Atmega collecting and relaying interrupt calls

The interrupt vector table is provided by the C runtime. It is
not normally intended to be overridden by user code. You can, however,
do it, if you replace the whole C run time by your own, and compile your
sketch with the -nostartfiles option.

I have played this game once I was trying to accurately assess interrupt
latencies. See the details in this answer (the answer is long,
but you can go right to the last section).


I modified your code to produce a working example:

const unsigned long fiveMinutes = 20 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  Serial.println (fiveMinutes);
  }  // end of setup

void doStuff ()
  {
  Serial.println ("Doing stuff");
  }

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.

  I thought I could update global variables inside subroutines ...

You can.

Are you sure you didn't have:

void loop() {
  unsigned long lastCheck;
...


The function prototype of a member function is completely different to that of a global function. The two are not interchangeable.

There are ways of working around it, such as "bouncing" your callback through a global function, but they're messy.

However, in this situation you are better off just ditching TimerObjects.h and doing it manually - it's not exactly difficult:

#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
     void pumpstep(void);
     uint32_t ts;
     void run()
  private:
    char pin;
    char dir;
};

#endif

Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    ts = 0;
    pinMode(pin, OUTPUT);
    pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

void Pump::run() {
    if (millis() - ts >= 100) {
        ts += 100;
        pumpStep();
    }
}

Then in loop call:

myPump.run();

You can, of course, just combine run() and pumpstep() into one single function.


What will happen if I set ARef to 3.3V and try to use adc connected to 5V

The datasheet of the Atmega328P does not give a direct answer to this, but

  Single ended channels that exceed V REF will result in codes close to
  0x3FF.

(Datasheet Chapter 24.5.2)

sounds, as it would not destroy the ADC, but only result in a value very close to the maximum. I also found another side, where this is also stated. They linked to the Arduino forum, where a similar question is handled in this thread.

So all in all it should be save to provide more than the reference voltage at the ADC pins, as long as it does not exceed the supply voltage (for the UNO 5V).

As Majenko pointed out in his answer, the datasheet states, that it is safe to provide VCC+0.5V at any pin (except for reset). I just wasn't sure, if this can easily be applied to this special hardware, but it seems, that it can.


LED won't turn on and serial monitor won't display values

Like Edgar says, what you need to do is this:

bool waitFor(char in, int pollTime, unsigned long timeOut)
{
  while (micros() < timeOut)
  {
    if (Serial.available())
    {
      if (Serial.read() == in)
      {
        Serial.println("done");
        return true;
      }
    }
    delay(pollTime);
  }
  return false;
}

If it still doesn't run after that then change setup() to this:

void setup()
{
  Serial.begin(9600);
  Serial.println("Initialising...");
  pinMode(9, OUTPUT);
  while (!waitFor('g', 200, 60e6)) {}
  Serial.println("g command received...");
  analogWrite(9, 128);
  Serial.println("About to start...");
  startTime = micros();
  for (x = 0; x < 512; x = x + 1)  {
    Vs[x] = (analogRead(analogPin));
  }
  endTime = micros();
  Serial.println("Finished...");
  for (int x = 0; x < 512; x = x + 1)  {
    Serial.println(Vs[x]);
  }
  Serial.print("The result is : ");
  Serial.println(endTime - startTime);
  Serial.println("All finished.");
}


Connect 12v DC sensor to Arduino UNO using TTL RS485

You should be fine.
RS-485 does specify signal levels of ±1.5V to ±5V, but even so, and even when the sensor would misbehave or when the common mode voltage is low or high, there is still the TTL-to-RS485 converter in the middle that has 5V TTL logic on the Arduino side.
As long as the TTL-to-RS485 converter is properly connected to the Arduino and working as it should, the Arduino is safe.


Arduino nano getting powered through analog input?

Power is flowing from the analog pin, through the internal clamping diodes, to the Vcc line. Those diodes are however not designed to handle that much current, so don't continue doing this.

Either also disconnect the ground wire from the battery, or simply add a resistor between the battery and the analog pin. Something like 10k. That way less than a mA of current will be clamped, and the arduino will stay off.


Running in loop or once according to a slide switch position

Let's assume the switch is on pin 9, that the pinMode() has already been set, and that the switch reads HIGH for loop operation.

#define MODE_SWITCH  9
#define DO_LOOP  HIGH

// This loop will execute once if the mode-switch is off, or
// will execute continously if the mode-switch is on:
do {
  servo_things();
  stepper_things();
  motor_things();
} while( digitalRead(MODE_SWITCH) == DO_LOOP );

in C/C++, 'do-while' loops always execute at least once, since the condition isn't tested until after the first pass through the loop. If the 'while' condition is satisfied (or TRUE), the loop will execute again, otherwise the loop will exit.


Hardware Serial connection for Arduino Mega 2560 NEO GY-GPSMV2 GPS module

Most importantly, I want to point out that a Mega has 4 HardwareSerial ports: Serial, Serial1, Serial2 and Serial3.  There is no reason to use an inefficient software serial port library.  Software serial libraries use the processor to handle each bit transition, so they use much more CPU time.

SoftwareSerial is particularly inefficient, because it disables interrupts for the entire time that a character is being sent or received, and it can't do both at the same time.  This will interfere with your sketch or other libraries.  This answer lists the various serial port choices.

To answer your question:

  ... how can I apply this on an actual wiring? should I split the wire? or what?

Yes, 3 things get connected together at two places.  Most people use breadboards for prototyping.  Stick two wire ends (a "split" wire) and one end of a resistor into a common row of the breadboard, connecting them electrically.

But for a permanent solution, you should solder two separate wires and one end of the resistor together.  A small piece of perfboard can help secure the wires and discrete components.  It's a little kludgey, but you can strip the insulation from the middle of one piece of wire (don't split the wire) and solder one end of the resistor to it.

BTW, I always recommend real level-shifter modules that use FETs.  They're fast, so you can also use them for SPI interfaces, like an SD card, and they're bi-directional (5V to or from 3.3V).  And they're cheap.  You would just solder individual wires from the Arduino and the GPS device to various through holes in the module PCB.

The picture in your post shows a direct connection between the GPS transmit pin and the Arduino receive pin.  While this will not damage either pin, the GPS transmit voltage is not quite within the range specified for the Arduino receive pin.

Note the use of the word "specified".  If you read the specifications for the two devices, you will see that a logic 1 out of the GPS pin (called VOH) is slightly under the minimum acceptable voltage for the logic 1 input to an Arduino pin (called VIH).

You can also use discrete components to "step-up" the GPS TX voltage up a little.  You can google for many different solutions.  Hackaday has a nice summary.  MicroChip AppNote DS41285A has many suggestions.  Again, I would strongly suggest using a level-shifting module.

Many people report using a direct connection without problems.  It is possible that:

the actual devices have a higher VOH and/or lower VIH, or
the data is received with various amounts of errors, and the GPS parsing library (or sketch) ignores the errors.  Take a look at my NeoGPS library.  It is the fastest, smallest, most accurate and most reliable GPS library.  It can help you detect (and reject) bad data.


Nano 33 IoT rescue from the dead: No USB. No upload mode

Use the SWD interface and a programmer to burn the bootloader to SAMD.

source of the picture https://medium.com/@manuel.bl/arduino-in-circuit-debugging-with-platformio-9f699da57ddc

I had luck with Adafruit DAP library using an Arduino M0 to burn a bootloader to MKR Zero.


Yes, that's the idea behind bus protocols like i2c. You only require the sensors on i2c to have different bus adresses. A sensor's address usually can be chosen by soldering a jumper (the mpu6050 provides this feature on pin AD0). If you can't avoid an address collision you could use an i2c multiplexer or a microcontroller in between the sensor and the actual mcu (but probably that's not neccessary when using only two sensors).

Using SPI and I2C at the same time is absolutely no problem on the atmega!


Unplanned behavior with two power sources

Beginner error: As stated in the diagram, I connected the external source of power to the 5V pin, while it should have been connected to the Vin pin. /ashame


Int64_t aka long long acts as int32_t and overflows at 2^31

1 << 31 is interpreted by the compiler as (int)1 << (int)32.
See the implicit types of integer literals. The
rules of usual arithmetic conversions state that no implicit conversion
is performed in this case. The result is then computed as an int, and
it overflows. Note that this is undefined behavior. The assignment
int64_t a = ... converts the (already overflowed) result to the wider
type, without changing its value.

You probably want to write something like:

int64_t a = 1LL << 31;


I see a lot of 'almost' repetitions like :

  if (RelaySourceDigi == 7) {
    shifter.setPin(16, LOW);
    shifter.setPin(17, LOW);
    shifter.setPin(18, LOW);
    shifter.setPin(19, LOW);
    shifter.setPin(20, LOW);
    shifter.setPin(21, LOW);
    shifter.setPin(22, HIGH);
    shifter.setPin(23, LOW);
    shifter.write();
    lcd.setCursor(0, 2);
    lcd.write(8);
    lcd.setCursor(2, 2);
    lcd.print("Coaxial 3");
  }

Move this to a separate function, and make an argument (or more) of items that vary.
This will greatly reduce your code, making it more managable/maintainable.

Below I changed the entire program. Note I didn't check for runtime errors, and it is highly possible I made some copy/paste errors, but it will give you a clue what you can change. As you can see, the program is radically shortened (and more maintainable).

What you need to do is:

Check each change
Check for copy/paste errors
Read a little bit about pointers (e.g. the &RelaySource and *t constructs)
Also I highly suggest not to use so many constants, but use enums, to denote the value for each different mode you have. So instead of case 1, you can write case TAPE_1.
Split loop in smaller functions (e.g. one function per mode).
I didn't install your libraries but used e.g. #include "LiquidCrystal_I2C.h" and stubbed all functions (meaning I can call them but they don't do anything, just to check for compiler errors in the main program).
Also instead of Aux, use a boolean (true, false).
You see I use a lot of (state - 1) constructs. It's common practice to start counting at 0, not at 1, it will make your life easier. Only when displaying a value for a user, add +1.
Below the program.

//Libraries
#include "LCD.h"
#include "LiquidCrystal_I2C.h"
#include "Shifter.h"

#define SER_Pin 8 //SER_IN 14 on 74HC595
#define RCLK_Pin 9 //L_CLOCK 12 on 74HC595
#define SRCLK_Pin 10 //CLOCK 11 on 74HC595
#define NUM_REGISTERS 3 //how many registers are in the chain
//initaize shifter using the Shifter library
Shifter shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS);

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

const int ButtonPinUp = 2;
int ButtonPinUpState = 0;
const int ButtonPinDn = 3;
int ButtonPinDnState = 0;
const int MuteButtonPin = 5;
int MuteButtonPinState = 0;
const int AuxButtonPin = 4;
int AuxButtonPinState = 0;
const int fbutton = 6;
int RelaySource = 1;
int RelaySourceDigi = 1;
int RelayRec = 1;
int RecDigi = 1;
int Mute = 0;
int Mode = 0;
int Aux = 1;
int state = 0;
int old = 0;
int ButtonPoll = 0;

byte opt[8] = {
  0b00000,
  0b01110,
  0b11011,
  0b10001,
  0b10001,
  0b10001,
  0b11111,
  0b00000
};

byte coax[8] = {
  0b00100,
  0b01110,
  0b11111,
  0b10001,
  0b10001,
  0b01110,
  0b00100,
  0b00100
};

byte mut[8] = {
  0b00001,
  0b00011,
  0b00111,
  0b11111,
  0b11111,
  0b00111,
  0b00011,
  0b00001
};

byte outp[8] = {
  B00000,
  B00100,
  B00110,
  B11111,
  B11111,
  B00110,
  B00100,
  B00000
};

byte upp[8] = {
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111
};

byte inpp[8] {
  0b10000,
  0b10000,
  0b10100,
  0b10110,
  0b11111,
  0b00110,
  0b00100,
  0b00000
};

byte ann[8] {

  0b11111,
  0b10001,
  0b10101,
  0b10101,
  0b10001,
  0b10101,
  0b10101,
  0b11111
};

byte dnn[8] = {
  0b11111,
  0b10011,
  0b10101,
  0b10101,
  0b10101,
  0b10101,
  0b10011,
  0b11111
};

byte too[8] = {
  0b00000,
  0b00100,
  0b00110,
  0b11111,
  0b00110,
  0b00100,
  0b00000,
  0b00000
};

void printAtCursor(int a, int b, const char* c)
{
  lcd.setCursor(a, b);
  lcd.print(c);
}

void setup() {
  lcd.begin(20, 4);
  lcd.backlight();

  byte* list[] = {outp, coax, mut, opt, upp, inpp, ann, dnn, too };
  for (int n = 0; n < 9; n++)
  {
    lcd.createChar(n + 1, list[n]);
  }

  pinMode(fbutton, INPUT);
  pinMode(ButtonPinUp, INPUT);
  pinMode(MuteButtonPin, INPUT);
  pinMode(ButtonPinDn, INPUT);
  pinMode(AuxButtonPin, INPUT);

  for (int n = 11; n < 14; n++)
  {
    pinMode(n, OUTPUT);
  }

  printAtCursor(3, 0, "Digital/Analog");
  printAtCursor(3, 1, "Audio Selector");
  printAtCursor(4, 2, "Built-In DAC");
  printAtCursor(2, 3, "V2.0f (23052020)");
  delay(4000);
  lcd.clear();
}

void setPin(int first, int last, int pin)
{
  for (int n = first; n < last + 1; n++)
  {
    shifter.setPin(n, pin == n ? HIGH : LOW);
  }

  shifter.write();
}

void setLines(int a, int b, const char* t, int x = -1, const char* u = "")
{
    lcd.setCursor(0, a);
    lcd.write(b);
    lcd.setCursor(2, a);
    lcd.print(t);
    if (x != -1)
    {
      lcd.write(x);
      lcd.print(u);
    }
}

void loop()
{
  // shifter.clear(); //set all pins on the shift register chain to LOW
  shifter.write(); //send changes to the chain and display them
  //check button states
  ButtonPinUpState = digitalRead(ButtonPinUp);
  ButtonPinDnState = digitalRead(ButtonPinDn);
  MuteButtonPinState = digitalRead(MuteButtonPin);
  AuxButtonPinState = digitalRead(AuxButtonPin);
  ButtonPoll = digitalRead(fbutton);

  if (AuxButtonPinState == HIGH && RelaySource == 1 && state == 1) {
    lcd.clear();
    Aux           = ~Aux;
    digitalWrite(13, Aux == 0 ? LOW : HIGH);
  }

  if (ButtonPoll == HIGH) {
    state = old + 1;
  }

  lcd.clear(); // Happens in all cases
  switch (state) {
    case 1: // Fall through
    case 2: // Fall through
    case 3: // Fall through
    case 4:
      lcd.setCursor(1, state - 1);
      lcd.write(5);
      old = state;
      break;

    default:
      old = 0;
      break;
  }

  // Assuming state = 1..4
  if (ButtonPinUpState == HIGH)
  {
    lcd.clear();
    int* t = NULL;
    int maxValue = -1;

    switch (state)
    {
      case 1: t = &RelaySource;     maxValue = 8; break;
      case 2: t = &RelayRec;        maxValue = 5; break;
      case 3: t = &RelaySourceDigi; maxValue = 8; break;
      case 4: t = &RecDigi;         maxValue = 4; break;
      default: break;
    }

    *t = min(1, max(maxValue, *t + (ButtonPinUpState == HIGH ? 1 : 0) + (ButtonPinDnState == HIGH ? -1 : 0)));
  }

  if (MuteButtonPinState == HIGH) {
    lcd.clear();
    Mute = (Mute == 0 ? 1 : 0);
    digitalWrite(12, Mute == 0 ? HIGH : LOW);
  }

  // RelaySource
  setPin(0, 7, RelaySource - 1);
  if (RelaySource == 1 && Aux == 0)
  {
    setLines(0, 7, "D", 9, "A:");
  }
  else
  {
    const char* rs1[] = { "Line 1", "Line 2", "CD 1", "CD 2", "Tape 1", "Tape 2/DCC", "Tape 3/DAT", "MD", "MD" };
    setLines(0, 7, rs1[RelaySource - 1]);
  }

  if (RelaySource == 8)
  {
    shifter.setPin(0, LOW); //set pin 1 in the chain(second pin) HIGH
  }

  // RelayRec
  int         rr1[] = { 8      , -1   , 9       , 10      , 11       };
  const char* rr2[] = {"Source", "OFF", "Tape 1", "Tape 2", "Tape 3" };
  const int   rr3[] = { -1     , -1   , 9       , 9       , 9        };
  const char* rr4[] = { ""     , ""   , "2,3"   , "1,3"   , "1,2"    };

  setPin(8, 11, rr1[RelayRec - 1]);
  setLines(1, 6, rr2[RelayRec - 1], rr3[RelayRec - 1], rr4[RelayRec - 1]);

  // RelaySourceDigi
  setPin(16, 23, 17 - RelaySourceDigi);
  if (RelaySource == 1 && Aux == 0)
  {
    lcd.setCursor(7, 0);
    const char* t[] = { "Optical 1", "Optical 2", "Optical 3", "Optical 4", "Coaxial 1", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
    lcd.print(t[RelaySource - 1]);
  }

  const char* t1[] = { "Sony 5-CD", "Sony MD[", "Optical 3", "Optical 4", "Philips CD-R [", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
  const int   t2[] = { 4          , 4         , -1         , -1         , 2               , -1        , -1         , -1          };
  const char* t3[] = { "]"        , "]"       , ""         , ""         , "]"             , ""        , ""         , ""          };
  setLines(2, 8, t1[RelaySourceDigi - 1], t2[RelaySourceDigi - 1], t3[RelaySourceDigi - 2]);

  // RecDigi
  const char* t[] = { "Optical Out1", "Optical Out 2", "Coaxial Out 1", "Coaxial Out2" };
  setPin(12, 15, 11 + RecDigi);
  setLines(3, 6, t[RecDigi - 1]);

  delay(150);
}

Update

I wanted for myself to see how to clean it fully, so I tried below.

Still check for copy/paste problems, as I didn't execute the sketch (but it compiles without warnings).

Original sketch: 2746 bytes (8%) program storage space, 142 bytes (6%) of dynamic memory
Sketch below   : 1546 bytes (4%) program storage space,  40 bytes (2%) of dynamic memory.

Conclusion:

25% less program storage space used
67% less dynamic memory used
Less lines of code
Better readability
Better maintainability
No (or less) code duplication
Smaller function complexity
Less statements (added more to initialization)

Code:

//Libraries
#include "LCD.h"
#include "LiquidCrystal_I2C.h"
#include "Shifter.h"

const uint8_t SER_Pin = 8; //SER_IN 14 on 74HC595
const uint8_t RCLK_Pin = 9; //L_CLOCK 12 on 74HC595
const uint8_t SRCLK_Pin = 10; //CLOCK 11 on 74HC595
const uint8_t NUM_REGISTERS = 3; //how many registers are in the chain

Shifter _shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS);
LiquidCrystal_I2C _lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

enum EMode
{
  RELAY_SOURCE,
  RELAY_REC,
  RELAY_SOURCE_DIGI,
  REC_DIGI,
  LAST_MODE
};

static const uint8_t _buttonPinUp = 2;
bool _buttonPinUpState = false;
static const uint8_t _buttonPinDown = 3;
bool _buttonPinDownState = false;
static const uint8_t _muteButtonPin = 5;
bool _muteButtonPinState = false;
static const uint8_t _auxButtonPin = 4;
bool _auxButtonPinState = false;
static const uint8_t _forwardButton = 6;
uint8_t _relaySource = 0;
uint8_t _relaySourceDigi = 0;
uint8_t _relayRec = 0;
uint8_t _recDigi = 0;
bool _mute = false;
bool _aux = true;
EMode _mode = RELAY_SOURCE;
bool _buttonPoll = false;

static const byte OPT[8]  PROGMEM = {  0b00000,  0b01110,  0b11011,  0b10001,  0b10001,  0b10001,  0b11111,  0b00000 };
static const byte COAX[8] PROGMEM = {  0b00100,  0b01110,  0b11111,  0b10001,  0b10001,  0b01110,  0b00100,  0b00100 };
static const byte MUT[8]  PROGMEM = {  0b00001,  0b00011,  0b00111,  0b11111,  0b11111,  0b00111,  0b00011,  0b00001 };
static const byte OUTP[8] PROGMEM = {  B00000 ,  B00100 ,  B00110 ,  B11111 ,  B11111 ,  B00110 ,  B00100 ,  B00000  };
static const byte UPP[8]  PROGMEM = {  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111 };
static const byte INPP[8] PROGMEM = {  0b10000,  0b10000,  0b10100,  0b10110,  0b11111,  0b00110,  0b00100,  0b00000 };
static const byte ANN[8]  PROGMEM = {  0b11111,  0b10001,  0b10101,  0b10101,  0b10001,  0b10101,  0b10101,  0b11111 };
static const byte DNN[8]  PROGMEM = {  0b11111,  0b10011,  0b10101,  0b10101,  0b10101,  0b10101,  0b10011,  0b11111 };
static const byte TOO[8]  PROGMEM = {  0b00000,  0b00100,  0b00110,  0b11111,  0b00110,  0b00100,  0b00000,  0b00000 };

static const byte* const CHAR_LIST[] PROGMEM = {OUTP, COAX, MUT, OPT, UPP, INPP, ANN, DNN, TOO };
static const uint8_t PINS[] PROGMEM = { _forwardButton, _buttonPinUp, _muteButtonPin, _buttonPinDown, _auxButtonPin };

static uint8_t* const    MODE_VALUES[] PROGMEM = { &_relaySource, &_relayRec, &_relaySourceDigi, &_recDigi };
static const uint8_t     MAX_VALUES[] PROGMEM = { 7             , 4         , 7                , 3         };

static const char* const RELAY_SOURCES[] PROGMEM = { "Line 1", "Line 2", "CD 1", "CD 2", "Tape 1", "Tape 2/DCC", "Tape 3/DAT", "MD", "MD" };

static const char* const RELAY_SOURCE_DIGI_1[] PROGMEM = { "Sony 5-CD", "Sony MD[", "Optical 3", "Optical 4", "Philips CD-R [", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
static const int         RELAY_SOURCE_DIGI_2[]         = { 4          , 4         , -1         , -1         , 2               , -1        , -1         , -1          };
static const char* const RELAY_SOURCE_DIGI_3[] PROGMEM = { "]"        , "]"       , ""         , ""         , "]"             , ""        , ""         , ""          };

static const int         RELAY_REC_1[] PROGMEM = { 8      , -1   , 9       , 10      , 11       };
static const char* const RELAY_REC_2[] PROGMEM = {"Source", "OFF", "Tape 1", "Tape 2", "Tape 3" };
static const int         RELAY_REC_3[] PROGMEM = { -1     , -1   , 9       , 9       , 9        };
static const char* const RELAY_REC_4[] PROGMEM = { ""     , ""   , "2,3"   , "1,3"   , "1,2"    };

static const char* const DIGI_RELAY_SOURCES[] PROGMEM = { "Optical 1", "Optical 2", "Optical 3", "Optical 4", "Coaxial 1", "Coaxial 2", "Coaxial 3", "Coaxial 4" };

void printAtCursor(int a, int b, const char* c)
{
  _lcd.setCursor(a, b);
  _lcd.print(c);
}

void setup()
{
  _lcd.begin(20, 4);
  _lcd.backlight();

  for (int n = 0; n < 9; n++)
  {
    _lcd.createChar(n + 1, (byte*) CHAR_LIST[n]);
  }

  for (int n = 0; n < sizeof(PINS) / sizeof(uint8_t); n++)
  {
    pinMode(PINS[n], INPUT);
  }

  for (int n = 11; n < 14; n++)
  {
    pinMode(n, OUTPUT);
  }

  printAtCursor(3, 0, "Digital/Analog");
  printAtCursor(3, 1, "Audio Selector");
  printAtCursor(4, 2, "Built-In DAC");
  printAtCursor(2, 3, "V2.0f (23052020)");
  delay(4000);
}

void setPin(int first, int last, int pin)
{
  for (int n = first; n < last + 1; n++)
  {
    _shifter.setPin(n, pin == n ? HIGH : LOW);
  }

  _shifter.write();
}

void setLines(int a, int b, const char* t, int x = -1, const char* u = "")
{
    _lcd.setCursor(0, a);
    _lcd.write(b);
    _lcd.setCursor(2, a);
    _lcd.print(t);

    if (x != -1)
    {
      _lcd.write(x);
      _lcd.print(u);
    }
}

void ResetShifter()
{
  // _shifter.clear(); //set all pins on the shift register chain to LOW
  _shifter.write(); //send changes to the chain and display them
}

void ReadButtons()
{
  _buttonPinUpState = digitalRead(_buttonPinUp) == HIGH;
  _buttonPinDownState = digitalRead(_buttonPinDown) == HIGH;
  _muteButtonPinState = digitalRead(_muteButtonPin) == HIGH;
  _auxButtonPinState = digitalRead(_auxButtonPin) == HIGH;
  _buttonPoll = digitalRead(_forwardButton) == HIGH;
}

void HandleAuxButton()
{
  if (_auxButtonPinState && (_relaySource == 0) && (_mode == EMode::RELAY_SOURCE))
  {
    _aux = !_aux;
    digitalWrite(13, _aux ? HIGH : LOW);
  }
}

void HandlePollButton()
{
  if (_buttonPoll)
  {
    _mode = (EMode) ((_mode + 1) % EMode::LAST_MODE);
  }
}

void StartLcd()
{
  _lcd.clear(); // Happens in all cases
  _lcd.setCursor(1, (int) _mode);
  _lcd.write(5);
}

void HandleButtonPinUp()
{
  if (_buttonPinUpState)
  {
    static uint8_t* const modeValue = MODE_VALUES[_mode];
    static uint8_t maxValue = MAX_VALUES[_mode];
    *modeValue = min(0, max(maxValue, *modeValue + (_buttonPinUpState ? 1 : 0) + (_buttonPinDownState ? -1 : 0)));
  }
}

void HandleMuteButton()
{
  if (_muteButtonPinState)
  {
    _mute = !_mute;
    digitalWrite(12, _mute ? HIGH : LOW);
  }
}

void ProcessRelaySource()
{
  // RelaySource
  setPin(0, 7, _relaySource);
  if (_relaySource == 0 && !_aux)
  {
    setLines(0, 7, "D", 9, "A:");
  }
  else
  {
    setLines(0, 7, RELAY_SOURCES[_relaySource]);
  }

  if (_relaySource == 7)
  {
    _shifter.setPin(0, LOW); //set pin 1 in the chain(second pin) HIGH
  }
}

void ProcessRelayRec()
{
  setPin(8, 11, RELAY_REC_1[_relayRec]);
  setLines(1, 6, RELAY_REC_2[_relayRec], RELAY_REC_3[_relayRec], RELAY_REC_4[_relayRec]);
}

void ProcessRelaySourceDigi()
{
  setPin(16, 23, 17 - _relaySourceDigi);
  if (_relaySource == 0 && !_aux)
  {
    _lcd.setCursor(7, 0);
    _lcd.print(DIGI_RELAY_SOURCES[_relaySource]);
  }
  setLines(2, 8, RELAY_SOURCE_DIGI_1[_relaySourceDigi - 1], RELAY_SOURCE_DIGI_2[_relaySourceDigi - 1], RELAY_SOURCE_DIGI_3[_relaySourceDigi - 2]);
}

void ProcessRecDigi()
{
  static const char* const t[] PROGMEM = { "Optical Out1", "Optical Out 2", "Coaxial Out 1", "Coaxial Out2" };
  setPin(12, 15, 12 + _recDigi);
  setLines(3, 6, t[_recDigi]);
  delay(150);
}

void loop()
{
  ResetShifter();
  ReadButtons();

  HandleAuxButton();
  HandlePollButton();
  StartLcd();
  HandleButtonPinUp();
  HandleMuteButton();

  ProcessRelaySource();
  ProcessRelayRec();
  ProcessRelaySourceDigi();
  ProcessRecDigi();
}


How many sensors can an ARDUINO UNO support?

A arduino can theoretically use more sensors than it has bits of storage based on your lowlever programming and algorithmic skills.
however since most people tend to only use one connection per arduino pin and mostly basic c++ and arduino instructions this is a lot lower. some people also use a shift register to easily increase the port amount.
for your project it depends you can use your ir sensors using one pin each for most ir sensors. the load sensor can be used on a single analog pin if you make it yourself, most prebought ones support ic2 which is really great for your case as I will describe later however you might not need it. hall effect sensor needs one I/O pin, rfid shield seems to use around 5 I/O pins for the average module, and the motor shield you plan to use the lose module which controls 2 motors uses up to 6 I/O pins, the arduino shield might contain more than  L293D motor driver so it might use up more pins, also you should make sure the specific shield edition supports connecting pins to the unused I/O you often have to solder those connections yourself.
so assuming you use all I/O connections and no ic2 where you use one  L293D motor driver board and not a shield(or a shield with pin redirection you should need around:
14 I/O pins from which 1 to a max of 3 are Analog pins(the load and ir ones might be analog based on the type).
however you should check the ports and layout of your actual hardware since this all can differ based on what types you use.
might some of tour sensors use ic2(they have a sda and scl pin) than you need 2 pins on your arduino for all of them together as long as they don't have matching id's. see i2c like a computer network.
so you should be able to use it without a shift register since a arduino uno has 18 basic I/O pins assuming you don't use pin 1 and pin 2 due to the interference with the serial port. 6 of those 18 pins are analog ones. analog pins can be used like normal digital pins. if you use i2c you should also take 2 pins of so you would have 16 usable pins when you use i2c and serial. you can theoretically use 20 pins, but I would recommend not using pin 0 and 1 as for they can prevent your board from accepting a new scetch upload which might require more difficult ways of uploading and problems when using serial connection.


This error means, that there is library overlapping on a vectors. To solve this error, you need to modify your Library file :

STEPS :

Remove the Softserial Library
Download AltSoftSerial library
if you have shield then you need to replace AltSoftSerial in place of SoftwareSerial in both .cpp as well as .h files.
Import AltSoftSerial library in place of SoftwareSerial in the sketch.

Execute .


Thermistor value correct on Uno backwards on Nano

There is no "correct" way. The thermistor and the resistor combine to make a voltage divider. Whether the thermistor is connected to +5V (AKA R1) or to GND (AKA R2) determines the formula to use to calculate the resistance.

The general form is:

          R2
Vout = ------- x Vin
       R1 + R2

To solve for R2 (thermistor connected to GND) you re-arrange to:

                 1
R2 = R1 x --------------
          (Vin/Vout) - 1

To solve for R1 (thermistor connected to +5V) it's:

     R2 x Vin
R1 = -------- - R2
       Vout

Vin, of course, is 5V, and Vout is a voltage you calculate from the analog reading on the Arduino.

Once you have the resistance you can then calculate the temperature. That part doesn't change regardless of the orientation of the thermistor.


As Juraj already explained, you cannot use Serial.read() outside a function.

What you probably want is to call it within the loop, or a function called from loop (via other functions).
Than you can call also turnMotor from Loop or a function called from loop. The value (int serial_input) probably doesn't have to be global anymore, but that depends on the time where you assign the value and where you call turnMotor.


Arduino can't write MPU6050 data to SD card

You seem to be expecting a statement of the form

idx ;

to increment a variable, but it will not, so your idx and count variables are forever 0 and you keep trying to re-open the same file without ever closing it.

To increment a variable, use the ++ operator as in

idx++;

count++;


Is SoftwareSerial left out for the ATTiny85/84?

Short answer - no. It's not left out, on the contrary.

But before addressing to the compiler error you mentioned, a small clarification:

  I downloaded the hardware from https://code.google.com/p/arduino-tiny/

The link you provided is not hardware, but software called the ATtiny core files. It contains the necessary files that will help you compile and upload code from Arduino IDE to the ATtiny (even when using ArduinoISP as programmer).

The SoftwareSerial is a library that comes with the Arduino IDE zip/installation. If you have downloaded the latest version of Arduino IDE from the Arduino Website, you should be able to find the SoftwareSerial library files located at:

[Path to Arduino installation folder]\libraries\SoftwareSerial

Example for SoftwareSerial library files you should expect to find there are SoftwareSerial.cpp and SoftwareSerial.h.

  fatal error: SoftwareSerial.h: No such file or directory

The compiler error you receive seems to imply that the compiler cannot find the header file (SoftwareSerial.h) for SoftwareSerial library. This indeed seems quite odd, since this library does not require any special installation, and as mentioned, is part of the libraries that are built into the Arduino IDE installation.

So, to mitigate this, I would recommend that you will:

Make sure the library folder exists in the location mentioned above
If it doesn't, then you should probably re-download the Arduino IDE installation, and after that install the ATtiny core files as per the instructions (important!). Installation instructions are located in the README file inside the ATTiny core zip file
(tiny\avr\README).
If it does exist, and you still get this compiler error, then you must have a corrupted installation (perhaps the compiler include folders is messed up). I would still recommend following the re-installation as mentioned in the previous bullet.
Make sure that you can find the ATtiny 85 in the board list, at Tools->Board and that it is selected.
Another angle that might shed more light on this error, would be to turn on the verbose output for the compiler (you can do it in the Arduino IDE, by choosing File->Preferences-> "Show verbose output during" and checking "compilation"). Verbose output can help you track down any compiler command line errors, like missing include folders.
Last but not least, if the SoftwareSerial folder exist, you could use the Arduino IDE to check if the IDE can identify its existance, by going to Sketch->Import Library, and looking for SoftwareSerial. If it's not there, then the folder is not located properly under the 'libraries', verify the path as mentioned above (did you move it?)

Finally, when you will be able to compile your code, try using the SoftwareSerial example that comes with the library to check it. Note that it is not going to work 'out-of-the-box' as with the Arduino Uno; The ATtiny does not have the same FTDI hardware for communicating directly with USB, so for sending and receiving serial messages using the ATtiny you will have to either use the Arduino Uno as a proxy (using the Uno's pins 0 & 1) or to use dedicated USB to Serial hardware similar to this one.

  Switching the board to UNO makes the problem go away

As a side note, switching to the Uno will make most ATtiny problems 'go away' since the Uno is much more equipped than ATtiny85/4, both on the MCU level and on the breakout board level, which you get with the Uno (and which you don't get when working directly with a chip like ATtiny). Also, most of the code base out there is targeting the Uno and not ATTiny.
So if you are doing your first steps with the ATtiny, be prepared that many things that 'just worked' with the Uno will require extra/different code before they could work with the ATtiny (and some won't work at all).

You can use my simple Analog to Serial code :

/*
Takes an input on the AtTiny85 from the VERY TRICKY analogue input pin 2 (as labeled in HLT tutorial)
 and outputs these with Software serial to the arduino uno, or Duemillanove
 Hookup
 ATTINY85 pin 3 -> Arduino Uno pin 0
 ATTINY85 pin 4 -> Arduino Uno pin 1

http://www.instructables.com/id/Easy-ATTiny-Serial-Communication-with-Tiny-AVR-Pro/
 */

#include <SoftwareSerial.h>
// Definitions
#define rxPin 4
#define txPin 3
SoftwareSerial mySerial(rxPin, txPin);
int sensorPin = 7; //ACTUALLY PIN LABELED AS "2" on the HLT tutorial
int sensorVal = -1;

// the setup routine runs once when you press reset:
void setup() {
  pinMode(sensorPin, INPUT);
  mySerial.begin(9600);
analogWrite(0,1); // This is kind a heart beat to show the ATTINY is "alive"
}

// the loop routine runs over and over asensorpingain forever:
void loop() {
  sensorVal = analogRead(sensorPin);
  mySerial.print("Input Val: ");
  mySerial.print(sensorVal);
  mySerial.println();
}


How to disable Arduino Yun to work as Access Point and set it to work as needed?

Yun expects wifi to be working and, if it's not, it will reboot itself after 60 seconds and return in access point mode.

In order to disable this check, edit file /etc/rc.local and turn wifi-live-or-reset into #wifi-live-or-reset (with a starting #).

Once done, use LuCI (the advanced configuration panel) to configure network interfaces.


EEPROM can only store the values 0-255 in any one address. That's the maximum range of an 8-bit value, and EEPROM "cells" are 8-bit in size.
You will have to split your value up into multiple 8-bit chunks and store each chunk at a different address - for example for 32-bit values you can use:
uint32_t val = 77880; // In hex is 0x13038
int addr = 0;
EEPROM.write(addr, val & 0xFF); // Stores 0x38 in address 0
EEPROM.write(addr + 1, (val >> 8) & 0xFF); // Stores 0x30 in address 1
EEPROM.write(addr + 2, (val >> 16) & 0xFF); // Stores 0x01 in address 2
EEPROM.write(addr + 3, (val >> 24) & 0xFF); // Stores 0x00 in address 3

Then to read you do the opposite and shift the values and OR them:
uint32_t val = (uint32_t)EEPROM.read(addr) |
               ((uint32_t)EEPROM.read(addr + 1) << 8) |
               ((uint32_t)EEPROM.read(addr + 2) << 16) |
               ((uint32_t)EEPROM.read(addr + 3) << 24);

Alternatively the EEPROM library has a "store anything" helper to do it for you:
EEPROM.put(addr, val);

That will store the variable val across enough cells to fit it (4 in the case of a 32-bit variable), so you must know not to write to the other cells used by it (0, 1, 2 and 3 in this case) or you will corrupt your data.
You recall it with:
EEPROM.get(addr, val);


Can I control relays through an Arduino while using USB joystick?

Afaik USB on an Arduino is not really easy to accomplish. The USB is normally only usable for uploading a sketch and trace (RS232) data. Not to be used as a specific USB device. There are people who upload special firmware to have the Arduino used as USB device but this is not something for a beginner.

A camera with an Arduino is quite impossible, especially if you want to process the data from that camera on a microcontroller. You might take a look at a Raspberry Pi instead, afaik it also has a HDMI output.


I found out the issue I was having, though I have a Gemma.

What worked for me:

Selecting the correct board under "Tools" -> "Board:" (in your case, the Adafruit Feather 32u4 is probably the one you want)
Selecting the "USBtinyISP" under "Tools" -> "Programmer:"

Then it was able to upload to the Gemma, after hitting it's reset button twice to get it into a 'programming mode' (I don't know if the feather has such a feature).

If you are still having problems make sure that you have properly set up your arduino IDE for adafruit boards, and just play around with settings (try different programmers).

I don't know why it was so hard finding this info out, and why it is not more visible on the documentation to set these things up. I think I found out the 'hitting reset twice' thing somewhere buried in a forum... I digress, but Adafruit does need to consolidate their documentation to make it clearer.

Hope this helps


Can I connect an Arduino wifi module directly to my android phone?

A phone running in wifi tethering (mobile hotspot) mode is no different to a wifi access point or router. So yes, you can use that.

Chances are though that you will need a mobile internet connection in order to activate mobile hotspot mode in the first place.


What will use less memory, an array or if ... else?

As Ignacio says, if the compiled size is the same both ways, look for something else.  (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)

When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the if method, so there are tradeoffs.

You can replace the clunky if statement and its two lcd.prints  with the following:

      lcd.print(hour>12? "am" : "pm");

Note that that line retains the two bugs that your if statement has, but it produces them more compactly. :) [One error is that your if statement prints pm for hours 0 through 12 and am for hours 13 through 23.  Another error is that it prints zeroes instead of twelves for the hours after midnight and noon.  More properly, a program should print like 12:xx am during hour 0 of the day, and like 12:xx pm, 1:xx pm, ... 11:xx pm during hours 12 through 23.]

Also note that as Gerben mentions, moving the "am" and "pm" strings into program memory via

lcd.print(hour>12? F("am") : F("pm"));

saves 6 bytes of RAM.  However, that improvement in RAM usage is offset by 74 additional bytes of program space! The following saves 6 bytes of RAM while increasing program size by only 12 bytes so may be preferable:

lcd.print(hour>12? 'p' : 'a');
lcd.print('m');

The following lines of C can replace much of the code you showed.  However, the printf library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some printf functions.  It replaces the lines from if (hour>12) { hr = hour - 12; } ... to the end with

enum { bufsize=8 };
char buf[bufsize];
snprintf (buf, bufsize, "%02:02%cm", hour%12, minute, hour>12? 'p' : 'a');
lcd.print(buf);


Using MCP23017 with 5 rotary encoders, WITHOUT missing a single step from any of them?

Interrupts don't mean that you can do lots of things at the same time. All they mean is that something can be responded to rapidly, as long as nothing else is being responded to of an equal or higher priority.
And coupling that with an IO expander which will inevitably slow things down means that you really can't do what you are trying to do.
If you want to respond instantly to every single pulse of every single encoder then each encoder has to be attached to something that can itself respond to those pulses.
I would be inclined to have a small microcontroller attached to each individual encoder (or maybe two encoders if you have enough interrupt pins) and deal with each separately - that way one encoder cannot interfere with any other. The small MCU can then keep track of position or count (depending on what it is you are trying to do) and you communicate that to a "master" controller (the Arduino for example) over some other bus, asynchronously to the encoder's pulses.
If you want more rapid response to the encoder movements then it could be possible to implement your own interrupt signal from the small MCU to the Arduino to say "My encoder has been moved", at which point the Arduino can collect the data. It won't matter how long that takes to happen as the small MCU will be keeping track of any other changes. The ATTiny85 using Pin Change Interrupts could be a good low-cost choice for this.


Is an Ultrasonic Sensor or Infrared Sensor better for measuring distance (to/from a human body)?

That depends on your requirements. An IR distance sensor will work better with different materials, since IR light is mostly reflected in very broad angles (expect for very reflective materials, like mirrors), so that uneven surfaces are also detected. But you will get a significantly worse error margin in your 50cm range. Normal IR distance sensors are just an LED and an IR photo transistor, sometime with some extra components. So the LED is lighting up and the photo transistor is measuring, how much of the IR light is coming back. The IR sensor depends also on the reflectiveness of the materials and the level of surounding IR light.
But as you don't really need to measure the distance, but just want to know, if there is an object in the range, an IR sensor might be enough. You would need to change the threshold of your IR sensor according to your needs (by experimenting with it).
All in all I think, yes, an IR sensor can give you better results for your application, though not for really measuring the distance, but only for the presence in a range with rather big error margin.


ATtiny85: Power consumption vs clock speed

The datasheet shows that current decreases at lower frequencies. Around 1 mA at 1 MHz running at 5 V. More like 5 mA at 8 MHz running at 5 V.

You can save quite a bit by using lower voltages as well, as you can see. For really big savings use a sleep mode. Read about Power saving techniques for microprocessors.

(Edited to add)

To amplify on my remarks, you should be able to get 200 nA consumption at 3.5 V in sleep mode with no watchdog timer. That will still respond to interrupts, such as closing a switch.

If you need to do things periodically you can enable the watchdog, and then get around 5 µA consumption at 3.5 V.

This is so much less current than the 1 mA mentioned above, that it is well worth exploring running in power-down mode, where possible.


Pros and Cons of using a non-pointer class object

In this situation, where you are just working with globals, the static declaration is preferred, although it makes little difference.

The static declaration (MyClass mc2) will reserve space in the BSS. The dynamic allocation (mc1 = new MyClass()) will allocate space on the heap at run time at the start of your sketch. Both are in pretty much the same area of RAM (the heap is directly above the static data area).

The only trouble starts to come when you want to free (delete) the object created with new. That can, over time, make a complete swiss-cheese mess of your heap which can cause memory allocation problems.

For that reason the dynamic method is shunned, but if all you ever do is allocate at the start and never deallocate then there is little practical difference between the two methods.


Does Nano not get sufficient power via USB?

I have a few clones but have not seen this behaviour so I guess it could be one of three things (in order of most likely to least):

They have a fault related to taking power from the USB connector.
The USB lead is not able to supply enough power ie. it is cheap and extremely thin and cannot carry much current. Have you already tried other cables?
Your USB port cannot supply enough power. Given that the spec says 500mA from a USB 2 port, this seems unlikely unless the port is faulty. Have you tried other ports / another PC?


split reading sensors values from stream after it via xbee

Try a communication protocol with a , as a delimiter like:

messageId,data1,data2,data3,....,dataN\n

And use the Messenger library to parse it.

See my answer on comms protocols here:

Communication Protocol Best Practices and Patterns

An how to use the Messenger library here:

Send Processing color data into Arduino


Notifications in constant loop (Blynk) trying to trigger along with serial function

Your code:

timer.setInterval(16000L,notifyOnButtonPress);

Is calling this function every 16s.

This code:

if (floatLevelLow && floatLevelLow != floatSavedState) {

needs some parentheses to force your desired order-of-operations. As it stands now, you are asking the result of floatLevelLow && floatLevelLow and comparing if that is not equal to floatSavedState. That's likely not what you want.

Did you mean:

if (floatLevelLow && (floatLevelLow != floatSavedState)) {

EDIT:

Also, your if/else is missing brackets around the 2nd clause and should be:

} else if (floatLevelLow != floatSavedState) {
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
}


How to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?

The Arduino Stream/Print classes may sometime need some extra attention.

BTLEserial.println(gps.location.lat()`, 6);

The member function is available in the class Print but gets "hidden". You can help the compiler to find it with a prefix:

BTLEserial.Print::println(gps.location.lat()`, 6);

Cheers!


Not able to add JSON data to Arduino data

Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).

Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".

E.g.:

float diff = abs(TPS - TPS_Json);
if (diff < 0.5) {
    // do something
}


Arduino Nano not visible in Serial Ports (Mac OS)

Is it an original Nano or a clone?

The original Nano uses FTDI's FT232 ship, whereas clones use the CG340 USB-to-TTL chip. The former works fine straight away Mac OS Sierra, whereas the latter needs a driver.

The CG340 driver doesn't work under Mac OS Sierra. Fortunately, someone patched the driver and made it available at GitHub. There you'll also find some troubleshooting instructions that can help (hopefully).

From Adrian Mihalko's repository at GitHub:

ch340g-ch34g-ch34x-mac-os-x-driver

Latest macOS Sierra-compatible driver for devices using the CH340G, CH34G or CH34X chipset. This chipset is used in several Arduino-clones.

Introduction

Version 1.3 (2016-09-27) of the OEM driver for the CH34x chipset currently causes a kernel panic (a.k.a. crash) when installed on macOS Sierra. To resolve this issue, please download and install the driver in this repo.

Installation

Remove the old driver by issuing one of the following commands (depending on your installation):

sudo rm -rf /System/Library/Extensions/usb.kext
sudo rm -rf /Library/Extensions/usbserial.kext

Restart your Mac.
Double-click on the CH34x_Install_V1.3.pkg file.
Restart your Mac.
Plug in your device. It should now be listed under the /dev directory. Examples:

/dev/cu.wchusbserial1410
/dev/cu.wchusbserial1420

Troubleshooting

If, and only if, the device is not recognized after the installation (or you cannot install the driver), please disable System Integrity Protection:

Reboot your Mac into Recovery Mode by restarting your computer and holding down Command+R until the Apple logo appears on screen.
Open the Terminal (Applications > Utilities > Terminal).
In the Terminal window, type in csrutil enable --without kext (or to fully disable: csrutil disable) and press Enter.
Restart your Mac.

Please share this page!

Regards,
Adrian Mihalko


Get more PCINT capable pins on Mega 2560

The Atmega2560 has a total of 24 pins associated to the PinChange interrupt. You cannot change that. It is an internal property of the microcontroller.
As you already have seen yourself, you need to use extra chips to extent the available IO pins. There are different options to consider:

IO-Port-Expanders (available for I2C or SPI) (for example the PCF8574. Don't know, if that is the best, just the port expander, that I also used myself)
Shift-In (for inputs) or Shift-Out (for outputs) registers (often used are the 74HC595 (Shift-out register) and the 75HC165 (Shift-In register). I often used this tutorial as reference)

As you don't want to poll these chips all the time, I suggest, that you use one, which provides an additional interrupt pin. That pin will change its value, when one of the input changes. You could then connect this pin to one of the interrupt pins of the Atmega2560. When the interrupt triggers, you can read the states of the input pins.

But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.

Indeed that wouldn't be good. So you should divide the pins up by their purpose, not by their association to a player. For example all end stop inputs, or all outputs for the stepper motors. Then you need to access, what timing requirements each group has. Then you can take the group with the lowest requirements and check, if and which chip would be able to handle the data fast enough. For example the "finish LED". You didn't specify, what exactly it does, but I guess, that it is not really time critical. So you could handle all finish LEDs via a single shift-out register.
Or take the inputs for the holes: I guess here you have some sensor, that triggers, when a ball passes it. Check how long the sensor get's triggered. Most likely (depending on the type of sensor) this depends on the speed of the ball. Take a speed, that you want to consider maximum (for example the pitching speed of a good baseball player, as these are really high), and calculate, how long the resulting pulse will be. The chip, that you choose, might be fast enough for this. So you could handle all ball hole inputs over extra chips (meaning chips providing extra input chips, like a Shift-In register or a port expander).

In case there's no need for the PCINT requirement, which pins can be used as an alternative?

Every pin capable of digital IO. That's nearly every pin on the Arduino Mega. Though that means, that you cannot use interrupts for them and you have to poll then constantly. That might be ok for you. It really depends on your exact timing requirements.

I thought polling was a "avoid where possible"-area?!

Yes and no. First you asked for the possibility of using other pins, so I mentioned that above. Though doing that means using no PinChange interrupt. Generally polling is bad, when

you spend too much time on it, leaving no time for other functions of the code, or
if the events, that you are polling, are too short for your polling code.

That can happen in the cases, that

you use blocking code to poll (like waiting with a while loop for a button press), which blocks all other functions from executing.
your code needs a long enough event to register it (for example the signal from your hole sensors might be very short. If your polling interval is bigger than that, you will loose some events)

If you stay inside of the confinements and use non-blocking code, there is nothing bad with polling.
Let's take the often used Bounce2 library for Arduino. It helps you with reading buttons and handles the debouncing for you. It does not use any interrupts. You are expected to call Bounce.update() often enough to catch all button presses, which is typically a few ms at max. But since the Arduino Mega runs on 16MHz, it is capable of way faster speeds than the few ms. Calling Bounce.update() often enough is easy, when you don't write code, that stays a long time to execute. So no delays, except for maybe very short ones. Instead you can use the coding style of the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses the millis() function as a time base to check repeatedly, if it is time to do something, and only do so, if it really is time for it. Much like you are baking a pizza by putting it into the oven and then regularly watch at your clock, if it is time to get the pizza out of the oven. You don't want to sit in front of the oven waiting for pizza. The analog of doing that is writing blocking code with delay().
So all in all about polling vs interrupts: It depends on your requirements. Fast response times or short events often need interrupts, though you need to cope with limited usable pin numbers and different interrupts (which is a bit more complex to code). Polling - when done right - can give you big freedom and rather easy handling, while saving interrupt sources for more important functions. Though it poses bigger limits on response times and the duration of events. Also it depends strictly on the rest of your code.

Note, that in the above, terms like "time critical", "fast response times" and such are more meant for the region of a low number of microseconds. Timings in the millisecond range can easily be done by using the mentioned non-blocking coding style (either with millis(), or for greater resolution and accuracy at low numbers of milliseconds micros()). The principle is always the same and there are tons of tutorials about it on the web and even many questions and answers on this site. So you can google for this, to get a more detailed tutorial.


The INA219 gives you the instantaneous current and voltage at a given moment in time, whereas your DMM shows you the average over a period.
The L298N is giving out a PWM waveform that is rapidly being turned on and off.
You see where this is going?
Your Arduino detection will be giving you either full power or no power (or somewhere in between owing to the low-pass filter effect of the motor), pretty much randomly, whereas the DMM will give you the average over a number of samples.
You would need to rapidly sample the PWM signal over a period of time and calculate the average to get an idea of what the current and voltage might be.


If you are giving power to nodemcu through USB cable. SD card VCC can be connected to the VIN pin of nodemcu ESP8266. I faced the same problem
NodeMCU V3 + SD Card with Arduino IDE Not working
but after connecting VCC of SD Card to VIN pin of nodemcu. it worked.
Thanks for the helping me Mr. Juraj


RC drag strip finish line with mph calculation (using 1" spaced lasers)

ONE:

What you can do is use a while loop waiting for the first pulse and then wait until the last pulse, for an idea look at this code from Gadjet, he made a chronograph with a similar operation, you would just need to adapt the design, this might not be as accurate for an 1". Also it will be the issue of having ties between cars. This is short as I don't like this option.

TWO:

Another option, although using what you don't want to use, would be using the interrupts on the Arduino. I am basing the following on the fact that you are using two cars.

What you can do is have a finish line for both vehicles and detect a break with a interrupt, one interrupt pin per lane(UNO has to interrupts).

The trick here is that you place both the outputs from one lane onto a single interrupt pin with a edge detector type of circuit1 to generate a pulse while the vehicle crosses a point, especially important as it will be in the inch area for a while. The code handles the double pulse on one pin. I know this works as I used this on a ballistic chronograph which works in microseconds detecting shots >2000fps over a 0.406 foot distance.

1 This is an example of the circuit you would use at the output of each sensor before the OR gates:

The hardware would just become a duplicate for each lane, and to combine the input on one pin you can use an OR gate IC or you can use diode OR gate:

Interrupts are actually easy to use with Arduinos, and there are a lot of examples out there.

Have a look at the below flow chart to get an idea of operation in the code:

A small thing would be that the code ignores a interrupt once the cars have passed so it doesn't calculate a second time.


How to call class A's method from class B?

In your Java version, you define MainClass like this (my comments added):

public class MainClass{ // Define a new Class
    DoClass d;          // Add a member variable to the class
    public MainClass(){
        d = new DoClass(this); // Initialise the member variable
    } // MainClass()
} // MainClass

In your C++ you don't do the same thing - but you should! The class needs a DoClass member so that you can use it in other MainClass functions:

// MainClass.h
...
#include "DoClass.h" // Need the .h here - remove it from the .cpp
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
  private:
    DoClass _d; // Create a private member variable to use
};

and

// MainClass.cpp
MainClass::MainClass() : // MainClass constructor (note colon)
           _d(*this) // Initialise member
{
} // MainClass::MainClass()

Now, you want DoClass to be able to use MainClass, so you passed it into DoClass's constructor. But DoClass cannot have a MainClass inside it - MainClass already has a DoClass inside it! Infinite impossibility! So you need DoClass to merely contain a reference to the MainClass that it sits inside. That's the C++ unary & operator (different from the binary & operator), which is used similar to the pointer * operator:

// DoClass.h
...
// Need to advise compiler MainClass exists...
// but can't #include MainClass.h! Infinite loop!
class MainClass;

class DoClass
{
public:
    DoClass(MainClass &m); // Reference to MainClass
    void callMainClassFunct();
private:
    MainClass &_m; // Reference to MainClass
};

and

// DoClass.cpp
DoClass::DoClass(MainClass &m) : // DoClass constructor - note colon
         _m(m) // Initialise member variable
{
}


Arduino Leonardo is not recognized by usb cable in Windows 8

It is highly likely that the sketch you loaded is causing this.

  However, when I press the restart button on the Arduino, the PC will detect it as an Arduino Leonardo bootloader(com 7) but after few seconds it disappears.

For a few seconds after reset the bootloader will configure the board as a USB serial device, awaiting upload of a new sketch. Once that times out it runs the existing code. If the existing code does not configure the USB port (eg. by doing Serial.begin) then it will cease to enumerate as a USB device. This is perfectly normal.

The "fix" is to upload a sketch that uses the USB interface. For example, open a serial port, open the keyboard (Keyboard.begin()) or similar.


Inorder to plot multiple variables or waveforms simultaneously a 'space' is printed between the two print statements.

Serial.print(counter);
Serial.print(" ");
time = millis();
Serial.println(time);

OR

Serial.print(counter);
Serial.print("\t");
time = millis();
Serial.println(time);


I added a mpu.resetfifo after de mpu.dmpGet.... lines.
Since then 2 different systems work for at least 5 hours and with the original interupt pin attached


How to include Vref in thermistor temperature calculation?

The formula to get the analog voltage from the ADC reading is:

    V = Vref × reading ÷ 1024

(yes, it's 1024, not 1023). The formula to get the thermistor resistance
from the measured voltage is:

    R = Rref × V ÷ (Vref − V)

where Rref is your 10 kΩ pull-up. You can combine these
two formulas in order to get the resistance directly from the ADC
reading:

    R = Rref × reading ÷ (1024 − reading)

You may notice that, while doing this simplification, Vref
cancels out. It's not an error. The readings you get with this setup are
indeed independent of your reference voltage.

Update 1: After the OP's edit, we now have a completely different
question. The question is now: how come the readings do depend on the
reference voltage that is used, whereas in theory they should not.

The answer lies most likely in the ADC calibration. If high accuracy is
a requirement, the correct formula for the measured voltage is

    V = Vref ×
(reading + Eoff) ÷ (1024 + Egain)

where Eoff and Egain are the offset error and the
gain error respectively. These errors are not knows a priori, and they
are usually neglected when the accuracy requirement is low. The
datasheet only gives constraints on how big these errors can be. The
actual values depend on the specific microcontroller and can somewhat
depend on the reference voltage. The only solution to get rid of these
errors is to calibrate your own ADC. See Response of the Arduino
ADC for an example on how this could be done.

Update 2: If I had to program this in an Arduino, I would rather
simplify the calculations as much as possible before coding:

do not compute the measured analog voltage, nor the resistance, as
they are not needed
compute instead the ratio R/Rref directly from the analog
reading
rewrite the calibration polynomial as a function of
log(R/Rref) instead of log(R) (which actually means
log(R/(1 Ω)))
optimize the evaluation of the polynomial by using
Horner's method.

With these optimizations, we get:

// Coefficients of polynomial fit of log(R/Rref) -> 1/T.
const float c0 = 3.3540165e-3;
const float c1 = 2.5416075e-4;
const float c2 = -2.5959644e-6;
const float c3 = -9.3951087e-8;

// Convert ADC reading to temperature in deg. C.
static float temperature(int reading)
{
    float R_ratio = reading / (1024.0 - reading);  // = R / Rref
    float x = log(R_ratio);
    float inverse_T = c0 + x*(c1 + x*(c2 + x*c3));
    return 1/inverse_T - 273.15;
}

void loop()
{
    int reading = analogRead(A3);
    Serial.println(temperature(reading));
    deay(500);
}


int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

1) so it

calls function digitalRead() (puts value on stack, jumps, prepare function frame - each cost some time)
calls 3 other functions (with all the same problems)
check for sanity of value
check for PWN (and eventually calls another function)
does the PIND & (0b100)
returns from function (so read stack, clear the frame, jumps, set the result)

just to obtain the same functionality

typical for library functions, that each call makes sure the environment is sane and expected each and every time it is called - in close loop you can check it onece before and then just do not broke it
translates parameter from nice arduino numbers to real addresses and bits each and every time again

2) it access the PORT D (see AVR (the processor) internal construction) and reads value of its 3. bit (which maps to the relevant pin of the chip/Arduino board

3) see following comment - it is expected length of the pulse (maybe with some safety limit)

4) _BV is for BitValue - shift 1 to position given by arg (that is macro doind 1 << IRpin) maybe more nice/readable version, compiles to the same. (the ! is ofcourse negaition)


The USB cable was too long, and hence power loss.

Sorry, I figured it out a day after I asked this question.


How to send data from ThingSpeak to ESP-8266 (Arduino) using ThingHTTP?

For sending information to/from Arduino best option is MQTT. It's lightweight and very simple to use.

While your Arduinos are using MQTT to send info and receive commands (like changing thresholds), your Web server has access to the same information in real time. You can format it and present it in any way you like, without any Arduino participation.


I need to run pthreads ...

You probably don't need to run pthreads. This sounds like an X-Y problem.

What you are probably saying is "I need to do multiple things at once" (such as flashing LEDs whilst taking ADC readings, or play sounds at the same time as moving a vehicle forwards).

You could get better answers if you described the project (X) and not your proposed solution (Y) which you think is pthreads.

I have a web page about How to do multiple things at once ... like cook bacon and eggs which goes into this sort of thing in some detail.

Some example code from that page which blinks different LEDs at different rates is:

// 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

  It's become so annoying that I'm thinking of buying a Pi.

Sure you can do that. You can buy a Mac or a Windows PC. You can buy 5 Arduinos. But if you want to learn how to do multiple things on an Arduino you can learn how to manage a "state machine" and do it all on $5 of hardware.

As an example of what can be done see this post about a retro arcade game called Toorum's Quest written by Petri Häkkinen and run on an Atmega328P (same chip as in the Arduino Uno).

Hardware and screenshots:

In his code (which I compiled using the Arduino IDE to test it) he has:

Multiple sprites on a TV screen with a resolution of 104x80 with 256 colors.
Sprites are multiplexed so you can have as many as you want on the screen.
He moves them around according to game logic
He plays music and sound effects at the same time
He reads from a game controller


How to setup Arduino Wifi Shield with Red Bear Lab BLE Shield?

The way the Arduino talks to each of the shields is by first telling the device that it wants to communicate with it, and then by exchanging information with that device. The Arduino uses 3 pins, 11, 12, and 13, to communicate to both the shields, and a 4th pin which it uses to select which of the devices it wants to use. This way the Arduino can use connect to two shields at once, by just selecting one at a time

I did some research, and found that the selection pin on the WiFi shield (which I believe is the same as yours: https://www.arduino.cc/en/Main/ArduinoWiFiShield) are pins 10 and 4; pin 4 for the SD card selection, and pin 10 for the WiFi selection. Now since pin 10 is used as a selection pin for both the WiFi shield and the BLE shield, you run into some problems: both the boards will be selected at the same time when pin 10 is used. In this case, you can use the Sparkfun go-between board you linked.

I've never used it myself, but it appears to be able to change what pin is attached where on the shield it's attached to. In this case, you want to put the WiFi shield on the bottom, then the Sparkfun go-between shield, then the BLE on the top. You want to set up the go-between shield to change pin numver 10 to another pin that's not being used (any pin but 11, 12, 13, 7, 4, or 10).

In the Arduino code you will at some point declare which pin is being used to select which board. In this case, set the WiFi selection to 10 (default), the SD card selection to 4 (default), and the BLE selection to whatever pin you changed pin 10 from with the go-between shield. This way, when you select the shield on pin 10, it will only select one shield, rather than two.


WS2812 (?) RGB LED matrix turns on white

Use a MOSFET to control the matrix power line and activate the MOSFET only a few milliseconds before turning off your LEDs: this way the few millis intercurring between power on and off control signal will not be noticeable and will reduce the current bootstrap consumption.

simulate this circuit – Schematic created using CircuitLab


esp8266 advertising AP even when flashed with custom firmware

The Espressif ESP8266 SDK is part of every Arduino sketch for the ESP8266. The SDK handles the WiFi and other basic functions of the chip.

If enabled, the SDK remembers WiFi STA and SoftAP settings and start to connect right after boot. At default it is enabled. In Arduino sketch this is controlled by WiFi.persistent(bool) and of course this setting is stored too.

To clear SoftAP settings, call WiFi.softAPdisconnect(). To only turn off SoftAP, use WiFi.setMode(WIFI_STA).


Connection bluetooth master and slave with Android

First try

if(conect.available()>0)
 {
enter=conect.read();
if(1)
{ digitalWrite(8,HIGH);
 conect.print("1");
}
 }
 }

If that works,  think about what entreda is and that exactly you're trying to do there.


How is this code working?? val3 is defined as constant

In your code, the const int val3 = 7; definition, is outside of any functions so it defines a global constant/variable (available in every part of your code).

The int val3 = 8; definition is inside your setup () function, so it acts as a local variable only within that function. This overrides the val3 constant defined outside of the setup () function. I.e. the global val3 constant and the local val3 variable inside of setup () are not the same variable, which will inevitably lead to confusion (as in your case).

It’s valid syntax but I don’t consider it good coding practice. It’s good to know why it works that way though.


Power consumption in Arithmetic Operation in Arduino UNO

The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.

The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.

Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

Addition

Test sketch

volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo += 42;
  }

Generated code

  a6:   80 91 00 01     lds r24, 0x0100
  aa:   90 91 01 01     lds r25, 0x0101
  ae:   8a 96           adiw    r24, 0x2a   ; 42
  b0:   90 93 01 01     sts 0x0101, r25
  b4:   80 93 00 01     sts 0x0100, r24
  b8:   f6 cf           rjmp    .-20        ; 0xa6 <main+0x10>

Measured consumption

I measured an average of 7.00 mA.

Multiplication

Test sketch

volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo *= 42;
  }

Generated code

  a6:   4a e2           ldi r20, 0x2A   ; 42
  a8:   20 91 00 01     lds r18, 0x0100
  ac:   30 91 01 01     lds r19, 0x0101
  b0:   42 9f           mul r20, r18
  b2:   c0 01           movw    r24, r0
  b4:   43 9f           mul r20, r19
  b6:   90 0d           add r25, r0
  b8:   11 24           eor r1, r1
  ba:   90 93 01 01     sts 0x0101, r25
  be:   80 93 00 01     sts 0x0100, r24
  c2:   f2 cf           rjmp    .-28        ; 0xa8 <main+0x12>

Measured consumption

I measured an average of 6.32 mA.

Conclusion

I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.

Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).

I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?

Update

As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.


How do i get stored Midi to Play back without the notes sounding sustained?

You need to store and send out the 'note off' messages in addition to the 'note on' messages.


Would an Arduino Uno be suitable for a simple time-based locking circuit?

It is a great occasion to use the Arduino!

There are many tutorials for the Arduino out there, so thats a good place to start. This forum is a good place to ask any Arduino related question if you need to do so.

The following contains MY OPINION

In my opinion, an Arduino Nano would be great for this project. It is really user friendly and can pretty much accomplish many things. A Pro Mini would be better, but seeing sa you're a beginner, stick with the Nano.

A good long lasting batteRY would be a simple USB power bank. It outputs 5V and has a lot of juice. For a locking circuit, a simple servo would work IF THE THINGS THAT IS IN THAT "SAFE" ISN'T 1M $$. A servo does a decent job as a lock.

Good luck!


burn arduino bootloader and compiled sketch at same time

If you program via ISP, it erases the boot loader, because you do not need it. The whole point of the boot loader is to allow programming over USB. So if you want to use the normal Arduino USB input to program, burn the bootloader and then do not use the ISP.

Note my knowledge of this dates back to older arduino ~1.0 software, it is possible modifications have been made, but the above should still be true. If you have an ISP you do not need the bootloader at all.


MPU6050 Sending Bad values for Angular Velocity

At last! I have discovered the solution.

Quick Solution for those who don't like reading: Amend the previous rollRate formula to rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. Or, if you don't want the filter, rollRate = -1 * gx / 16.4;

The problem starts with the function mpu.getRotation(&gx, &gy, &gz) which accepts int16_t types for gx, gy, and gz. Since int16_t is a 16 bit integer, it has a maximum range of -32,768...+32767. The reason this integer type is used is because the output range for the gyro is -32750...+32750, which fits nicely into the 16-bit integer's range.

The problem was that when I converted these values to a readable angular velocity (and complementarily filtered) using  rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI)); , the gx value was multiplied by -180 in part of the calculation. This means that if gx was high enough initially, it would have rolled over to -32786 and ruined the whole calculation, causing the horrible spikes in the graph.

At the same time I discovered this problem, I also realized that converting from radians to degrees was unnecessary, as the gyro output was already in units of degrees (just scaled by a sensitivity factor). After that big face-palm, I revised my rate formula to the following: rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. You will notice the scale factor has changed from 131 to 16.4. That is because the gyro range is actually +/-2000 deg/s by default, not 250 deg/s. I tried to change it back to +/-250 with mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);, but after examining the graph, it appeares that mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); does not account for this setting change, and resulted in the ypr overshooting and then leveling out to its correct value after a delay. I decided not to mess around with the quaternion container, q, and just accepted the lower sensitivity.

Like the previous image, I suggest zooming in.


Whats the best way to keep an Arduino in a waterproof junction box and prevent overheating?

The linear regulator on an Arduino works by converting excess voltage to heat. If you power it with 12V and draw a full amp from it it will turn (12-5)*1a or 7 watts of power to heat, and quickly overheat even if it's not in a box.
If you power it from 6.5V and only draw 300mA from it, it will turn (6.5-5)*.3, or a little under half-a-watt. While the Arduino is idling it will probably only draw 50mA, so less than 1/10th of a watt of heat.
For infrequent, short bursts of a few seconds you can probably get away with drawing 500mA of power without overheating.
Or skip the internal regulator and use a buck style voltage regulator. Those generate a LOT less heat.
Edit:
For a project I did recently, I used an external 5V regulated supply for everything. I cut a USB cable and soldered the red and black (+5V and ground) to the 5V supply, and plugged that into the Arudino's USB connector. That feeds 5V into the Arduino.


How to scroll data in LED dot matrix through multiple modules?

This is the function for my problem.

void draw(void)
{
uint32_t map_buffer=0;int8_t i,k;
uint8_t data_reg[4] = {0xaa,0xbb,0xff,0xff};      // random data to write
uint8_t dis_buf[4],no_device,no_col;s=0;l=3;

for (i=0;i<4;i++)
map_buffer |= data_reg[i] << i*8;                 // loading data into map_buffer

for (col=0;col<32;col++)                          // for 8 matrix columns
{
    map_buffer >>= 1;                            // start shifting the data by 1 pixel
    for (i=0;i<4;i++)
    dis_buf[i] = map_buffer >> i*8;              // loading shifted data into display buffers
    for (i=0;i<4;i++)
    {
        for (row=1;row<9;row++)                 // for 8 matrix rows
        {
            SPI_TX_m(data = (row<<8) | (dis_buf[i]),i);
        }
    }_delay_ms(1000);
}

}


How to flush the input serial buffer in Arduino?

One possible approach is to read and discard everything for a fixed time, like a second. For example:

unsigned long now = millis ();
while (millis () - now < 1000)
  Serial.read ();  // read and discard any input

I'm not a big fan of trying to "flush the input buffer". How do you know if a second is long enough? Or maybe it is too long? You are better off reading to some known delimiter.


Problems with transmission between ATtiny85 and Arduino Uno with 433MHz RF modules and Manchester

You set receivedSize to zero at instantiation, then load it with buffer[0], which also appears to be zero.  You should check that value to ensure it's correct and that it's at least 2 as 1 isn't less than. Otherwise when you go into the loop, i is 1 and receivedSize is zero (i is > receivedSize.)  So it fails to enter the loop, so no write.

uint8_t receivedSize = 0;

receivedSize = buffer[0];
for (uint8_t i = 1; i < receivedSize; i++)
     Serial.write(buffer[i]);

There may also be a logic problem. If you receive one byte, the receivedSize will be 1 and it still won't print.  Keep in mind that the array goes from 0 to limit and your 'data' lives starting in buffer[1].  Meaning if 6 characters are in the buffer only 5 (1 thru 5) will print. It may be much more clear to add the index at the position 'buffer[i + 1]' then the i can run it's normal 0 to n.


What options do I have to get 5v on my current project?

SD cards require 3.3V. Usually, to connect them to an Arduino running at 5V you need to get a level converter. However in your case it sounds like you are making work for yourself:

3.3V <--> 5V <--> 3.3V

  in order to power my sd card module, I need to input 5V

Which SD card module? Maybe you don't need a "module".


AT command not send but blue LED stays on

TX is an output. RX is an input.

By connecting TX to TX and RX to RX you have connected an output to an output, and an input to an input.

You need to connect the TXs to the other RXs.

Also: see (NEWBIE) Sending AT Command from Arduino UNO to ESP8266 doesn't work


Inserting myself in serial communication

You may be able to sniff the communication from the Raspberry Pi itself,
with no extra hardware. Assuming the program on the Pi can be configured
to use a serial port other than /dev/ttyACM0, a sniffing
program could create a pseudo-terminal pair, then forward data back and
forth between /dev/ttyACM0 and the master pseudo-terminal, while
logging everything. If you point your Pi application to the slave
pseudo-terminal, you have your man-in-the-middle logger:

Arduino --(/dev/ttyACM0)-- logger --(pseudo-tty)-- application

The interesting thing about a slave pseudo-terminal is that, as far as
the application is concerned, it behaves exactly like a regular serial
port.

There seem to be quite a few implementations if this idea. C.f. the
answers to these other stack exchange questions:

How can I monitor serial port traffic?
Sniff serial port on Linux

Just as an example, the README of
interceptty states:

  interceptty is designed to sit between a serial port (or other
  terminal device, or program, or socket, or something connected to a
  file descriptor) and a program which is communicating with that
  device, recording everything that goes back and forth between the two.
  It does this by opening the real device, creating a pseudo-tty, then
  forwarding everything between the two, recording whatever it sees.


Disassembling a RC car for a Arduino Robot

Sometimes modifying something can be harder than starting from scratch. This is probably one of those cases, but it is over all not too difficult if you have the courage.

Start with a good example, like this robot.  It will give you an idea of what hardware you must add to your RC car and how to program the Arduino.


If your IR library does not support sending signals stored in PROGMEM,
then you will have to provide the data in RAM. However, you do not have
to keep both signals in RAM permanently: only the one you are about to
send needs to be there.

I suggest you keep all the IR signal data in PROGMEM while not sending
them. Whenever you want to send a signal, you copy it to a RAM-based
buffer and give the address of that buffer to the library. The same
buffer will be reused for any signal you are sending. This will cost
you some CPU time for the copy, and save 394 bytes of RAM. The savings
will scale up if you add more signals to your sketch.

const size_t signal_size = 197;

static PROGMEM const uint16_t irSignaloff[signal_size] = { ... };

static PROGMEM const uint16_t irSignalon[signal_size] = { ... };

/* Send an IR signal from PROGMEM. */
void send_signal(const uint16_t *signal) {
    static uint16_t signal_buffer[signal_size];
    memcpy_P(signal_buffer, signal, signal_size * sizeof *signal);
    irSend.sendRaw(signal_buffer, signal_size, FREQ_KHZ, false);
}

//...
send_signal(irSignalon);
send_signal(irSignaloff);

Here I am assuming that all your signals have the same length, which is
true for the example you show, but may be false if you add more signals
later. You may then need to size the buffer as the longest of all your
signals, and provide the signal length as an extra parameter to
send_signal().

Note that the RAM buffer does not need to be static. I chose to make it
static here only in order for avr-size to give you a good estimate of
the memory requirement of the program.


The general way of doing long things triggered by an ISR is to simply set a flag insode the ISR, which then gets checked inside void loop().
volatile byte flag = 0;

void loop(){
    if(flag){
        // Do something here
        flag = 0; // reset the flag
    }
}

void receiveEvent(int howMany){
    flag = 1; // set flag, if correct data was received
}

Here keep the following in mind:

The loop() needs to run fast to react fast. Long delays are doing other long stuff there will impact the responsiveness of the code. Depending on your plans for the exact behavior, the usage of delay() is generally not good. You should look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning that rather early.

flag mus be declared volatile, to tell the compiler, that is may change at any time. Otherwise it might optimize the variable away.

flag is of type byte here. It is imprtant, that this flag only has a single byte, because reading and writing of a single byte cannot be interrupted. Multi-byte variables get read or written in multiple COU cycles, thus it would be possible, that the interrupt writes parts of the variable, while you are reading it in the main code. That would lead to garbled data. By using a single byte, you avoid using critical sections for keeping the reading in main code save. For a flag thats way simpler.


Arduino Uno programed from a Nvidia Jetson tx2

The version of the Arduino IDE contained in the Jetson repositories is buggy on the Jetson TX2 with Jetpack 3.2+ and the Arduino IDE in the repository is rather old.  Instead, try the beta related to Github Issue #7302.  This beta should work with the Jetson and other aarch64 platforms.  Many thanks to the wonderful people working to support this platform.
Steps
After downloading and unpackaging the build, perform the following steps:
#Install the OpenJDK Dependencies
sudo apt-get install openjdk-8-jre openjdk-8-jdk

#Remove the Packaged Java Folder
cd ${PATH}/arduino-PR-beta1.9-BUILD-69
sudo rm -r java

#Add armhf Architecture to Package Manager
sudo dpkg --add-architecture armhf
sudo apt-get update
sudo apt-get install libc6:armhf libstdc++6:armhf

#Install the Arduino IDE
sudo ./install.sh
sudo ./arduino-linux-setup.sh

#Reboot

Notes

The script arduino-linux-setup.sh handles the permissions for the IDE to talk to ttyACM0, updates the udev rules, and removes the pesky Modem Manger.
The armhf packages are necessay to prevent ctags from crashing.
If you are still having issues with CDC/ACM, install the module using the scripts from JetsonHacks


Can't power mg2639 cellular shield with battery

Turns out the soldered short of SJ3 was not complete.  After resoldering the shield powers up as expected.


ATtiny85 (Digispark) with 433mhz RF transmitter not working

I got it to work. The last comment of @Maximilian Gerhardt about I/O output got me thinking and I read up on it. So if I use 5V to power the ATtiny the I/O output voltage representation for 1 and 0 are significantly higher then with 3.3V. So now I underclocked the ATtiny to 8Mhz in order to use a 3.3V power supply. This way the I/O output matches the transmitters expectations. Now the communication is working.

Thanks for your help Max!


How to show one thing in the serial monitor?

You have declare flag1 and flag2 as Boolean values but then you are looking to see if they are HIGH or LOW.  Bools are either true or false.  However because of the quirks of C++ this will probably work, if High and low are 1 and 0, its just bad style.

When you have this bit of code:

if (flag2 == HIGH)
{
    delay (50);
    measure ();
}
if (flag2 == LOW)
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}

You could use an else statement instead, i.e.

if (flag2 == true) // Corrected to true
{
    delay (50);
    measure ();
}
else
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}


Why are the files not being created correctly?

When you save a file using the Save As button from the Arduino IDE, it saves the current file as a sketch i.e. as an .ino file.

To create a .cpp and .h files for working on a new library, you need to create the files alongside a sketch. For this, you can use the Tab button on the top right (circled in red).

Click on it, and select New Tab. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (test.cpp) and press Enter.

Your file has now been added to the current directory.

Similarly, follow the same steps for creating the .h file.

Once your library is complete and ready to ship, you can move the .cpp and .h files to a separate directory and then add it under libraries.


Controlling an LED using SIM900A and Arduino

Try this code.

#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}


How can I get a unique address for all my Arduino boards while in RS485?

Just assign every node a variable like "const int ID = 5" and so on and then before sending the instructions send a line terminator, the ID, line terminator and the data you need to send to the nodes. Every device listens but they all wait their ID to accept the commands. For example:

Serial.write('\n');
Serial.print(ID);
Serial.write('\n');
Serial.print(|LT2|LP3|LM5|LR4|LI6);
Serial.write('\n');

NOTE: This is the easiest way. Most likely not the most reliable or optimized.


Voltage, current measurement from solar panel using INA219 and ESP-12F

You connected the V- and V+ probes of the INA module direct to the V- and V+ of the solar panel. That means you connect V+ with V- from solar panel  over a 0.1 Ohm resistor. That is like a short. The Solar panel gets overloaded and the voltage breaks down. Lucky you, the solar panel can not provide more current. If it could, then the shunt resistor would be grilled. RIP ;-). Try put the v+ and V- in series with the LED and LED_Resistor. e.g.
Solar+ --> IN4001 --> INA+ |no connection| INA- --> LED --> R(LED) --> Solar-

That would make more sense. It'll show you how much current is drawn by the LED.
If you want to know how much current the panel can deliver, you would have to build a circuit with a potentiometer and measure the Voltage between V+ and V- of the Panel. You can also use the INA to mesasure the current through the potentiometer. Begin with a high resistancy, then turn the poti towards lower resistance and check when the voltage breaks down. The INA shows you the current. But be aware that, the max current depent on the amount of light the panel is exposed to and on the age of the panel itselves. So the values will change as these conditions change.


It is CMOS in that the IO pins of the MCU use MOSFETs not BJTs.

However I2C is slightly different in that it is open-drain not push-pull, so it's not really either TTL or CMOS since it doesn't conform to either logic level standard (since there is no "high" voltage, only what is pulled up by the external resistor). That said, since the ATMega is normally CMOS when in input or push-pull mode the logic levels of the I2C should conform to CMOS not TTL in order for the Arduino to read them properly.

It's closer to RTL than TTL or CMOS.


Why do we declare constant lat and lon value

Static variables are allocated storage only once in a program lifetime
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it and you can't change const variable's value
and i guess you know double is a data type that can save floating point numbers
that line declare two variables with names LONDON_LAT and LONDON_LON and both of them are in one line
and because london's latitiude and longtitude doesn't change the const keyword is used
also i guess because those variables are constants you can use #define visit https://www.arduino.cc/reference/en/language/structure/further-syntax/define/


There are two ways this could be tackled:

physically through connections between the xbee and arduino and read the xbee pins directly (I've never done this, and it comes down to your shield supporting it). Each of the desired output pins of the receiving xbee would be tied to a GPIO pin of the arduino. Alternatively,
serially using AT commands via the serial connection.

I have never worked with series one, but essentially:

setup a serial connection to your arduino
send the desired AT command requesting the pins value
read the serial port response

Make sure to read the manual for the series 1 xbees for the right AT commands and in how to interpret the results. Register at digi and download the datasheet.

Also, just realise reading the xbee data is going to be different depending on how you have the xbee setup, ie API vs AT mode.

Here is someone who has done some work with series 1: http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index

I'll leave the actual implementation to you since this sounds a little like a homework assignment. Give it a go using the second method above and see how you go. Then post back here (ie update the question) including source code and exact layout (schematic preferred) and we'll see where we can help you from there.

Hint: google such terms as: "read data pins xbee arduino" (without the quotes).


teensy as a keybooard throws error as keyboard input

You are calling Keyboard.println() which sends the character string followed by a new line.  If you want to emulate a keyboard you should only use Keyboard.print() which only sends the character string with no new line.


Control Air Pump Depending on Pressure Sensor

So you basically want a hysteresis control for the air pump.

const int lowerLimit;//fill in as needed
const int upperLimit;

void loop(){
    int pressure = readPressureSensor();
    if(pressure < lowerLimit) turnPumpOn();
    if(pressure > upperLimit) turnPumpOff();

}

The helper functions I used should be easy to implement based on the tutorials you found.