Serial.print prints but lcd.print does not

In the findName() function, you declare a char array of name text. Internally, text is a pointer to a block of memory 12 bytes in size.

When you return text within the findName() function, you are passing back the pointer to the block of memory. The return type of char is inconsistent with the return command. But probably more problematic is that once findName() ends, the memory set aside for the text array is marked as unused. It is no longer reserved for holding anything and may be reallocated at any time by some other function or operation.

In C/C++, array variables do not refer to the entire array, but to the first element in the array. The fact that your program works with Serial.print() is probably just good luck. lcd.print() may declare some variable or buffer which overwrites what the findName() function had put in those 12 bytes.

There are many approaches to take to resolve this. One way is to declare char arrays in the "highest" scope in which it will be used, and to declare it with the largest size that you could ever see in the operation of your program.

In your case, you can:

...
      char temp[12];
      byte who = random(1, 13); // 1 to 12
      findName(temp, who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    void findName (char *text, byte number) {
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
    }

What this does:

temp is now the char array
findName() takes the pointer to the char array, and the number as arguments
findName() modifies text, which refers to the same block of already-allocated memory as temp, and that block of memory does not go away at the end of findName().
Because findName() is not returning a value, it's return type is void.


I think the problem is because there is no delay time after your motor switch its direction, so the robot is stay on position where the switch is pressed. I don't know if this gonna work, but perhaps you can add delay after the direction changed.
But based on your code, I can't find a condition to run if no switch is pressed. For alternative, you can try this

int direction_state = 1; //state where robot moves forward

void loop(){

  /*notes that here I assume while robot moving forward,
   *the rear switch is impossible to pressed, so does while
   *robot moving backward, the front switch is impossible to
   *pressed.
   */

  while ((digitalRead (switchRear)==LOW) && (digitalRead (switchFront)==LOW))
  //no switch pressed, loop will break if any switch pressed
    {
      if (direction_state == 1) runMotorForward(); else
                                runMotorBackward();
    }

  //indicator which switch is pressed and start of 2s motor stops
  if (direction_state==1) digitalWrite(ledYellow,HIGH);
  else digitalWrite(ledGreen,HIGH);

  motorStop(); //stop the motor
  delay(2000);

  //indicator 2s motor stops finished
  if (direction_state==1) digitalWrite(ledYellow,LOW); //indicator front switch is pressed
  else digitalWrite(ledGreen,LOW);

  direction_state = -direction_state //toggle the state
  if (direction_state == 1) runMotorForward(); else
                            runMotorBackward();

  delay(2000);

}

Feel free to ask if it's not works


You are handling your buttons in completely the wrong way. You are basically saying:

  While I press this button send a constant stream of NOTE ON commands. Otherwise send a constant stream of NOTE OFF commands.

  At the same time, send more NOTE OFF commands because the other buttons aren't pressed.

So you can see it's going to be a bit of a mess.

Instead you need to detect changes in the state of a button.

For example:

void loop() {
    static bool oldButton1 = LOW;

    bool button1State = digitalRead(button1);

    if (button1State != oldButton1) { // It changed from last time
        oldButton1 = button1State; // Remember it for next time
        if (button1State) { // Pressed
            noteOn(0x90, c3, 0x64);
        } else { // Released
            noteOn(0x80, c3, 0x00); // Note: 0x80 is NOTE OFF, not 0x90.
        }
    }

    ... etc for the other buttons ...
}


Unable to add multiple potentiometer in Midi controller

Your logic is flawed here:

  int i;
  for (i = 0; i < AnaPinsNum; i++)
    potIn[i] = analogRead(pot[i]) / 8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
      }
    }

The first three lines read all three analog pins:

  int i;
  for (i = 0; i < AnaPinsNum; i++)

    potIn[i] = analogRead(pot[i]) / 8;

However then, outside the loop, you are using the value of i which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.

  int i;
  for (i = 0; i < AnaPinsNum; i++)
    {   // <------------------------------- add this
    potIn[i] = analogRead(pot[i]) / 8;

    // potentiometer could be too sensitive and
    // give different (+-1) values.
    // send CC only when the difference between last value
    // is more than 1
    if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1)
      {
      // value changed?
      if (potIn[i] != lastAnalogValue[i])
        {
        // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
        // more info: http://arduinomidilib.sourceforge.net/a00001.html
        MIDI.sendControlChange(1, potIn[i], 1);
        lastAnalogValue[i] = potIn[i];
        }  // end of not same as before
      }   // end of value changed
    }   // <----------------- add this

  If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.

If I understand your question correctly:

Change:

MIDI.sendControlChange(1, potIn[i], 1);

to:

MIDI.sendControlChange(i, potIn[i], i);


Flexibility of SoftPot Membrane Potentiometer during the use?

As you can see from this data sheet it will show you examples on how it is used. https://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf

I'd buy a curved one just to make sure, because as it bends, the 2 conductive materials will touch.


Arduino Mega 2560 from .org- which IDE works?

Arduino.org and arduino.cc have come to a agreement.
As such all incompatibilities that exist (I don't think they exist for this mega board) will be solved with next version of the Arduino IDE as if it is a board of their own.


How to load Atmega328p 8mhz board using board manager

Assuming that you have a 3.3V Atmega328P and are using an external 8MHz occilator:

In the Arduino IDE click on Tools.
Scroll down until you see an option starting with the word Board:
Select the option called Arduino Pro or Pro Mini

Click the Tools menu once again.
This time select the option starting with Processor:
Select the Atmega328P (3.3V, 8MHz)
Done!

Alternatively you can edit the boards.txt file located somewhere similar to C:\Program Files (x86)\Arduino\hardware\arduino\avr
Fuse bits can be calculated using one of these online tools:

http://www.engbedded.com/fusecalc/
http://eleccelerator.com/fusecalc/


Will the Uno bootloader work in the Duemilanove?

So I researched it a bit, and there does not seem to be any problems with running the UNO bootloader on a Duemilanove board.

The biggest difference between the two seems to be the USB interface:

USB interface

Duemilanove uses FTDI, UNO uses another microcontroller (ATmega8u2).

Since the USB to serial is transparent for me as an end user for the most parts, it doesn't really matter to me.

Leaner bootloader

The UNO bootloader is smaller than the duemilanove.


How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?

On Arduino IDE side, the upload speed is coded in hardware/arduino/boards.txt

uno.upload.speed=115200
...

for every kind of board; you cannot change it directly from the IDE (that would be too dangerous as that value must match the expected speed for the actual bootloader of every board).

Now as per the optiboot loader side, the upload speed is defined in BAUD_RATE macro, in optiboot.c:

/* set the UART baud rate defaults */
#ifndef BAUD_RATE
#if F_CPU >= 8000000L
#define BAUD_RATE   115200L // Highest rate Avrdude win32 will support
#elsif F_CPU >= 1000000L
#define BAUD_RATE   9600L   // 19200 also supported, but with significant error
#elsif F_CPU >= 128000L
#define BAUD_RATE   4800L   // Good for 128kHz internal RC
#else
#define BAUD_RATE 1200L     // Good even at 32768Hz
#endif
#endif

So I guess you can:

#define BAUD_RATE 19200 before that block of code
recompile the optiboot loader
upload your own new bootloader version
update uno.upload.speed accordingly in boards.txt
check it on the usual blink sketch and cross your fingers :-)

Please note that this kind of task is not for beginners, you need to know what you're doing.
Also note that I disclaim any responsibility if you get unable to upload programs to your Arduino afterwards!


Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

You do not want a voltage regulator you need a level shifter.

You can buy them cheaply or make them up with a transistor or MOSFET.

I gather the ESP8266 has a Tx (transmit) to the Arduino. You probably don't need to level-shift that, as the Arduino Uno will interpret 3V upwards as a HIGH. For the Rx (receive) from the Arduino you need to level-shift the data pin (possibly a voltage-divider might work) since the 5V from the Arduino needs to be converted down to 3.3V.

The ESP8266 Vcc and CH_PD can go to the Arduino 3.3V pin.

Disclaimer - I haven't done this, I am summarizing what I read on various web pages. Read some of the answers on the pages you get when you do a Google search for more details.

References

Voltage divider - Wikipedia
Level shifter - StackExchange
SparkFun Logic Level Converter - Bi-Directional
4-channel I2C-safe Bi-directional Logic Level Converter - Adafruit
Bi-directional level shifter for I²C-bus and other systems - PDF
ESP8266 Community Forum


How to convert byte array into a single variable

You can't convert 20 bytes to long. Send it as string of hex values. A byte takes two characters in hex, so you will send a 40 characters string, which can be simply decoded back to bytes.

char str[sizeof(myTID) * 2 + 1];
const char* hex = "0123456789ABCDEF";
for (int i = 0; i < sizeof(myTID); i++) {
  str[i * 2] = hex[(myTID[i] >> 4)];
  str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
}
str[sizeof(str)] = 0;
Serial.println(str);


Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?

Yes as long as the polarity is correct, the board will only take the current it requires


Tracking Device Using Arduino UNO, GSM and GPS

void loop() {
    ....
    loop();
    ....
}

That's an instant death warrant right there. You can kiss your stack goodbye as it crashes mercilessly into your heap. Never ever ever call loop() from anywhere.

Your decision as to whether or not to get the GPS data is completely flawed. It will run the function once when it finds "Staff" and never again (unless it sees "Staff" again on serial). It doesn't keep finding the same thing over and over again unless you keep sending it over and over again.

And come to that - how exactly are you sending "Staff" and "Stop" through GSM? I assume by SMS message, however I see no code there to actively retrieve the SMS messages from the SIM. So you'll never see anything anyway.

You need to completely re-think your whole program methodology:

Look for new SMS messages
If any exist then read one and delete it.
If the message contained "Staff" then enable sending mode. If the message contained "Stop" then disable sending mode.
If sending mode is enabled and enough time has passed since the last sending then get the GPS data and send it.

You notice the sending of the GPS data is separated from the SMS reception. It's not the reception of the SMS that controls the GSM but the "mode" your program is running in. The SMS just controls that mode.

This is a crude form of Finite State Machine.


How to interface with generic IR RGB LED controller?

The IRRemote Library is a good starting point, but you'll probably need a RAW mode.   I've got a couple IR controllers from different companies, and they use different codes for the same things.


I figured it out.

I was passing the engine objects as references instead of pointers.

main.cpp

// Engines
engine::Engine
    engine1(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    engine2(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    engine3(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    engine4(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);

engine_controller.cpp init list

EngineController::EngineController(engine::Engine &t_e1, engine::Engine &t_e2, engine::Engine &t_e3, engine::Engine &t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}

The solution would be to use dynamic memory allocation.

main.cpp

// Engines
engine::Engine
    *engine1 = new engine::Engine(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    *engine2 = new engine::Engine(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    *engine3 = new engine::Engine(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    *engine4 = new engine::Engine(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);

engine_controller.cpp init list

EngineController::EngineController(
    engine::Engine *t_e1, engine::Engine *t_e2,
    engine::Engine *t_e3, engine::Engine *t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}


Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

The auth_read_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.

The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.

Here's how I connected it:

Component markings and connections

|-------------------------------------------|
|   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
|----------|-------|-----------|------------|
| SDA (SS) |  10   |     7     |            |
| SDA (SS) |       |     6     |    SDA     |
| SCK      |  13   |     5     |            |
| SCK      |       |     4     |    SCK     |
| MOSI     |  11   |     3     |            |
| MOSI     |       |     2     |    MOSI    |
| MISO     |  12   |           |    MISO    |
| IRQ      |  N/C  |    N/C    |    N/C     |
| GND      |  GND  | 8,9,11,14 |    GND     |
| RST      |   5   |           |    RST     |
| 3.3V     |       |     1     |    3.3V    |
|-------------------------------------------|


Difference between PWM and regular output port for servos?

Servos does not use PWM, it uses PPM:

PWM = Pulse width modulation, The pulse start at 0ms, and is high for the percentage of the time compared to the percentage of the voltage you want, 5v signal, if you want 1v, the pulse is 20ms High and 80ms Low.
PPM = Pulse position modulation, The pulse length is always 5ms High and 95ms low, but the interesting part is if high starts after 5ms or 50ms (or any other).

So PWM is to lower voltage, PPM is a signal pulse.

This means that no matter what port you are using on the arduino you are able to control a servo since you only need High or Low, and not a lower voltage.

What you need to be aware of in this case is on the arduino is a PPM signal is using up a timer. The arduino has 3 timers where of 2 is available, one is used internally. Though there is code where you can attach up to 3 servos on the same internal timer.


Arduino and Raspberry Pi - initiate I2C communication as slave

You need to use a separate signalling method to alert the Pi that a sensor value is ready to be collected.

This is usually done using an interrupt signal. Your Arduino changes the state of a GPIO pin which is connected to a GPIO pin (through suitable logic level translation as necessary) on the Pi. When the Pi sees that pin change state it requests the data from the Arduino.

It is most common to have the transition from HIGH to LOW as an interrupt signal (aka Active Low) since that allows a simple wired-OR arrangement (open drain GPIOs with a pullup resistor) to allow more than one device to raise the same interrupt.


Using TMRpcm object, why is the SD Card failing to be found by arduino?

See  https://github.com/greiman/SdFat

Ensure it works with the sdinfo example, and then you can just use the sdformatter example to format the card.


Using Serial as boolean function argument

HardwareSerial defines operator bool(), which allows it to be used in a boolean context.


The question is what goes wrong, and why, when the ISR trigger is set to LOW.

edge vs. level triggered interrupts.

Read the datasheet.


Reading multiple bytes from *software* serial

Serial1 on the Arduino Leonardo is hardware serial, not software.

There are several ways to read in multiple bytes from Serial.

Instead of detecting Serial.available() (i.e. non-zero), change it to Serial.available() >= 2

if (Serial.available() >= 2) {
  for (int i=0; i<2; i++) {
    buffer[i] = Serial.read();
  }
}

Or you can leave it as it is, and read into the buffer one at a time.

static int bufferIndex;

if (Serial.available())
{
    buffer[bufferIndex++] = Serial.read()
}

You'll need to detect the contents of the buffer in another if statement, and also deal with the bounds of the index.

Honestly though, noise is your issue here - this is an example of an XY problem. There's nothing inherent in using a microcontroller with relays that should mean that serial won't work.


Serial read SSID and PASSWORD WiFI connection failed in ESP32

Is your Serial Monitor setting set to "Both NL and CR"? Change it to "Newline" should works.

What happened is if your Serial Monitor has a setting of "Both NL and CR", when your press Enter, it generates a \r\n, the Serial.readBytesUntil(10, ssid, 50) picked up that \r at the end of the array, when you use it as SSID, it is not a valid SSID.


There's a hardware conflict between these two boards which seems to not be resolvable. The solution was to buy the Keyes USB shield, make sure only it has access to pins 9 and 10 from the Arduino and then wire pin 7 (or 8) into pin 9 of the CAN shield, while also properly initializing the CAN shield with that new pin.

Lastly, the Keyes USB shield's ICSP header isn't long enough, so you need to cut 2 mm off the male non-ICSP pins in order to seat it properly on the CAN shield.


What is the best way to attach TMP36 sensor to the copper coil?

If you don't have to worry about conductivity from the electrical standpoint, you could use a thermal epoxy such as Arctic Silver which uses "microfine" particles of silver to conduct heat. It's a two part (redundant when using the term epoxy, I think) adhesive that is engineered to transfer heat, but may also short conductors. I've used the stuff and unless subject to intentional separating force, it holds well.


How can I differentiate between multiple circuits?

First, let's consider the logic of your program. You have two groups of
pins: 6 pins connected to the wires and 6 pins connected to
the terminals. The first thing I would do is forget that these are two
different groups. Consider you just have 12 pins that the user has
to connect in a specific fashion. This way most “weird things” the user
could do, like connecting wires together, are not a special case
anymore. They are just another invalid combination. Now what you have to
do is, for every pair of pins among those 12, determine whether or
not they are connected together. If any pair is connected that shouldn't
be, you have an invalid combination. If any pair is not connected while
it should be, it's again an invalid combination. If every pair is the
expected state (either connected or not connected), then the user did
solve the puzzle.

Now, for the hardware side. A simple way to know whether two pins are
connected together is to set one of them to INPUT_PULLUP and the other
one to OUTPUT LOW. This second pin should be the only one
accessible to the user that outputs a LOW. All other exposed pins
should be set as either INPUT or INPUT_PULLUP. Now, if the first pin
reads LOW, you know have a connection. If it reads HIGH the two pins
are not connected together.

Here is an example program demonstrating that principle. It loops over
the 66 possible pairs to check whether they are connected or not.
You just have to replace the inner if with your code that validates
the combination.

const int PIN_COUNT = 12;
const uint8_t pins[PIN_COUNT] = {...};

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

    // Set all pins to INPUT_PULLUP.
    for (int i = 0; i < PIN_COUNT; i++)
        pinMode(pins[i], INPUT_PULLUP);
}

void loop() {
    // Loop over all pin pairs (pins[i], pins[j]).
    // Set pins[i] to OUTPUT LOW, then read pins[j].
    for (int i = 0; i < PIN_COUNT - 1; i++) {
        pinMode(pins[i], OUTPUT);
        digitalWrite(pins[i], LOW);
        for (int j = i+1; j < PIN_COUNT; j++) {
            if (digitalRead(pins[j]) == LOW) {
                Serial.print("pins ");
                Serial.print(pins[i]);
                Serial.print(" and ");
                Serial.print(pins[j]);
                Serial.println(" are connected together.");
            }
        }
        pinMode(pins[i], INPUT_PULLUP);
    }
}

As for the safety, you should be fine as long as the users do not have
access to any low-impedance ground or voltage source. In particular, the
GND and 5V pins should not be user-accessible. For extra protection, you
could put a 1 kΩ resistor in series with each pin, but then all the
pins that are not actively being tested should be set to INPUT rather
than INPUT_PULLUP, otherwise multiple pullups in parallel may start to
compete with the series resistor.


There is a far easier (and safer) way to charge them without using an Arduino. Over-voltage is an issue and another crucial factor with the 18650 batteries is to not let the voltage drop below 2.5 volts when you are dis-charging them. There is a simple "Charge/Discharge Board Module for 18650 Lithium Batteries" that sell for approx. $1 US:

http://www.ebay.ca/itm/2in1-1A-USB-Charge-Discharge-Board-Module-for-18650-Lithium-Battery-Phone-Bank-/302039028674?hash=item4652edd3c2:g:bDkAAOSw9NdXrBoE.

The board has a "fast charge" current of 1000 mA until the battery reaches 4.2 volts, then it switches to a "trickle charge mode". The circuit board also stops current flowing out of the battery once the voltage drops to 2.5 volts. Most of the older charger boards do not have this feature and it's almost as important. It also has a "over-current" protection current of 3.0 amps in case you try to draw too much power from it.

The circuit board has a mirco USB connection on it but be VERY careful before you plug it into a computer USB port. My old MacBook only provides up to 500 mA at each USB port, half of what's required.

The circuit board is 0.700" X 1.050". Here is a picture of it:


arithmetic operation outcome differs from the expected outcome

Once again an example to Why should I learn C/C++ first before learning Arduino.
The main point here is: know your data types.

Your calculation millisec*frequency/1000 would work if it was a compile time constant that is evaluated by the pre processor. In any other case this is a runtime value and so the limitations of the datatype apply.

Unless stated otherwise I assume your variables millisec, frequency and counting are of type int. int has a platform specific width. On Arduino this is 16-bit. (Other platforms have other widths)

It is also signed, that is why it can hold values between -32768 and 32767.
You calculation millisec*frequency evaluates to 500 * 220 = 110000 which is many times larger than the value that can be represented.

You can do two things:

Use long which is 32-bit on Arduino. But actually I'd prefer to use a type with an obvious width. As you don't seem to need negative values I'd prefer uint32_t.
If milliseconds is a constant, you can make it smarter by reducing your calculation to a division by two (or better a single right shift).


I'm not familiar with the term proxy code, but I'm assuming that it's a piece of code on your computer that acts as a man in the middle.

You cannot directly use Arduino to run a shell command, so you'll need to create a program on your computer that listens to serial and then executes a command.

For the "proxy code" Python would be a good choice because of the pySerial library that plays nicely with Arduino. It seems fairly easy to execute a shell command with Python.

As per the Arduino code, something like this would work good:

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

loop() {
  if(state == true) {
    Serial.print('A');
  }
}


Potting of circuits can lead to various issues. It can't be told exactly what caused your device to fail until you uncover it like an archeologist.

Common problems are:

Resin entering a spring loaded contact and canceling out contact forces
Resin exsuding corrosive substances ruining contacts
Resin expanding during curing and opening spring contacts or even breaking up solder contacts
Same effect after cool down of resin

Later and often unexpected problems are:

thin gaps around potted objects (i.e. no surface contact) literally sucking in water.
potting material producing water itself during curing.

Many of these problems can be circumvented by applying conformal coating, as suggested by comments and apparently proven right by your experiments.
If it is not necessary refrain from using sockets and solder connections directly to the components. You won't be able to salvage them, anyway.


Installing Arduino 1.5.6 solved the issue.


Blink LED with different on off times just once with millis

You could use two millis() based timers.
// Sketch uses 1066 bytes (3%) of program storage space.
// Global variables use 27 bytes (1%) of dynamic memory.
// Arduino Uno, IDE 1.8.9
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds){
      m_timerActive = 0;
      m_previousMillis = 0;
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

    byte IsActive(){
      return m_timerActive;
    }

};

// Make copies of the object to work with.
MillisTimer TwoSecondTimer(2000);
MillisTimer ThreeSecondTimer(3000);

void setup(){

  // Call this function when an event is triggered.
  ThreeSecondTimer.ReStart();

  // Timer status indicator.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Call the update function as fast as possible.
  if(ThreeSecondTimer.Update()){
    digitalWrite(LED_BUILTIN, HIGH);
    ThreeSecondTimer.Stop();
    TwoSecondTimer.ReStart();
  }

  // Call the update function as fast as possible.
  if(TwoSecondTimer.Update() && !ThreeSecondTimer.IsActive()){
    digitalWrite(LED_BUILTIN, LOW);
    TwoSecondTimer.Stop();
  }

}


Exiting from one loop and get ready for another

You are never really invalidating the passwords. The statement

password1.append('1');

adds '1' to the guess, it does not change the password itself.
If you really want to invalidate the password, you should change it to
something that cannot be typed on the keypad. For example

password1.set("X");  // untypable password

Whether or not you do invalidate the previously used passwords, you
should reset the guesses once a password has been checked. This can be
done in checkPassword(), or in keypadEvent() as follows:

switch (eKey) {
    case '*':
        checkPassword();
        password1.reset();
        password2.reset();
        break;
    ...
}

BTW, all your return statements are useless, and the first
switch/case in keypadEvent can be replaced by

    if (keypad.getState() == PRESSED)

which would be easier to read.


Prevent 5V output on Arduino Nano 5V pin

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

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

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

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

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


The MG811 spec gives you the range of measurement, but without the values and connections of the surface mount op amp on the board the only way to determine the voltage output for each CO2 concentration is with a Voltmeter and an already calibrated CO2 PPM meter, which you could perhaps borrow from a lab or university.  Once you have the CO2 values and Voltages that correspond, you can build a formula or function to convert the digital values to voltages and then to CO2 concentrations.

The other option is to trace the tracks on the PCB and create a schematic and then post the spec above and the schematic with resistor values included on the electronics Stack Exchange.


Washing machine controlled by Arduino for homebrewing

There is an article by Atmel, talking exactly about this (not for homebrewing, though). They provide a link to a PDF file that describe in detail a project involving Arduino and a re-created washing machine.

Note that it seems to be some kind of Bachelor graduation project, and that the students seem to build an entire washing machine. They control the rotor using an Arduino, and even provide the code (and a brief history about washing machines..).

Apart from building the entire machine, there are two main directions here as I see it:

Manipulate the existing washing machine's control board using Arduino. The bad news are the it would require some reverse engineering of the existing controller, because, per my understanding (and I'm not an expert on the subject) there is no one standard and any manufacturer seems to use it's own propriety control board (similar to Microwaves or Dishwashers). The good news are that an expert could probably do it, either by dumping the controller memory and examining the hex code or by using JTag.
Another way to go here is interfacing the electrical hardware itself; see this instructable where the guy connected the Arduino in parallel to the start button, by thus allowing an alternative way to start.

As for a beginner, it would make more sense to go for the latter; in-parallel connection with an existing hardware button should be a fairly comprehensible task. Consider the hazards of working with a high voltage/power device such as washing machines. I must say that on first glance such a project doesn't seem fit a novice, but I would be the last one to hold an enthusiast's back. And if you know any, I would suggest asking supervision from someone with a strong EE background.


16Hertz Uno R3 Board vs Arduino Uno R3 Board

You need to have a look at the Arduino comparison table. This shows that all Arduino Uno boards run at 16 MHz. It seems that you have fallen for the marketing on the page for the Uno kit that you provided.

Also, which version of the IDE are you running? You should upgrade to the latest version, which is currently, at the time of writing, version 1.6.1.

To answer your questions in turn:

"16Hz" is the brand name and has nothing whatsoever to do
with the speed, which is actually 16 Mega Hertz. "Clock" and
"Frequency" refer to the same thing. 16 MHz is the clock frequency
of the board, and is the speed at which the ATmega328 runs at.
The RS Online link does indeed state 20 MHz, but that is merely the
maximum speed at which the ATmega328 can run at. The Uno under clocks it at 16 MHz.
The Ports menu will show you a number of possible devices, Arduino Uno should be one of them (which is the one you should select) and three items below that will be Arduino Mega or Mega 2560 (which you should ignore, you do not have a Mega board1). Unfortunately the Arduino site only shows the Mac menu, even on the Windows guide

which is no help to you, assuming that you are running the Arduino IDE on Windows. You should actually see this in the Board menu:

and this in the Port menu:

As you can see, there should be no mention of the microcontroller in the Port menu.
The 16Hz branded Uno and the Arduino Uno are to all intents and purposes the same and as I state in the first line, the 16 MHz Uno is exactly the same as a regular Uno, it is just marketing.
Both the 16Hz and the Arduino Uno have a ATmega328 and the Mega board has a ATmega2560. Again, check the Arduino comparison table to see the variety of the boards and their respective microcontrollers.

I hope that answers your questions.

1 If you do chose the Arduino Mega or Mega 2560 option, in the Board menu, then indeed there will be an additional Processor menu. However, this is irrelevant in your case, as you do not have a Mega board, and so you need to chose the Uno in the Board menu. If you do so, then the Processor menu will disappear, as it is not needed for the Uno.


Arduino Serial and myserial clarification. How to print out rx output?

It seems like you are using both the hardware UART pins and two other pins for SoftwareSerial i.e. UART emulated by the arduino.

When you write Serial.read() or Serial.write(), Arduino knows to use the UART hardware on the chip which is has RX/TX pins 0 and 1 for most Arduinos. So by using these functions you will be able to communicate with any device which is connected on these pins.

Generally, when you have the Arduino connected to your computer, these RX/TX pins internally go to a serial port on your computer via the USB, hence you can send/receive data to the computer and view it on the Serial Monitor. Great for debugging purposes!

Sometimes, like in your case for controlling the camera, you need to have another serial port for communication because UART is point to point i.e. only 2 devices can communicate via it. SoftwareSerial helps you do that by using  two other pins on the Arduino into RX/TX pins. If you look at the top of your code file you will see a line like this

SoftwareSerial mySerial = SoftwareSerial(...);

Inside the brackets you will also see the two pin numbers which are being used as RX/TX. In the software serial example pins 10,11 are being used. So whatever is connected to these pins (i think your camera module is) will be able to send/receive data using mySerial.write() and mySerial.read().

Hence, to be able to receive data from the camera you will use mySerial.read().


Can Arduino UNO permanently store a code?

idk if the arduino stores the code for ever

The code is saved in the flash memory, which is non-volatile. It does not lose its content during power cycles. Also, when looking at the time dimension, it holds the code over a very long time, though not for ever. The datasheet of the Atmega328p (the microcontroller in the Arduino Uno or Nano) states:

Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

So over 20 years at a temperature of 85°C you can get 0.0001% of data loss in the flash memory. At normal room temperature you can get that loss in 100 years. So significantly longer than the lifetime of most electronic products.

I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

There are different ways and levels of protection. Though that is a more advanced topic, that you should tackle, when your product is finished otherwise. There are multiple resources on the web about this. The first place to look is always the datasheet of the used microcontroller. First part might be to not use the standard Arduino bootloader, but your own. And then you can set 2 fuses for getting different levels of protection (write protection, read protection), that will lock out 99% of the people. This question on Electrical SE might also be interresting for you. You can find many resources on the web by searching for something like "Arduino code protection" or "AVR code protection" (if you are using an AVR based microcontroller like with the Arduino Uno/Nano/Mega)

Apart from that I also would open the question to you, if your code is really that new and ingenious, that you need to protect it from being read that way? It might totally be, that this is the case for you. But from my perspective the probability is very low. I cannot say of my own codes, that they are worth the hassle of protection. And it also depends on what you really want to prevent that way.
For context: When you program the Arduino (or any microcontroller) with your C/C++ program, the text of the program is not saved on the Arduino. Instead the code is first converted to Assembler code and then compiled into binary machine code. On that level all the nice concepts of the higher level languages are not present, so they are done by multiple lower level functions (for example loops are jumps with conditions). An attacker might read the machine code back from the microcontroller. The biggest threat here is, that he would just copy it to a new microcontroller.
If he wants to get "code" from it, he would invoke a disassembler, which converts the machine code back to the assembler language. But at this point all symbols (names of variables, functions, ...) are lost, because they are not saved in the original machine code from the start. Reading and understanding such a code is very difficult, especially, if your code is rather big and complex. Most times it would be easier for an attacker to just reverse engineer your code based on the behavior of the original microcontroller.
So in the end, you cannot really prevent people from building counterfeit products. That's what a patent is for.
This does not mean, that you should not use the code protection. Just do a realistic security assessment and then decide, if it is worth the hassle.


What info should I look for when choosing a solid state relay for arduino?

If you're only controlling a button, the load current and load voltage are pretty much irrelevant since I'd be surprised if you even used 5% of it's rating in either category. I can't tell you how much you'll need here since I don't know the voltage that the relay will be operated on and the resistance of the path for the load.

What you do need to look at is the voltage and current of the input/control/logic signal. It should allow a 5V control voltage and the current draw for that logic signal should be no more than 40mA, although it's ideal to stick to a lower number (say, 30mA).

However, manually picking out a relay manually isn't ideal for a beginner since it requires a bit of extra components to properly run. A relay module (Amazon) allows you just hook up your wires to the jumpers and terminals of the relay module without any extra soldering (as far as I know they aren't breadboard compatible, thus requiring a custom PCB or having it "flop") or parts.


Pro Micro recognised as Micro (win10, IDE 1.8.1)

Treat it as what it is.

What windows sees it as is just what USB reports it as. It's just a name. It has no bearing on what it is or how you program it. Select the actual board that you have in the IDE, not what Windows says it thinks it is.

As a general rule: Ignore everything Windows ever says, it's full of sh!t.


How to control MKR1000 from outside your local network

The only way I can think of to achieve this would be to port forward your router, and forward port 80 (http) to your MKR1000. You can check out https://portforward.com/ for instructions on that.

If you don't want to port-forward, you'd have to have the MKR1000 connect to a centralized IOT server somewhere, and have the user go through the server to access the MKR1000. That's how other iot devices such as nest cameras do it.


You can define an interrupt service routine (ISR) for each Timer and PWM pin that it handles. These are known as TIMERn_COMPA_vect, TIMERn_COMPB_vect and TIMERn_COMPC_vect. The Mega has six Timers (n=0..5).

ISR(TIMERn_COMPA_vect)
{
// Timer/Counter compare match A
}

Check the PWM configuration for how the pin is set, cleared or toggled.

Cheers!


How do I get more than 64 characters of message from serial

First: There is no such concept of a message on the Serial bus, unless you implement it yourself. On hardware level only individual bytes are transmitted, and you don't even know, when each byte will be transmitted exactly. Since there are only individual bytes in the first place, there is no limitation on how many bytes can be transmitted.

Yes, the Serial library has a limited buffer of 64 bytes, but as Majenko wrote it is not intended for buffering all bytes for one of your messages. It should only buffer the bytes, until the main sketch can read them from the buffer. On reading the bytes will be removed from the buffer, leasing buffer space for new characters.

The buffer size of the Serial library can be increased by changing the numbers in HardwareSerial.h in the following lines

#define SERIAL_TX_BUFFER_SIZE 64

#define SERIAL_RX_BUFFER_SIZE 64

But this is not really the solution to your problem. When first filling the buffer and then read the whole message you just arbitrarly
constrain yourself to a insufficient solution.

Instead of waiting for all the messages bytes (and finally filling up the buffer) you should steadily check, if new bytes are available and then load them into your own buffer. You can use a delimiter byte to mark the end of a message, mostly "\n" (newline character) is used for this. Copy the bytes into your own buffer, until you read the delimiter byte. Then use the message as a whole for your application. Don't forget to clear your buffer afterwards.

The examples for the Serial library, especially the SerialEvent example show how to do this in your code.


About random numbers

What you are trying to achieve is actually not that easy. An Arduino is
basically a computer, and as any computer, it is designed to execute
instructions in a very deterministic fashion. Computers are not good
at randomness and, unless fitted with dedicated hardware, they cannot
generate random numbers. Given this, you are left with two options:

pseudo-random number generators
entropy gathering

The first is the easiest:

int first_dice  = random(1, 7);  // 1 (inclusive) to 7 (exclusive)
int second_dice = random(1, 7);

and voilà! You have two random-looking numbers. They are random-looking
in the sense that you will find no obvious pattern in any sequence of
numbers you draw. However, if you reset your Arduino, either with the
reset button or by power-cycling it, it will give you the exact same
sequence as in the first run. Thus, pseudo-randomness in useless unless
you commit to never unpower your circuit. It is a good starting point,
however, if your main goal is to get started with Arduino programming.

Entropy gathering means getting some randomness from outside the
Arduino: you would connect it to some source of randomness and perform
some measurement that has unpredictable outcome. A human being is a good
source of randomness: if you require the user to press a button before
displaying the dice value, the timing of the button press is a good
random source. The micros() function can be used to get the current
time with 4 µs resolution, which is more than enough for this
purpose. Entropy gathering is usually used in tandem with pseudo-random
number generators, as a way to seed them, like this:

wait_for_the_user_to_press_a_button();
randomSeed(micros());
int first_dice =  random(1, 7);
int second_dice = random(1, 7);

If you cannot have human interaction, you could try to get some
electromagnetic noise by performing an analogRead() on a floating pin.
Ideally you would connect that pin to an analog noise source. See the
first comment to this answer for more information on this option.

About arrays and loops

You should definitely try to find a good tutorial about arrays and
loops. Whenever you find yourself writing tons of almost-identical lines
of code, you should wonder whether you can replace that repetition with
a loop. For example, for displaying the digit 1, you may write:

if (number == 1) {
    digitalWrite(leda,  LOW);
    digitalWrite(ledb, HIGH);
    digitalWrite(ledc, HIGH);
    digitalWrite(ledd,  LOW);
    digitalWrite(lede,  LOW);
    digitalWrite(ledf,  LOW);
    digitalWrite(ledg,  LOW);
}

(I am using the "canonical" A–G letter assignments, and yes, you should
also take care of setting to LOW the segments you want to be off).
This code is an obvious candidate for being replaced by a loop:

if (number == 1) {
    for (int segment = 0; segment < 7; segment++)
        digitalWrite(leds[segment], digit1[segment]);
}

This requires that you first define the following arrays:

//                A     B     C     D     E     F     G
int leds[]   = {  2,    3,    4,    5,    6,    7,    8 };
int digit1[] = { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW};

This logic can be pushed one level further by using a two-dimensional
array (an array of arrays): instead of defining six arrays digit1,
digit2... digit6, you create an array of arrays like this:

int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         ...
};

and you use digits[number] instead of digit1, etc. This way you get
rid of the whole if () ... else if () chain, replaced by:

for (int segment = 0; segment < 7; segment++)
    digitalWrite(leds[segment], digits[number-1][segment]);

Take care though that in C++ arrays are indexed from zero, which is why
you need to use number-1 as the index in digits. If you have more
than one die (which is your case), you can also put their pin
assignments in a two-dimensional array. Then all the dice updating code
would be wrapped inside a loop indexed by the die number. Putting all
this together you end up with something like this:

// Pin assignments.
int leds[][7] = {
   /*                A     B     C     D     E     F     G  */
   /* 1st die */  {  2,    3,    4,    5,    6,    7,    8 },
   /* 2nd die */  { A0,   A1,   A2,   A3,   A4,   A5,   A6 }
};

// 7-segment "font".
int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         /* 3 */  {HIGH, HIGH, HIGH, HIGH,  LOW,  LOW, HIGH},
         /* 4 */  { LOW, HIGH, HIGH,  LOW,  LOW, HIGH, HIGH},
         /* 5 */  {HIGH,  LOW, HIGH, HIGH,  LOW, HIGH, HIGH},
         /* 6 */  {HIGH,  LOW, HIGH, HIGH, HIGH, HIGH, HIGH}
};

void setup()
{
    for (int die = 0; die < 2; die++) {
        for (int segment = 0; segment < 7; segment++) {
            pinMode(leds[die][segment], OUTPUT);
        }
    }
}

void loop() {
    for (int die = 0; die < 2; die++) {
        int number = random(1, 7);
        for (int segment = 0; segment < 7; segment++)
            digitalWrite(leds[die][segment], digits[number][segment]);
    }
    delay(200);
}

This is still lacking the entropy gathering phase discussed above.


What are the SVG pins for on the SainSmart Uno clone?

SVG = Signal, Voltage, Ground.

The Signal pin will carry the actual output, which may be high or low at any given time. It's basically just a male version of the corresponding standard GPIO pin. The Voltage pin will always be high (which can be 5v or 3.3v on this board, depending on the output level switch). The Ground pin is exactly what the name suggests -- it's connected to the board's ground.

This obviously means there is a lot of duplication. Why have two signal pins? And why bother having so many Voltage and Ground pins if they're all the same anyway?

The reason is simply convenience.

If you have a standalone external component (such as a motor), you would normally have to run 3 separate wires to it. With the regularly-spaced SVG pins on the board, you can instead use a 3-way cable with a suitable female header block. You can run that to an equivalent set of 3 pins on the external component. That means you are able to attach/detach the component by plugging/unplugging (effectively) a single cable.

I don't think the SVG idea is a 'standard' as such, largely because (in this form) it's only really of benefit to people who are experimenting or prototyping (as opposed to designing a more permanent system). It seems to be fairly popular among hobbyists and enthusiasts though. You just need to watch out for components which may put their equivalent SVG pins in a different order.


What is the best serial communication method between an Arduino and a spectral sensor?

The I2C on this device is slave, not a master. Even though it has its own clock, it is designed to operate as a slave being read by a master.

You will have no issues using the I2C interface - in fact Adafruit uses it for their own software library.

Since there is already a I2C-based library available from the manufacturer I would use that, unless there is a good reason to use the UART instead.


The biggest trouble you are going to find is the voltage levels. The MCP2551 works at 5V and your MCU is 3.3V. I personally don't have experience with this MCUs, but some STM32 MCUs are 5V tolerant on some pins, including the CAN_TX and Can_RX and it's fine to use a 5V Transceiver like the MCP2551.

Anyway, you still can replace the CAN Transceiver with one that has a built in level shifter,  like one of the following:

MCP2562
ATA6561
SN65HVD256
NCV7351D13

I've used all the above, except the TI one, and they all talk nicely between each other. Some have different features, like silence or advanced sleeping modes.

Cheers


How to read an analog value on ESP32-CAM with the SD card reader enabled?

According to the schematic and pin notes, I don't think you can use GPIO4 as an ADC input (it can be used as a GPIO pin and technically it can be configured as an ADC pin), but it has a 47k pull-up resistor on it, making it not possible to be used as an ADC input.
Depend on your hardware wiring skill, one alternative is to use an external ADC chip with i2c interface (such as an MCP3221) and connect it to TWI_SCL and TWI_SDA, but those pins are only available on cam-connector, not on the header pins.


why leonardo bootloader is bigger than UNO?

Apparently leonardo and UNO are very similar boards.

No, they are very, very different.

The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.

The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.


I can think of two ways of doing this.

One is to use the H channel of the HSV colour space (as I show in the answer to this question. This would give you a smooth transition between two colours through the pre-defined spectrum of the hue range.

The second is to simply specify two colours and then mix them at different percentages depending on how far along the length you are.

For example, here's a (untested) small function that "mixes" two individual colour channels together and returns the result:

uint8_t mix(uint8_t a, uint8_t b, int pct, int range) {
    if (pct <= 0) return a;
    if (pct >= range) return b;
    return (((uint32_t)a * (range-pct)) / range) + (((uint32_t)b * pct) / range);
}

pct is the led number in your chain, and range is the total number of LEDs.

So you could (hypothetically):

uint8_t red1 = 0, green1 = 255, blue1 = 0;
uint8_t red2 = 255, green2 = 100, blue2 = 100;

for (int i = 0; i < 50; i++) {
    uint8_t red = mix(red1, red2, i, 50);
    uint8_t green = mix(green1, green2, i, 50);
    uint8_t blue = mix(blue1, blue2, i, 50);
    setLedColor(i, red, green, blue);
}


Send an multidimensional array of values from one arduino to another through serial port

Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.

Sending:

int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      Serial.print(a[x][y]);
   }
}

Receiving

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      a[x][y] = Serial.read(); // Not sure about the exact prototype
   }
}

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.

And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.

If you need dynamic sizes, first send the number of rows and columns and than the values.

In that case instead of 3 and 4 define two constants and use them:

#define NR_ROWS 3
#define NR_COLUMNS 4

int a[NR_ROWS][NR_COLUMNS] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < NR_ROWS; x++)
{
   for (int y = 0; y < NR_COLUMNS; y++)
   {
      Serial.print(a[x][y]);
   }
}


ESP8266 seems to be bricked , how to recover?

No, you have not bricked your ESP8266 by turning on GPIO7's pullup.  All that will do is provide a weak pullup on the MISO line of the flash chip, which itself will have no effect - the flash chip's SPI Data Out pin will be able to easily override that weak pullup.

You can remove the flash chip and replace it with a completely blank brand new flash chip with nothing on it and still upload new code. There is nothing in the flash chip that the ESP8266 relies on to operate.

The boot sequence of the ESP8266 is as follows:

- Start executing the bootloader from the built-in ROM
  - Read the GPIO pins to determine code execution source
  - If flash is selected then initialize flash chip and read from address 0
    - Code on flash examines partition table to find code entry point
    - Jump to code entry point
  - If UART is selected then initialize UART
    - Wait for commands over the UART and respond accordingly

The startup code (boot stage 0) is in ROM. It's impossible to "brick" that.  All that is in the flash is the code that tells the ESP8266 how to find the user's code, and that gets flashed to the chip every time you reprogram it.

You can think of it like BIOS boot on a PC.  In the ROM is the BIOS that tells the CPU how to read from the hard drive. Then at the start of the hard drive is the code that tells the CPU how to load the operating system.  The hard drive doesn't come with that code on it - you install that along with the operating system. But the motherboard has the BIOS built into ROM which tells it how to get going and read that boot sector.

However it is possible to destroy an ESP8266 by connecting the wrong things up to it in the wrong way.  It is also possible to destroy some USB chips (the CH340G in particular) by wiring things up wrong.

So chances are that if you have bricked your ESP8266 it has nothing to do with your program and everything to do with what you have wired to it.


Arduino Nano off 9V : is there any change to output?

It looks like VIN connects to a LM2940, 5 volt regulator, so the voltage on the OUTPUT pin (D2) will never be higher than 5V.


Will it work ? MPU6050 Gyro etc. etc. module

Code would normally look like this

#include <MPU6050.h>
#include <Wire.h>

MPU6050 mpu;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  mpu.initialize();
}

void loop() {

  //what is this doing for you?
  mpu.getWaitForExternalSensorEnabled();

  if(mpu.getIntDataReadyStatus() == 1) {
        float X = mpu.getRotationX();
        float Y = mpu.getRotationY();
        float Z = mpu.getRotationZ();
        Serial.print("X:");
        Serial.println(X);
        Serial.print("Y:");
        Serial.println(Y);
        Serial.print("Z:");
        Serial.println(Z);
  } else
  {
        Serial.println("MPU not ready");
  }

}


Why does Arduino round off some integers but not others when my desktop PC does not do this?

When you cast a floating point number to an integer, it always gets
rounded towards zero. If you want round-to-nearest behavior, you should
use the Arduino round() function.
As to the origin of the discrepancy you see, it comes from two facts:

The numbers you use are not exactly representable as floating point
numbers.
The double on an Arduino Uno is actually equivalent to a float
(32 bits only).

When you write a statement such as dnum = 1.3140;, the compiler stores
in dnum the floating point number that is closest to the decimal
number 1.3140.
Compare:
float32(1.3140) = 1.31400001049041748046875
float64(1.3140) = 1.31400000000000005684341886080801486968994140625
float32(2.3140) = 2.3139998912811279296875
float64(2.3140) = 2.31400000000000005684341886080801486968994140625

Out of these 4 examples, only float32(2.3140) is rounded down.


Will plugging in a 12v power supply in the wrong polarity to a CNC SHIELD fry my circuit or damage my power supply?

If you wire the power into that shield wrongly you risk killing things - and with those big electrolytics reverse polarity could get very messy indeed.
You need to identify the polarity before you wire it in, and to do that you need something that is sensitive to polarity.
If you don't have a DMM you can do it with a simple resistor and LED in series - an LED will only work if the polarity is right.
Take a normal LED of the 5mm type (they're easier to identify) and look for the flat edge on the flange around the base. That indicates which is the "negative" or cathode of the LED.  Alternatively look for which of the legs is the shorter of the two, which is also an indication of which is the cathode.
Connect a resistor to this identified negative leg. You want the resistor to be at least 1kΩ, but no more than 10kΩ. You don't need the LED to be bright...
Connect your wires, one to the LED and the other to the resistor.
If the LED lights up then the wire connected to the LED is positive and the wire connected to the resistor is negative.  If it doesn't light up then the wires are reversed.  In this case check it by swapping the wires over - the LED should now light up.


On all Arduino boards except the DUE, attachInterrupt() does not use the pin number as first argument but the interrupt number, which is different:

void attachInterrupt(uint8_t interrupt, void (*ISR)(void), int mode);

As documented on Arduino reference, for an Arduino UNO, the mapping is as follows:

Interrupt 0 -> Pin 2
Interrupt 1 -> Pin 3

So just change the code in setup() to:

attachInterrupt(0, inter, CHANGE);

And that should work for pin 2.


Arduino retrieving PHP echo using ESP8266

It looks like you post request may be missing a CRLF at the end (it needs two) and some spaces.

I think you need this:

 String postRequest = "GET " + location + "\r\nHTTP 1.0\r\n\r\n";

My suggestion would be to get a REST client (like the one you can get for Chrome as an App) and send the message to your server through that and see what the difference is.


Arduino compatible's serial port not showing Mac OSX

From the OSX System Report we learn that your board is based on an SiLabs CP2102 converter (or workalike), but according to your question you installed the drivers for an entirely different product from FTDI

(Arduino.cc has used FTDI in the past and CDC/ACM today, I don't believe they have ever used SiLabs so their instructions probably don't cover that, but other vendors obviously have)

Install the CP2102 drivers and it should work if you use the /dev/tty.XX device which then appears when you plug in the board.

SiLabs appears to provide the drivers at

http://www.silabs.com/products/mcu/pages/usbtouartbridgevcpdrivers.aspx

Just for sake of completeness, there are at least 5 distinct protocols/chips in use for serial-like USB communication with embedded devices:

FTDI
CDC/ACM Virtual Com Port
SiLabs CP210x
Prolific PL-2303
ch340

(Additional possibilities could include actual RS232 serial or serial-over-bluetooth)


Fair play, that is a lot of flux residue. I am assuming you are using some quite chunky solder with lots of flux in it.

Flux is non-conductive, so the residue will be forming an insulating layer on the outside of the solder. That doesn't mean the joint is bad, only that you can't get to the joint because the flux residue is in the way.

If there is a conductive path between the tip of the pin and the pad next to it then all is fine. The fact that you can't see the signal through the outside layer of flux is neither here nor there.

If you want to clean it off you can use isopropyl alcohol (AKA PCB cleaner, AKA "rubbing alcohol") and use, for instance, a tooth brush to scrub it off.


The problem is that you add 15, and than if it's >= 240, you decrease 15, so it will not change  (I wouldn't consider it haywire though).

You can better use a direction sign. Below is only the relevant code (not the GPIO functionality). What it does in the loop is, in case up is true, it adds fifteen, otherwise it subtracts 15. When 255 is reached, it starts counting down (up is false), when reaching 0, it starts counting up (up is true). This only works if 255 / the amount to add/subtracts reaches exactly 255, otherwise you have to check for <= 0 and >= 255.

bool up = true;
int fade = 0;

void loop()
{
    fade += up ? 15 : -15;
    if (fade == 0)
    {
      up = true;
    }
    else if (fade == 255)
    {
      up = false;
    }
}

Not considered good coding practices:

The last if statement can be substituted for the following line, which means: if going up and 255 is reached, go down, else if going down and 0 is reached, go up, otherwise don't change direction. But it is much less readable, so I prefer the longer if statement.

up = (up && (fade == 255)) ? false : ((!up && (fade == 0)) ? true : up);

Another version: if fade is 0 or 255 (only two possibilities), go up if 0 is reached, else (can only be 255) go down, else don't change.

up = (fade % 255 == 0) ? (fade == 0) : up;


You need two counter for this, one to keep track of how far the LED bar is filled, and one about the current 'running' LED to eventually 'touch' the LEDs which are already moved to the right.

Every led (currentLed) will run from index 0 until the last filled index, while the last filled index is decreased with 1 after every loop.

(note: I haven't checked the code).

// Fill from the right, thus count backwards.
for (int filledLedIndex = NUM_LEDS; filledLed >= 0; filledLed--)
{
   // Now let a LED run from 0 upto filedLedIndex;
   for (int currentLed = 0; currentLed < filledLedIndex)
   {
      // Make previous LED black
      if (currentLed > 0)
      {
         leds[i - 1] = CRGB::Black;
      }

      // Make current LED red
      leds[i] = CRGB::Red;

      // Show.
      FastLED.show();
      delay(50);
   }
}

// Clear all LEDs.
for (int led = 0; led < NUM_LEDS; led++)
{
    leds[i] = CRGB::Black;
}

FastLED.show();
delay(50);


is the Arduino shield pinout a standard, so that any Arduino shield can work with any Arduino board

Most shields will fit most of the "regular sized" boards. the obvious exception is the boards like the nano which are tiny. Shields are going to have the best compatibility with the Uno, just because that one is the most common, so if you are going to get one arduino and a bunch of shields, get an uno. Some shields (the gen 1 ethernet and wifi shields in particular had an issue where they could not be used on Megas because the mega listens to SPI on pins 50+ which simply were not connected to the shield, however most of the newer shields will connect to the 6-pin block in the center now-adays to allow Mega usage.

The next thing you want to look at is if you are stacking shields, if they will collide on pin usage (SPI gets around this through multiplexing) and some of the 3.3 volt devices may have conflicts with 5-volt shields. Although the 3.3v devices do provide 5v power-out pins in the same locations as the Uno, it becomes more of an issue with trying to read a 5v on a 3.3v pin, which could damage the microchip.

the best thing to do is to check the documentation of the shields and check which pins they use, what voltages they need/supply, and comparing this with the particular arduino you are using.


What causes a "blip" in LED brightness with sequence of 254, 255, 0, 1 brightness values?

The Why does an LED sometimes flash when increasing brightness? question does exactly describe my problem (except for the substitution of pin 11 for pin 9).  That question refers to this post at forum.arduino.cc which gives the beginnings of an answer.

The problem is caused by the fact that analogWrite(led, 0) does not use PWM, it just sets the pin to LOW.  So when you call analogWrite(led, 0), the value in the Output Compare Register (OCR) is left at 255.  When you call analogWrite(led, 1), the OCR value is changed to 1, but due to double-buffering this doesn't take effect until the next timer cycle begins.  So for a fraction of the current timer cycle the output pin is left at HIGH.

The solution is to either avoid calling analogWrite(led, 0) or to explicitly set the OCR value to 0 when analogWrite(led, 0) is called.  This will only work if another call to analogWrite() is not made in the current timer cycle.  Given that the default timer cycle takes 32 microseconds, this is unlikely to happen.  32 microseconds = 256 (ticks per timer cycle) / 16MHz (clock ticks per second) * 2 (default timer prescale factor).

For pin 9, the solution was to add these lines immediately after the analogWrite() call:

if (brightness == 0) {
    OCR1A = 0;
}

For other pins, use the correct Output Compare Register.  For the Arduino UNO they are:

+-------------+----------+-------+
| Arduino Pin | Chip Pin | OCR   |
+-------------+----------+-------+
|           3 |        5 | OCR2B |
|           5 |       11 | OCR0B |
|           6 |       12 | OCR0A |
|           9 |       15 | OCR1A |
|          10 |       16 | OCR1B |
|          11 |       17 | OCR2A |
+-------------+----------+-------+

Of course this solution will need to be modified if you have changed anything related to timers such as the PWM mode.

The solution given by the forum.arduino.cc post indicated that the Timer/Counter Control Register (TCCR) needed to be modified in addition to setting the OCR value.  This modification was to configure the PWM mode, but the PWM mode would have already been correctly configured by any previous call to analogWrite() for that pin.

Others have suggested that calling analogWrite(led, 1) before analogWrite(led, 0) would be a simpler solution, but that still results in a flash, albeit shorter.

Resources:

LED fade malfunction (random flash) (forum.arduino.cc/index.php?topic=360468.msg2486781)
hardware/arduino/cores/avr/arduino/wiring_analog.c
Secrets of Arduino PWM (www.righto.com/2009/07/secrets-of-arduino-pwm.html).  There is a more recent copy of this article at arduino.cc (www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM), but that copy has the useful graphics stripped out.
Arduino Timers and Interrupts (arduino-info.wikispaces.com/Timers-Arduino)


The Adafruit RTClib has a function to use the compiler date and time. You use the TimeLib maintained by Paul Stoffregen. That library does not have such a function, but you can write it yourself. For example with sscanf and setTime. Without external RTC that will only work if you upload a sketch and keep the Arduino always on. I have a clock like that, and since that clock is always on, I never had the need to add a RTC chip. When the Arduino resets, it returns to the date and time when it was compiled.

If you use a Arduino Due or Zero or M0 then they have their own rtc library.

If you want the computer to send the date and time, then you could make a command and send that via the serial port or via Bluetooth.

What kind of date and time do you want ? The local time, including the offset of the Daylight Saving Time ? That is possible, but not easy to make on a Arduino with RTC chip, in that case it is easier to send a command from the computer with the newest date and time.

It that function okay ? The object 'now' disappeares when the function ends, and yet you return that object.


Wemos mini pro switch power from servo with mosfet bs170

My supposition:

The MOSFET's R(DSON) is too high and causing a large voltage drop.

A servo uses more current than a little LED.  That current passing through the MOSFET, with an R(DSON) of potentially up to 5Ω, reduces the voltage available to the servo, causing it to not work. Further more, ground for the servo is raised up above the real ground level adding an offset into the logic levels that could cause communication issues.

Suggestion: Pick a MOSFET with a lower R(DSON) (ideally measured in the milli-ohms), and a lower V(GS) threshold (something around 1-2V max would be good).


Since you have both a V+ and V- you could just use 2 transitors. If you look at an H-bridge, you only need half the circuit.

The only problem is that you need V- to disconnect the NPN transistor, and the arduino can only go as low as GND. So you'd need a second transistor to drive it.

The same might also be needed for the PNP side, if the arduino voltage is regulated to a lower value than V+.

I found this schematic applicable, but only use the left side. The right side of the motor should be connected to ground (or the middle voltage of your battery). , and replace the opto's with normal transistors.

Come to think of it, I'm not entirely confident about replacing the bottom opto, since battery-negative is below GND in your case. I think it should work, but I'm still quite new to this stuff.

Also make sure you add something like 1k resistors to the base of the transistors (that replace the opto's)


How long will program stay in memory without power?

More than 20 years, and probably more than 100 years.

That's the guaranteed minimum:

  Data retention: 20 years at 85°C/100 years at 25°C(1)

  (1)  Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over
  20 years at 85°C or 100 years at 25°C.


4 Pelteir Plate Water Bottle wired to Arduino Uno

When it comes for amount of power from laptop, then this is not realy reasonable to expect even USB3, maybe some older laptops PCMCIA, or hardware docks. When it comes to Desk, They would have to be adjusted to get the ATX from PSU (it would have to be upgraded for purpose) We are still talking about a small Can or Yacult botle...
Even then insulate, insulate (and same again)
Then its a question of speed and how hot or cold) Battery pack that charges even when not used, used as buffer might work (for a short time).Controlling it from Arduino is easy part using function that switches one on other off whenever you want and then calling the function itself to make sure both steps happen, rather then manualy editing or using one output for controlling power on/off and another on two way relay switching between sets (relay would increase consumption here).


Is it possible to add an additional board on Arduino Web Editor (create.arduino.cc)?

No, there isn't.

The web editor is completely closed. It's a service run by Arduino, and as such it will only support Arduino's own boards.

Two reasons:

Why should they spend the time, effort and money adding support for other people's products?
It adds value to their products to encourage you to use real Ardiuno hardware.

Business is business, after all.


Managing timer intervals using millis at random intervals

I do not really understand your problem. More specifically,
“currentMillis-previousMillisx will always return true” does not make
sense, as it is not a boolean expression (it's unsigned long).

Anyway, the technique shown in blinkWithoutDelay is the way to go. Here
is my (untested) version:

const int relay_count = 4;  // we have 4 relays
const int relay_pins[relay_count] = {2, 3, 4, 5};
const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000};
bool sms_received();  // you implement this one

void loop()
{
    static int current_relay = -1;  // meaning: no active relay
    static unsigned long last_switch;
    unsigned long now = millis();

    // If no relay is active, wait for an SMS.
    if (current_relay == -1) {
        if (sms_received()) {
            // Switch on first relay.
            current_relay = 0;
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }

    // Otherwise, switch relays when it is time to do so.
    else if (now - last_switch >= durations[current_relay]) {
        digitalWrite(relay_pins[current_relay], LOW);
        if (++current_relay == relay_count) {
            current_relay = -1;  // no active relay
        } else {
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }
}

BTW, you did not specify what should happen if you receive an SMS while
one of the relays is active. I assume the SMS are only acknowledged when
no relay is active. Otherwise you would have to change the code.


The following code will pause (Give some delay) when it runs for the first time and also when you press the button.

void loop() {
  static int status = true;
  if(status){
    //Pause
    delay(15);
    status=false;
    return;
  }

  if(digitalRead(switch_pin) == LOW){
    digitalWrite(led_green_pin,LOW);
    digitalWrite(led_red_pin,HIGH);
    lastMotionState    = currentMotionState;
    currentMotionState = digitalRead(MOTION_SENSOR_PIN); //
      if (currentMotionState == LOW && lastMotionState == HIGH) {
        servo.write(90);
      }
      else if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
        servo.write(0);
      }
  }
  else{
    status = true;
  }
}

Give delay according to your need.


Using AA batteries to power Arduino and GPS unit

I suggest using 6 or 8 AA's (eg 6 alkalines or 8 NiMH) and a  MP1584EN DC DC Power Stepdown Buck Converter (about a dollar on ebay, 1.5 to 3 times that on Amazon).  Note, the hole pattern does not match up with breadboard spacing:

The batteries would tie in via a couple of diodes (preferably Schottky), as shown below.  When the 12 V supply is off, the converter would be powered by 9.6 V from eight rechargeable AA's.  When the  12 V supply is on, no current is drawn from the AA's.  The converter output should be adjusted to 5V before being connected to the Nano or other devices it powers.

Using a buck regulator has two advantages vs a linear regulator: battery current is lower (allowing the battery pack to be more efficient as it discharges) and less energy is wasted as heat.

Note, it might make sense to remove the power LED from the Nano, to save 3 to 5 mA of current.

simulate this circuit – Schematic created using CircuitLab


SoftwareSerial together with AltSoftSerial and HardwareSerial

in short - Yes. The following compiles and should work

Note the following links detail some subtle issues about HOW to use these various libraries. Some are more optimal depending upon your usage.

http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html#speed

http://forum.arduino.cc/index.php?topic=152122.0;wap2

You might also want to consider just using either Alt or Soft.
Note that NewSoftwareSerial is incorporated in the IDE 1.5.5+

/*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>

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

AltSoftSerial altSerial;
// AltSoftSerial always uses these pins:
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Arduino Uno        9         8         10

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());

  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}


I have a lengthy reference question about SPI which may help you.
To transfer outwards you do not need to use an interrupt. Nor is it polled. The data is simply placed in the SPI register and the hardware clocks the data out at the defined SPI rate.
To transfer inwards you are just reading the register. However to know when you need to read it, you would probably put the reading inside an interrupt routine.
I suggest you read the link above, and then if you want, you might expand your question more.
The source for the SPI transfer which I think applies to the Atmega2560 is as follows:
// Write to the SPI bus (MOSI pin) and also receive (MISO pin)
  inline static uint8_t transfer(uint8_t data) {
    SPDR = data;
    /*
     * The following NOP introduces a small delay that can prevent the wait
     * loop form iterating when running at the maximum speed. This gives
     * about 10% more speed, even if it seems counter-intuitive. At lower
     * speeds it is unnoticed.
     */
    asm volatile("nop");
    while (!(SPSR & _BV(SPIF))) ; // wait
    return SPDR;
  }

You can see that there is brief polling (the "while" line) for the register which the processor maintains to show whether the transmission has ended. Then the register is read and returned. So yes, there is polling there.
Now if you use an interrupt (see link above) then you will know that the flag has been set, and therefore there will be no delay (in the polling).


By best attempt to provide something of an answer.
You have said:

PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);

That is not literally represented in your code, so I take your question to refer
to:
int dist2 = dist1.toInt();
...
PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > (dist2 * 1710));

or a similar section.
When you execute this PT_WAIT_UNTIL, dist2 contains whatever value you initialized it with in int dist2 = dist1.toInt();   Assuming the condition isn't met, you are exiting runCommand() by way of PT_WAIT_UNTIL's return PT_WAITING;
#define PT_WAIT_UNTIL(pt, condition) \
  do {                               \
    LC_SET((pt)->lc);                \
    if(!(condition)) {               \
      return PT_WAITING;             \
    }                                \
  } while(0)

The LC_SET here in PT_WAIT_UNTIL is being used to generate a label that can be jumped-to later:
#define LC_SET(s)                                \
   do {                                          \
     LC_CONCAT(LC_LABEL, __LINE__):              \
     (s) = &&LC_CONCAT(LC_LABEL, __LINE__);      \
   } while(0)

Later when you later call runCommand to resume the thread, you execute LC_RESUME by way of PT_BEGIN(pt);
#define PT_BEGIN(pt) { char PT_YIELD_FLAG = 1; LC_RESUME((pt)->lc)
...
#define LC_RESUME(s)        \
  do {                      \
    if(s != NULL) {         \
      goto *s;              \
    }                       \
  } while(0)

goto *s here is ultimately jumping to the label created by your use of PT_WAIT_UNTIL.
You are now back in PT_WAIT_UNTIL checking the condition with the line if(!(condition)).  That is, you are checking millis() - lastTimeBlink > (dist2 * 1710)  However, what you are probably (more on that below) doing here is reading junk off the stack.  dist2 was initialized on a previous execution of runCommand and its effective lifetime ended when you returned in PT_WAIT_UNTIL on that prior execution.  On this new execution dist2 is uninitialized because you have jumped over its initialization.  If you turn the warning level up in File/Preferences you should see something for this.
A number of things can happen at this point, most of them not good.  I can't say what the compiler's optimizer will do to this code for certain, but not much would surprised me.  It seems likely, just on familiarity with optimizing compilers and what your code looks like, that it is generating code to read dist2.  That may  sound like a given, but it isn't when you're doing something undefined.  It's possible dist2 has the value from a previous run where you're executing this function in a loop.  But it could also have value that makes dist2 * 1710 evaluate to a duration of up to nearly 50 days, causes PT_WAIT_UNTIL to return from runCommand for so long as you're testing.
Generally, if you're going to use these proto-threads you're going to have to be very careful in thinking about what's actually initialized and what just looks like it is.  If you have a PT_whatever between a non-static local variable initialization or assignment and code where it's used, that's something to examine.


The physical construction of the card and socket are designed such that power to the card is cycled properly when the card is inserted and removed. The only thing the firmware has to do is to stop writing to the card before it is removed.

Unexpected removal can cause a problem in "larger" systems (e.g. cellphones or PCs) because they may have structures open on the card that are not yet complete, but small embedded systems typically do not have the capability to do so and so once all writes are completed the card can be removed.

Detection of non-presence of a card is another issue though, and the firmware will have to be designed to not fail in such a situation.


No, it is not compatible.  It uses the ENC28J60 chip from Microchip, whereas the others all use the W5100 Wiznet chip. A very different chip.

You can use it if you refactor all your code to use the Ethercard library instead of the Ethernet library.

There are cheap Chinese (or other far east) clones of the Ethernet Shields, that use the W5100 (or a counterfeit copy) that people have varying amounts of luck with if you really need W5100 compatibility. I have one, but have had problems with it starting up properly sometimes and needs a bit of a kick with the reset button.


Improve sampling speed while using a multiplexer

It's hard to offer much more than speculation without knowing more about the sensors and your current code, but here is one possibility:

If the bulk of your loop time is the sum of the conversion times, is it possible to cycle through the sensors twice, once to start each conversion (so they will convert nearly simultaneously), wait one conversion-time (or for the first sensor to complete), then cycle through them again to read back each converted value?

for each sensor,
  setup mux;
  send start conversion command;
end

for each sensor,
  setup mux;
  while conversion not done,
    ;  // wait
  read and store value;
end

For 16 sensors and assuming the conversion time the majority of the time spent, that could speed your sample rate to ~100Hz. Expect maybe half of that, since mux-setup and communication times are probably not negligible.


Does LabVIEW Linx affect the communication speed with Arduino?

For specific timing requirements, my recommendation is to write your own Arduino code.

The Linx module deploys its own ino program to the Arduino and uses serial IO to send it commands and receive data from it. Open NI I/O Trace to observe that traffic.


Programming stepper motor move a fixed step till it reach the target

I would start with the Blocking example provided with the library. Add the delays you need, the steps/distance you want. The following is simple but crude. It is call blocking code. It can only do the following sequence, but sometimes that is good enough.

A bit better would be to have a conditional loop to get to the final target. The loop would move 200, then delay 1 second, subtract the amount moved. Loop until you use up all the required distance. But initially I suggest to keep it simple and just make it work with inline sequences.

#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
void setup()
{
    stepper.setMaxSpeed(200.0);
    stepper.setAcceleration(100.0);
}
void loop()
{
    stepper.runToNewPosition(0);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
}


The Arduino Uno is not really designed for that. Simply keeping the power indicator LED, regulators and extra circuits on for a week will require in the order of 1500-2000 mAh (10*24*7=1680mAh). That is without any application at all on the MCU.

Now it is possible to modify the board and reduce this extra power requirements to less than 1 mA and as low as 0.1 mA. Or even better buy a Pro Mini clone and cut the wiring to the LED and regulator, and power with a 3.7 V/1500mAh battery directly.

Here is a great reference on the subject.

Cheers!


I can't upload sketches to my Arduino 101

It's hard to tell, but you can try a lot of options:

Use another USB port
Use another USB cable
Reinstall the Arduino IDE
Remove the device in the device manager and try reinstalling the Arduino IDE again
Try another Arduino (to see if the USB/install is ok)
Try on a different computer/laptop


Sorry for the delay. I posted this question on the EE board as suggested and forgot to come back here and close this out. It was an issue with the fuses. My initial attempt to setup the 16u2 missed the step where I was supposed to change the fuses. I thought this was accomplished when loading the firmware, but was mistaken.


Arduino Uno suddenly not recognized in Windows 8.1 (code 43)

Something is shorted out.

When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.

When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.

You can think of power supplies as having a very small internal resistance (R_p), and the board as being a resistive load (R_b). This forms a voltage divider, but because R_b >> R_p the voltage seen by the board is basically the same as that of the power supply. With a short, R_b is often < R_p, and thus the voltage seen by the board is much lower than the power supply voltage.

The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. Note: The component will get hot enough to burn your finger after a few seconds. One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.

If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.

Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.


What is the minimum wattage of resistors for breadboarding with Arduino Uno?

The answer is: It depends what you want to use them for.

You need a wattage that is higher than the power it will dissipate. What that power is depends on what you are doing with them.  There are standard formulae that tell you the power in any given situation.

For instance, if you know the current and the resistance you can use:  P=I²×R. If you know the voltage across the resistor it's P=V²÷R.

Take as an example the common resistor for an LED.  Assume a 2V LED and a 220 ohm resistor. With a 5V total voltage the voltage across the resistor would be 5-2=3V. So the power would be (3²)/220 = 9/220 = 0.041W so you could quite happily use a 0.125w (⅛w) resistor for that job.

To be honest though most common Arduino jobs can be accommodated by ⅛W or ¼W resistors.  ¼W is better for breadboarding since the leads are fatter than ⅛W, but ⅛W can take two leads at once direct into an Arduino's headers. Also if you fold the leads in half and squash them with pliers they fit better.


Bluetooth has two ways of dealing with device names. A device can optionally choose to advertise its device name. It also has to respond to a "get device name" request. The former is passive, and is what you normally see when scanning. The latter is active and requires you to connect to the device and make a request. If the device doesn't advertise the device name then the only way you can get the name is to make a GATT "Name Characteristic" request to the device. The ESP32 doesn't (AFAIK) do that automatically because these things are designed to be "light weight". Your heavier-weight "reference" software can go off and do more things because it's a full-blown application.

You can sometimes see the difference in the devices because your reference application might populate the list of devices with a combination of MAC addresses and names, and then replace the MAC addresses with names in a later step. Also it probably caches names that it has queried in the past.


I Have found the answer (by mistake)
i have added the includes to Boiler.cpp file

#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
.
.
.
#include "Boiler.h"

RF24 radio(7, 8);                                   // Init RF24 Radio
RF24Network network(radio);                         // Init RF24 Network
RF24Mesh mesh(radio, network);                      // Init RF24 Mesh

Boiler::Boiler(int pin ,float Rev , String Last )
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

void Boiler::init( char nodeID)
{
    _nodeID = nodeID;
    // Connect to the mesh and set Node ID
    mesh.setNodeID(_nodeID);
    if (_DEBUG) Serial.println(F("Connecting to the mesh..."));
    mesh.begin();

    // init LCD and print init data on LCD
    myGLCD.InitLCD(60);                         // Init LCD 55 contrast
    myGLCD.setFont(SmallFont);                  // Set small font
    myGLCD.clrScr();                            // clr screen
    myGLCD.print("Boiler Device",0,0);          //Print init Data on screen
    myGLCD.print("Rev :" , 0 , 10);
    myGLCD.printNumF(_rev,1 ,35,10,'.',1,'0');
    myGLCD.print(_last,0,40);
    myGLCD.update();                            // Update display

    turnOff();
}

and now it compiles ;-)


See my page about switches. Judging by your very-hard-to-read diagram, you have just connected the switch to an input pin like this:

That will not give a positive reading either way because it is "floating". You should connect a pull-up or pull-down resistor, like this:

Now if the switch is open, it is pulled-up to 5V by the resistor and the input will read HIGH. When the switch is closed the switch conducts and "overpowers" the resistor, and it would read LOW.

An alternative is to use a pull-down resistor like this:

That reverses the sense of the switch. When open it will read LOW and when closed it will read HIGH.

I hope you have a resistor in series with the LED.


Looking at the source code of the Arduino IDE on github, it looks like they call an executable (listComPorts.exe). So I would guess you can't get that info through serial.

Here's a C# app using WMI that can get port, vid, and pid:

namespace PortTest
{
    class Program
    {
        // Helper function to handle regex search
        static string regex(string pattern, string text)
        {
            Regex re = new Regex(pattern);
            Match m = re.Match(text);
            if (m.Success)
            {
                return m.Value;
            }
            else
            {
                return null;
            }
        }

        static void Main(string[] args)
        {
            // Use WMI to get info
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");

            // Search all serial ports
            foreach (ManagementObject queryObj in searcher.Get())
            {
                // Parse the data
                if (null != queryObj["Name"])
                {
                    Console.WriteLine("Port = " + regex(@"(\(COM\d+\))", queryObj["Name"].ToString()));
                }
                //PNPDeviceID = USB\VID_1A86&PID_7523\5&1A63D808&0&2
                if (null != queryObj["PNPDeviceID"])
                {
                    Console.WriteLine("VID = " + regex("VID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                    Console.WriteLine("PID = " + regex("PID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                }
            }
            Console.WriteLine("Done");
            int c = Console.Read();
        }
    }
}

From there, it looks like it searches an online database for more info. See: getBoardWithMatchingVidPidFromCloud() function.


Heart Pulse sensor analog value doesn't change even if sensor pressed by finger

Why my pulse sensor is unable to detect beats?
Chances are something wrong.  The only way to tell what specifically is to keep debugging.  If you don't have access to an Oscilloscope or Multimeter, this will involve checking your wiring and altering code.  To check wiring, make sure:

Minus (-) is to ground
Plus (+) s to your + voltage
S is to the A0.

Is my pulse sensor a clone or not?
It is likely.  Open-Source Hardware tends to have many clones.
If it is a clone, can it be fixed somehow?
Clones sell repeatedly if they work.  There is little point making a clone sensor that does not- if scamming was the point, one could ship empty envelopes.  If two different people make the exact same electronics, we hope that they behave very similarly regardless of who made them.
Do I need to buy another one?
Possible but unlikely.  If you can prove your sensor is defective, a seller might be willing to ship a replacement.
Try the following code to test the sensor.  My guess is that you are missing something due to Serial spamming.  Beyond that, taking a pulse may be tricky - the unskilled can easily pronounce some of the living as dead from just the wrist.  I suggest putting it to your throat to be on the safe side.

int minSV;
int maxSV;
unsigned int Frame;

void setup() {
 minSV=500;
 maxSV=0;
 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);
 if(sensorValue > maxSV) maxSV = sensorValue;
 if(sensorValue < minSV) minSV= sensorValue;
 Frame = Frame +1;
 if(Frame > 10000) //would be 1s if frame takes 0.1 ms
 {
  //might want to reset min and max here after debug is complete and sensor is verified to work.  Until then, reset the arduino to reset min and max.
  Frame =0;
  Serial.print("Min: ");
  Serial.print(minSV);
  Serial.print("; Max: ");
  Serial.println(maxSV);
 }
 // removed: delay(1);        // delay in between reads for stability
}