about how to share one External serial EEprom using two microcontrollers?

You didn't show us a complete, minimal, compilable example, so my answer will only cover some important points.

Your indention is way off. It is important to use the correct indention, since it help structure your code and will let you quickly see misplaced brackets. The Arduino IDE even has an autoformat function for this.
You are configuring and checking always the whole PORT A, but you have only connected one of the pins. When you configure the whole port as input (without pullup), the other pins will be floating. Also, if both devices have the pin on input (no pullup), this pin will also be floating. The check cannot work this way. You should only look at the first bit in the port registers, since that is the pin, that you connected. You can set all other bits to zero when reading, by performing a bitwise AND operation: if(PINA & (1<<PA0)). This will execute, when the first bit of PINA is 1. To set a single bit you can use the bitwise OR: DDRA |= 1<<PA0; will set the first bit of DDRA. To erase only that bit from the register, you can use DDRA &= ~(1<<PA0);. The rest of the port will stay untoched with this.
Your current protocol is, that the first MCU will check for LOW, do it' transmission, then drive the pin actively HIGH as a signal for the second MCU to start transmitting. The second MCU will do it's I2C stuff and then drive the pin actively LOW. So now we have an active LOW and active HIGH on the same pin, which in principle is a short. A rather big amount of current will flow from one MCU to the other, most likely destroying at least one of the pins (meaning the output hardware in the MCU, that serves that pin). To avoid this, you can use a principle like that, that the I2C port uses: Open Drain logic. You can start with the first MCU's pin configured as OUTPUT LOW, while the other is INPUT PULLUP. LOW means the first MCU can work. If the first MCU want's the second MCU to do a transmission, it will release the line by setting the PIN to INPUT PULLUP. The second MCU now sees a HIGH level on it's pin and starts it's transmission. When it is finished, it will drive the line actively LOW for a defined duration (enough for the first MCU to react) and then to INPUT PULLUP again. The first MCU will then see a LOW level on it's pin as a signal, that the second MCU is finished. It then itself drives the line actively LOW. Then the play starts again. The important thing is, that a HIGH state is only done by a pullup, not actively driven.

That said, I still don't see the necessity to share an external EEPROM for this use case. You are overthinking the problem. You wrote, that you don't want to miss a frame, if the second MCU is still processing the last frame. There are better ways to do that (especially when you consider the limited lifetime of EEPROM).

You didn't tell us, why you are using 2 MCU's, so maybe your goal can be reached with only 1 MCU, which will eliminate the whole need for transmission.
You could use another UART interface via SoftwareSerial or it's sibling libraries to let the MCU's communicate directly. "Not missing a frame" will still be the case, when you are not disabling interrupts. The library will read the data into a buffer in interrupts, while you are processing the previous frame. Depending on how much data you send, you might want to make the buffer bigger, but that is a simple change in the libraries definitions.
If you want to use I2C to communicate between both MCU's, you have 2 ways of doing it. You can either go the same way as described above for UART, by just letting it fill a big enough buffer, or you can do this through the bus transmissions. The first MCU would be the master, that tries to send the data to the second MCU (slave), when there is new data available. The slave will receive the data normally. When the frame is finished receiving, the slave can leave the bus, until it is finished processing. So, when the master tries to send more data in this time, the transmission will fail at the start, since no slave with that address is on the bus (the slave MCU left the bus for this period of time). You can check the return value of Wire.endTransmission(), which will reflect the corresponding error code. If this error code is returned, the master should wait a bit and try to send this frame again, until it is received successfully. That also means, that the master needs a big enough buffer for storing new data, while waiting for the slave to be ready. Or another way: The master can request 1 byte from the slave, that indicates, if the slave is ready for new data. If not, the master will wait a bit and ask again. If yes, it will transmit the data.

Note: Either way the frequency of data reception and processing must be equal for continuous operation. The whole chain will be as fast as the slowest part. If you receive data faster, than it get's processed, the buffer will fill up fast, until you really have to drop frames. The prinicples above are more about the case, when the processing and receiving may misalign or vary a bit, but at the average staying at the same speed. And for this simple communication buffers, that all communication libraries use, with enough space for maybe 2 to 4 transmissions (depending on the variation) are way enough.


LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch

Yes, the pins can be different depending on the LCD and the controller. My favorite solution to this is to run a simple "i2c guesser" sketch that can be downloaded from the following forum thread (download link is at the bottom of the first post):
http://forum.arduino.cc/index.php?topic=260510.0

With that sketch it usually only takes me a couple minutes to find the correct pin numbers.


Proximity sensor without proximity sensor; is my hand magic, my competency crap, or my arduino fried?

Nothing's broken; you have discovered  the nature of a floating pin.  Unfortunately, that means that strange things happen...

A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set.  To fix this, you need to add a pull-up or pull-down resistor (or activate the internal input-pullup resistor).

You can read about how to accomplish this here.


how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees

There is not enough information about your stepper motor, so let's assume some: let's use stepper motor with 1.8 degree per step (very popular step motor), and we will drive without any microsteps.
To accomplish the task you would need:

Arduino,
stepper motor,
stepper motor driver (like EasyDriver or some kind of Pololu drivers)
power supply. To avoid interference I would suggest powering up your Arduino with PC (through USB port) and additional, powerful PSU for the motor/motor driver only.

Now, you would need to provide at least two signals from Arduino to stepper driver (what I am saying here is example of EasyDriver). The signals named DIR and STEP. DIR selects the direction of the motor to spin. Depending of the stepper motor to driver PCB connections you may have clockwise spin when signal is in one state and counterclockwise when DIR is in opposite state. STEP accepts pulses to move the step motor. Driver moves the stepper motor when STEP input sees raising edge. One raising edge equals to one step = 1.8 degree (again, this apply when you do not use microstepping). To spin motor 180 degrees you need 100 steps.
To summarise:

Use two ports (simplest solution here with EasyDriver): One defined as DIR, other as STEP.
DIR low (selecting one of directions)
STEP pulse 100 times (step motor rotates 180 degrees)
pause (for whatever needs to be done)
DIR high (opposite direction to rotate back)
STEP pulse 100 times (stepper motor rotates 180 degrees to initial position)


How to measure total energy usage of an arduino board

In order to calculate the amount of energy you have to calculate the power first.

The relation is

Energy = (Power * Time of usage)

How to calculate the power?

The voltage for each device in the system is constant. What changes is the current withdrawal in each component in the project.
The main thing you have here is the pump and how much does it consume current.
Usually, you will have on the "plate" of the pump the current withdrawal of it.

Say it consumes 2 Amps.
If that is not available there, use a DMM "Digital Multimeter" and connect in series with the pump and measure the amount of current.

If there are any other major/important components in your project just calculate the current withdrawal from them.

Now add up all the currents and say you ended up with 2 Amps.

If all the components are operating at the same voltage, just multiply the total amount of current withdrawal by the voltage.
WHY?
Because:
P(power) = V(voltage)   * I(current)

If not, just find the power of each component.
Add up all the powers of all you components.

Now you will only have to calculate the energy.

E(Energy) = Power * time

Time here refers to how long is your system working?
Is it a full day, couple of hours. IT doesn't matter. Usually to make things easier use time (in terms of hours).

Say your power ended up with 3kW kilo Watt
You've run the system for 2 hours every day
Energy = 3 * 2 = 6 kWh

If you've kept this for a full month.
Energy save in a month = 180kWh.

Just find out how much do the ministry cost for each kWh, and you'll know how much money you've saved!


The device you pictured seems to be a switch-mode power module which will output 10V DC. Get rid of it before you do any damage.

You don't post any link to data, but I assume you mean the Transducer needs 10V peak-to-peak.

This can easily be accomplished by using 2 digital outputs, connected to the transducer, and driven in anti-phase.

The answer to Push-Pull tone code may be an answer to your problem, but may be overkill. If you just want to output a single tone it is easily done with simple code.

I don't know why you think the transducer outputs 50dB. If it really is doubling the drive voltage will only give 56dB.


Arduino shuts off and doesn't turn on after couple hours

I assume your charger is connecting to the USB port of the Mega2560.

That USB port has a polyfuse (actually a special type of positive-coefficient thermistor) which is normally rated at around 500mA (polyfuses are a bit woolly with their ratings since they are heat based).

If you are drawing near that limit of current the fuse will be gradually heating up. I would think that after 10 hours it may have reached its threshold temperature and thus switches the power off.

Disconnecting the power and allowing it to cool down would then make the board work again.

How can you test it?  Well, next time it switches itself off try bypassing the polyfuse (tweezers would be good to do that with) to see if the power LED turns on again.


Yes, it is (or at least WAS possible a few years ago) to have an ESP8266 self-program if you can get the file onto the file system, by using the Update core that is used by OTA and httpUpdate. This was a example program to do it, but I don't know if it still works. I would also suggest that you look at using LittleFS instead of SPIFFS as the latter has been depreciated.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <FS.h>

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

  SPIFFS.begin();
  Dir dir = SPIFFS.openDir("/");

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, LOW);

  File file = SPIFFS.open("/firmware-update.bin", "r");

  uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  if (!Update.begin(maxSketchSpace, U_FLASH)) { //start with max available size
    Update.printError(Serial);
    Serial.println("ERROR");
  }

  while (file.available()) {
    uint8_t ibuffer[128];
    file.read((uint8_t *)ibuffer, 128);
    Serial.println((char *)ibuffer);
    Update.write(ibuffer, sizeof(ibuffer));
  }

  Serial.print(Update.end(true));
  digitalWrite(BUILTIN_LED, HIGH);
  file.close();
}

void loop() {
}


The first thing to try is to use the 'proper' pins for the SPI:

SCK to Pin 10 on Arduino ---> Pin 13
CS to Pin 11 on Arduino ---> Pin 10
MISO to Pin 12 on Arduino ---> Pin 12
MOSI to Pin 13 on Arduino ---> Pin 11
VCC to 3.3V source on Arduino
GND to Arduino Ground

Try that first and see how you get on.

By the way, just thought I'd mention, probably worth just following the Adafruit example word for word as I'm guessing your board is pretty much a good fit for this tutorial:

https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial

good luck getting it rockin' ;)


I2C communication between 2 Arduinos with updated wire library

The problem I see is the Arduino 101 uses an Intel microprocessor (Curie) instead of an Atmel microprocessor.

The only information I could find is on the Arduino page for the 101, which mentions it has dedicated pins for I2C, but it also says that you can use the Wire library. Maybe you just need to update your IDE?

I'd help more, but I can't seem to find any useful information on the Curie...


Arduino controlling a heavy solenoid water valve

I have setup Arduino UNO and succeeded turning solenoid on when pot soil moisture dry, I was adding rain sensor when I mistakenly disvmcoonected the diode it fried my board, but atleast I had it working . I am using 24 volt normally closed solenoid , since I was monitoring over web I also had ethernet shield attached. And I was powering over ethernet using splitter and extracter.

The vin should only feed in 3.3 volt which you can get using stepdown buck converter , and use remains power to connect to solenoid. The transistor should be on the ground same as arduino nano the ground
The top became messy later


We work with Proculus displays, and we are a distributor of this display here in Brazil (Victor Vision). The display is great, very professional. Used in medical equipments, and cheaper than Nextion.
They are starting now in the web and selling in Alibaba.


Install Arduino SAMD Boards (32-bits ARM Cortex-M0+) board (using "Tools" -> "Board" -> "Boards Manager" menu).

Just search for "SAMD" in the search bar, choose the latest version and install.


What's a good alternative to an Arduino Nano that can be used with Neopixels?

ESP8266 mini is the best and cheaper alternative 2$5 on Ali express. Then 100% compatible with arduino toolchain/IDE + very impressive community/github library!


OMG, I was stupid. I can just place millis in this while condition.


7segment blink when the button is pressed

A simple solution would be to not worry about blinking as a piece of code, ie. remove those delays (I hate blocking code) and instead, if you are currently receiving a signal from the remote, do not display any number (or display your num00). Once the value is received and processed, then display that number.

This way, whilst ever the remote button is down, the display will blank out, and the number will appear as soon as the number is released. If it's the same number, then you will see the number, see a blank display, and then see the same number again. Obviously, if it's a different number, the new number would be displayed.

Since most people would only press the remote button for 100-1500ms, it should give you a nice delay anyway.

Finally, you may encounter some flashing if you process the data so quickly and the remote auto repeats. This could be handy if that number is processed multiple times by the receiving unit. The flashing would indicate that that is the case. If that is undesired, implement a simple state machine.

edit: your pastebin code came up whilst I was writing this answer. Having a quick look at your code, I would suggest that in the section:

if (irrecv.decode(&results)) {
  //receiving data? display nothing
  on(num00);
  digitalWrite(ledPin, HIGH);
  Serial.println(results.value, DEC);
  irrecv.resume();
  delay(100);
  int oldvalue = results.value;
  switch(results.value){
    case 16738455:
      Serial.println(0);
      num2display=0;      // make sure to declare this var somewhere
      //if (oldvalue == results.value){
      //  on(num0);
      //  delay(1000);
      //  on(num00);
      //  delay(1000);
      //} else {   // I think you missed an else here
      //  oldvalue = results.value;
      //}
      //on(num0);
      //delay(1000); // you don't want such large blocking delays
      irrecv.resume();
      break;
    case 16724175:
      Serial.println(1);
      num2display=1;       // add this for each section
      irrecv.resume();
      break;
      . . .
  }
}
else{
  digitalWrite(ledPin, LOW);
  on(num2display);
}

you only set the variable to be displayed, but display num00. Then in the else, you can display that number


In the Arduino world, a servo motor is a RC servo motor. It runs at 5V or 6V and most of them can rotate 180°.

In an industrial environment or with the central heating in a house, the valves are often 24V AC. The most common voltages are 12V and 24V, and most of them with work with DC as well.
Sometimes the term "servo" is used for them, that is for example for a controller for valves with multiple positions.
To control them with an Arduino, the easiest way is with a number of relais.

Some intelligent valve controllers have an input signal. That is the one that you have.
The link to that datasheet is for a valve controller for 24V or 230V AC mains voltage. It has inputs to control it. Depending on the type, the input signal can be 0...5V, to 10V or to 20mA. Which one do you have ?

When that valve is in a central heating, it is possible to cause damage. First of all the central heating is tuned to the house. The valves work together with the pump, and not every system has a automatic overpressure-loop-valve.


Protocol options for data exchange between Arduino and ESP8266

Most I2C tutorials made each Arduino a slave and master, but this approach is better, because each Arduino is either a master or a slave (not both) and no switching is needed. That makes things easier.

I2C is better than serial, because you can add more Arduinos in the same bus.

I have implemented I2C between two Arduinos and it's not more complicated that reading/writing to the serial port (which you have already done). And I bet you can generalize your serial port code to work with both serial and I2C comms.

This is my example (just a proof of concept). The slave Arduino controls a some pins, a temp. sensor and a watchdog under orders from the master Arduino. If slave doesn't receive a beat in time, it reset the master Arduino.

Master code

#include <Wire.h>

#define CMD_SENSOR    1
#define CMD_PIN_ON    2
#define CMD_PIN_OFF   3
#define CMD_LUMEN     4
#define CMD_BEAT      5

const byte SLAVE_ADDRESS = 42;
const byte LED = 13;

char buffer[32];

void setup ()
{
  Serial.begin(9600);
  Serial.println("Master");

  Wire.begin ();

  pinMode (LED, OUTPUT);
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Serial.println("Send LED on");
  Wire.write (CMD_PIN_ON);
  Wire.write (2);
  Wire.write (10);
  Wire.endTransmission();
  int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
  Serial.print("status=");
  Serial.println(x);
}  // end of setup

void loop ()
{
  Serial.println(".");
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_SENSOR);
  Wire.endTransmission();
  int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
  Serial.print("Disponibles = ");
  Serial.println(x);
  int temp = (int) Wire.read();
  Serial.println(temp);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_LUMEN);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ADDRESS, 2);
  int light = Wire.read() << 8 | Wire.read();
  Serial.print("Light=");
  Serial.println(light);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_BEAT);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  delay (5000);
}  // end of loop

Slave code

/*
   Esclavo I2C

   Recibe los siguientes comandos
   <- 1° byte -> <- 2° byte -> <- 3° byte ->
   CMD_SENSOR
   CMD_PIN_ON    n° de pin     duracion en segundos
   CMD_PIN_OFF   n° de pin
   CMD_LUMEN
   CMD_BEAT

   Cada comando recibe una respuesta, ya sea el valor pedido
   o un status.
*/
#include <max6675.h>
#include <Wire.h>

typedef struct {
  int pin;
  unsigned long off;
} PIN_PGMA;

/*
   Lista de pines que se pueden activar via CMD_PIN_ON.
*/
#define PIN_LUMEN   A0
#define PIN_LED      2
#define PIN_RESET    3
PIN_PGMA pgma[] = {
  {PIN_LED, 0},
  {PIN_RESET, 0}
};
const int pgmaSize = sizeof(pgma) / sizeof(PIN_PGMA);

#define CMD_SENSOR    1
#define CMD_PIN_ON    2
#define CMD_PIN_OFF   3
#define CMD_LUMEN     4
#define CMD_BEAT      5

#define ST_OK         0
#define ST_BAD_PIN    1
#define ST_TIME_0     2
#define ST_BAD_LEN    3

#define MY_ADDRESS  42

//  Maximo tiempo de espera entre comandos CMD_BEAT. Pasado
//  ese tiempo, se activa el PIN_RESET.
//  En milisegundos.
#define BEAT_INTERVAL 10000
unsigned long lastBeat;
//  Largo del reset en milisegundos.
#define RESET_LENGTH  250
byte cmd = 0;
byte status = 0;

int thermoDO = 11;
int thermoCS = 12;
int thermoCLK = 13;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

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

  pinMode(PIN_LUMEN, INPUT);
  analogRead(PIN_LUMEN);

  for (int i = 0; i < pgmaSize; i++) {
    pinMode(pgma[i].pin, OUTPUT);
    digitalWrite(pgma[i].pin, LOW);
  }
  lastBeat = millis();

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveCommand);
  Wire.onRequest (sendAnswer);
}

void loop()
{
  unsigned long now = millis();

  //  Baja la linea de RESET si no ha recibido un beat ultimamente.
  unsigned long diff = now - lastBeat;
  if (diff > BEAT_INTERVAL) {
    resetPin();
  }

  //  Recorre la lista de pines y apaga aquellos cuyo tiempo termino.
  for (int i = 0; i < pgmaSize; i++) {
    if (pgma[i].off > 0 && pgma[i].off <= now) {
      Serial.print("off pin="); Serial.println(pgma[i].pin);
      pgma[i].off = 0;
      digitalWrite(pgma[i].pin, LOW);
    }
  }
}

// called by interrupt service routine when outgoing data is requested
void sendAnswer() {
  byte temp;
  int  lightReading;

  switch (cmd) {
    case CMD_SENSOR:
      temp = thermocouple.readCelsius();
      Wire.write(temp);
      break;
    case CMD_LUMEN:
      lightReading  = analogRead(PIN_LUMEN);
      Wire.write(lightReading >> 8);
      Wire.write(lightReading % 0xFF);
      break;
    case CMD_PIN_ON:
    case CMD_PIN_OFF:
    case CMD_BEAT:
      Wire.write(status);
      status = ST_OK;
      break;
  }
  cmd = 0;
}

// called by interrupt service routine when incoming data arrives
void receiveCommand (int howMany) {
  cmd = Wire.read ();
  status = ST_OK;
  switch (cmd) {
    case CMD_PIN_ON:
      cmdPinOn();;
      break;
    case CMD_PIN_OFF:
      cmdPinOff();
      break;
    case CMD_BEAT:
      lastBeat = millis();
      break;
  }
}  // end of receiveEvent

void cmdPinOff() {
  if (Wire.available() != 1) {
    status = ST_BAD_LEN;
  } else {
    int pin = Wire.read();
    int i = searchPin(pin);
    if (i < 0) {
      status = ST_BAD_PIN;
    }
    else {
      pgma[i].off = 0;
      digitalWrite(pin, LOW);
    }
  }
}

int searchPin(int pin) {
  int i = pgmaSize - 1;
  while (i >= 0 && pgma[i].pin != pin) {
    i--;
  }
  return i;
}

/*
 * Programa el encendido y duracion del RESET.
 */
void resetPin() {
  if (digitalRead(PIN_RESET) == LOW) {
    unsigned long now = millis();

    int i = searchPin(PIN_RESET);

    pgma[i].off = now + RESET_LENGTH;
    lastBeat = now;
    digitalWrite(PIN_RESET, HIGH);
  }
}

void cmdPinOn() {
  if (Wire.available() != 2) {
    status = ST_BAD_LEN;
  } else {
    int pin = Wire.read();
    int len = Wire.read();

    int i = searchPin(pin);
    Serial.print("pin="); Serial.print(pin); Serial.print(",index="); Serial.println(i);
    if (i < 0) {
      status = ST_BAD_PIN;
      Serial.println("bad pin");
    } else {
      if (len == 0) {
        status = ST_TIME_0;
        Serial.println("ban len");
      }
      else {
        pgma[i].off = millis() + len * 1000;
        digitalWrite(pin, HIGH);
        Serial.println("ok");
      }
    }
  }
}


Setting Up a JavaEE app on an Arduino Yun Board

Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has.
Java EE is magnitudes bigger (and bugger) than that.

You might try with Java SE embedded, the smallest profile might fit to 11Mb:
http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf
and then you can roll your own web server.

(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).

What you can try is Raspberry PI, which works well with network, and Java (SE).
Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish_4_on_the_raspberry


The normal way is to use a P-channel MOSFET as a "high side" switch.

simulate this circuit – Schematic created using CircuitLab

R1 keeps it switched off under "normal" circumstances.  Driving D4 LOW makes M1 turn on and allow power through to the "component".

Make sure that the MOSFET has a threshold voltage of no more than (less than?) -3V (that is, somewhere between 0V and -3V - note: P-channel MOSFETs have their thresholds quoted as a negative voltage).

You could connect R1 to 3.3V instead of 5V, but since the  GPIO would have 5V on it when HIGH it would be wasting power while idling - so it's better to pull it to 5V instead.


If the Arduino doesn't show up on multiple computers, and others do, it may be bricked, or dead. You might try reflashing the chip, and hope that solves your issue. If it doesn't, chances are it's toast.

If however the device simply doesn't show up on one computer, but does on another. It's either a software issue, or a USB issue with that computer.

If winblows OS, try reinstalling, or updating the drivers for the USB, as well as the Arduino. And check your power management on the USB as well. I've seen Windows USB poop the bed if a device is connected / disconnected, or restarted several times in rapid succession. When this happens, sometimes Windows will think the port or device is faulty, and simply stop responding to its presence.

If *nix, make sure you've configured it properly.


If you want it really barebones and easy, you can checkout the Arduino "Dimmer" example sketch.

Instead of changing the brightness of an attached pin, you could take the input you send it over the serial console and execute various functions, depending on what you receive.

Something like this:

boolean newCommand = false;
void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);

  // other setup stuff here
}

void loop()
{
  byte command;

  // check if data has been sent from the computer:
  if (Serial.available())
  {
    // read the most recent byte (which will be from 0 to 255):
    command = Serial.read();
    // say that you received a new command
    newCommand = true;
  }

  // is there a new command?
  if (newCommand == true)
  {
    // do something depending on what command you received
    switch(command)
    {
      // if you receive command "1", do something
      case 1: functionWhatever();
              break;  // "break" out of the switch. otherwise it would continue executing the following commands as well
      case 2: functionWhatever2();
              break;
      //for cases that are not caught, send out an error
      default: Serial.write("invalid command");
              break;
    }
  }
}

If you want to use an existing library, you might want to check out:
EasyTransfer.

It can be used for communication between two Arduinos, which you then can use to execute functions on the other side of the line.

The code itself is relatively simple, so you might be able to adapt it to communicate with a processing script on your computer for example.


Analog read negative voltage inbuilt protection

All the IO pins contain a pair of clamping diodes to protect against over-voltage and negative-voltage situations:

As long as the current flowing through one of those diodes doesn't exceed its maximum forward current all will be well and the Arduino won't be damaged. If too much current flows then you will damage the pin.

Since you have 10KΩ resistors, at -5V the maximum current that could flow (assuming a 0.7V drop on the diode) would be (-5 + 0.7) / (10,000 / 2) = -860µA (negative because it's flowing backwards out of the pin from ground to your negative voltage source, not into the pin to ground).

Unfortunately the datasheet doesn't provide a current limit specification for those diodes, but I would expect such a small amount of current to be safe enough.


When the client sends you a request, you should answer only once. Your
root() function attempts to answer twice whenever the request contains
the argument “duty”. The client will not handle a duplicate response to
a single request.

Here is your root() function:

void root()
{
  iso();
  ser.send(200, "text/html", iso());  // ← first response

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());  // ← second response
  }
}

You may notice that the first response was sent before updating the
duty cycle.

The proper way to handle the request is to first handle the request
parameters, if any, then send the response:

void root()
{
  if (ser.hasArg("duty")) {
    s = ser.arg("duty").toInt();
    ledcWrite(4, s);
  }
  ser.send(200, "text/html", iso());  // ← only sent once
}

As a side note, there is absolutely no need to build the response five
times (you have five calls to iso() within root()) when you only
need it once!


Can I connect to a DALI network as a master node using an Arduino?

I have made a simple DALI controller with Arduino Nano. Maybe it will be useful for you. Look here: Simple DALI Controller


From zero to Arduino (maybe a HOWTO someday?)
Rule zero:

Don't overestimate the other Arduino users! They all were not born with this knowledge too.
Never be too shy to ask!
Making mistakes is ok as long as they trigger learning.

(-: short break :-)
You'll find lots of HOWTOs and other tutorials in the wild wild web.
I assume, the confusing thing is to read them in the wrong order.
Forget your Arduino(s) for a while and start with reading about:

General common components (resitors, capacitors...) and when and how to use them...

This will at least partially answer:

Safety rules, what happens when you do something wrong
How to read schematics (different elements that appear there)

If not already done:

Read about ANDs, ORs, NANDs, NORs, FLIPFLOPs...

This will show how their schematic symbols look like.

...compare them to creating the same behaviour by programming (if,
and (&&), or (||), ...)
Have a look at bit operations (&, |, ... on whole number variables.

The programming up to this point can be done on your PC.
After this, dedust your Arduino again and jump into:

What different pins are used for (yeah, even on a more basic level
than arduino documentation)

(Happy end. At least for now.)
(I make this a community wiki answer to invite others to expand this text.)


What is the best way to unit test my code without controller?

You can easily simulate your Arduino code using the famous Proteus ISIS.
You just will have to search for the specific Arduino simulation library for Proteus.

Here you a small tutorial of how to make this thing done:

First, identify the path the Arduino IDE generates the hex file to?
for example if you are using the official IDE you will find the hex file location in the "arduino IDE path/lib/preferences.txt"
Or if you are using Arduino ERW which I recommended the most on windows! So you can simply open the output folder by "Sketch > Copy HEX file as path".

Second, download the Arduino library from Here. Then copy ARDUINO.LIB and ARDUINO.IDX to folder "library" in the install directory Proteus.

Third, open ISIS and you should be able to find the component.

Please find this image of the worksheet after finishing the above steps, and simulation works just fine!

And as a head start for you, please find this small memo I prepared for the Arduino Uno Pins Layout:

0-14: I/O
A0-A5: Analog

We can use analog as digital:
=============================
Pinout:
00: Rx      | Can't be used as I/O if I wrote in the code Serial.begin
01: TX      |
02: Interrupt
03: Interrupt & PWM
04:
05: PWM
06: PWM
07:
08:
09: PWM
10: PWM & SPI
11: PWM & SPI
12: SPI
13: SPI
A0:
A1:
A2:
A3:
A4: TWI
A5: TWI


My original answer was probably over-kill....Just keep track of how many leds are lit:

int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
byte num_leds_lit = 0

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        digitalWrite(ledPins[i], i < num_leds_lit ? HIGH : LOW);
    }
}

Then, on button press, increase the count:

if (num_leds_lit < num_leds) {
    num_leds_lit += 1;
    set_leds();
}

Then to turn the leds off with the other button press:

if (num_leds_lit > 0) {
    num_leds_lit -= 1;
    set_leds();
}

------------------------- Original answer

There are a few ways to do it. One way would be to use a bitmask. I would write a function to turn the leds on/off

// Each bit represents the state of one LED (0 == off, 1 == on)
byte led_bits = 0;
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
// Need a mask to make sure we don't set too many bits
const byte led_mask = 0xFF >> 8 - num_leds;   // 00000111B in this case

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        // Turn on/off based on state of bit
        digitalWrite(ledPins[i], (1 << i) & led_bits ? HIGH : LOW);
    }
}

Then, on button press, set the mask:

led_bits << = 1;          // Shift left (001 -> 010)
led_bits |= 1;            // Set lsb    (010 -> 011)
led_bits &= led_mask;     // Ensure max bits: (1111 -> 0111)
set_leds();

Then to turn the leds off with the other button press:

led_bits >>= 1;          // Shift right (011 -> 001)
set_leds();


Based on your schematic, you need to provide a 3.3v power source to the 3.3v side of the logic level converter. You can use the 3.3v pin on the Arduino.

Also, it's really hard to evaluate your soldering with such a shaky picture. Just make sure none of the pins are connected. A visual inspection usually will do, but if you want to be sure, use your multimeter's continuity function. Test all adjacent pins to confirm they are not bridged.


What you have there is an XBee module. It is designed to plug into an XBee shield which then plugs into the Arduino.

So you need to buy more.

That's the bad news.  The good news is that you have already bought the most expensive part, and the shield to go with it is pretty cheap.

Numerous people make the shields, such as:

Sparkfun
Seeed
DFRobot

Also note that XBees talk to other XBees, so you need at least two of them to get any form of communication going.  If you want to talk to your computer there is a device called the XBee Explorer which plugs into the PC to allow you to communicate with an XBee module.


Trying to track down macro or #define values, possibly in arduino preprocessor

It might help to point out the use of -D switches of gcc here.
If you turn on verbose output of the Arduino IDE (I am using a pretty old version):

you will see, when you compile a sketch, that the compiler is not only called with a switch -m (e.g.  -mmcu=atmega328p) which describes the target (i.e. the ATMEL AVR instruction set or MCU type) for which the code is compiled, but also with a number of -D switches.

The -D switches predefine a name as a macro and also that depend on the target.

You might see for example

-DF_CPU=16000000L -DARDUINO=100

where F_CPU is used to pass information about the target's clock speed (16 MHz in this case) to code that depends on this, e.g. the delay function or the Serial library.

3 ways to define macros

In general, the confusion might come from the fact that including files in the Arduino build chain depends a lot on compiler flags, and there are several ways to define these:

#define
using -D switches
from the target specification (compiler built-in, -m)

The last point means that the above mentioned -matmega328p defines the macro __AVR_ATmega328P__ which is e.g. used in io.h to include the appropriate file with pin mappings, RAM sizes etc. (Google for avr-mcus.def to find a full list of these predefined macros for AVR targets.)

Finally, note that the Arduino IDE also sets include paths depending on the target. The appropriate set of pin definitions is selected by passing an include path like this to avr-g++:

-I/usr/share/arduino/hardware/arduino/variants/standard

where standard is replaced by leonardo, micro, mega etc.

Short answer / summary / how to debug

First, to generate a list of the current #define directives, use the -dM option like this (compiling an empty program that is specified to be C with -x c):

echo | avr-gcc -x c -E -dM -mmcu=atmega328p - | sort

Change -mmcu=atmega328p to your needs (you can also leave it out).

Second, you can use the option -g3 to include the macro definitions in the output. Keep the intermediate files by using -save-temps. You can append these to the compiler call by the IDE:

avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega168 -DF_CPU=8000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build5017602110288.tmp/SerialManual.cpp -o/tmp/build5017602110288.tmp/SerialManual.cpp.o -save-temps -g3

which will create a long output file *.ii (here SerialManual.ii) that lists among others the defines and typedefs and, most importantly, from which files they come.

Sample output:

# 1 "/tmp/build501760211028815624.tmp/SerialManual.cpp"
# 1 "/tmp/1//"
# 1 "<built-in>"
#define __STDC__ 1
#define __cplusplus 1
#define __AVR_ATmega168__ 1
#define __CHAR16_TYPE__ short unsigned int
...
# 1 "<command-line>"
#define F_CPU 8000000L
#define ARDUINO 100
...
# 1 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 1 3
# 34 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 3
#define _AVR_IOM168_H_ 1
#define SPM_PAGESIZE 128
#define RAMSTART (0x100)
#define RAMEND 0x4FF
#define XRAMEND RAMEND
#define E2END 0x1FF
#define E2PAGESIZE 4
#define FLASHEND 0x3FFF
...


How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?

Read the datasheet / programming manuals for the chip. The Arduino Due is arranged to run at 84MHz.

  I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

Install it. The IDE is (fairly) modular these days.

But I have to ask... why do you want to run at 16MHz?


Can I use arduino pro micro rx tx as digital pins

Using TX and RX on a 32U4 does not affect PC communication. It uses a competent different communication channel.
You can use those pins for digital operation with no problems, you just won't be able to use Serial1 for communication with serial peripherals.


You'll need something like the Ethernet Shield to connect your Arduino Uno to a LAN.

As for webserver functionality, the Webserver Example sketch does the bulk of what you need.

For the "access this data through the internet" part, assuming you want access beyond your LAN; you'll need to perform Port Forwarding on your local router (i.e. allow the "Internet" to see your Arduino).

If you need wifi, then personally I prefer the CC3300 to the Arduino Wifi shield.


The backslash in your comments are the problem. As per C++ language definitions, a \ at the end of the line is interpreted as a "line continuation". Thus, your comment gets continued in the next line and your variable declaration and initialization is commented out.

This is apparent when opening your code with a good syntax highlighting program, like Notepad++.

Removing all \\ from the end of the comment line solves your problem.

Side note: For more info, look at https://stackoverflow.com/a/30290133/5296568. Backslashes at the end of a line are actually useful when used in multi-line macro definitions.


LED fade class strobes for unknown reason

I added some Serial.print() statements to your code to point out the bug:

This is the modified LED::changeLed() function I used:

void LED::ledChange() {

  /**/Serial.print(brightness);

  // Flip LED change value between brightening and darkening
  if ( brightness <= lowest || brightness >= highest ) {
    change *= -1;

    isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

    // A 1-in-25 chance to change the fade-rate
    if ( random (25) == 13 )
      changeChange();

  }

  brightness += change; // Adjust the LEDs brightness

  analogWrite( pin, brightness ); // Brighten/darken the LED

  /**/Serial.print("\t+ ");
  /**/Serial.print(change);
  /**/Serial.print("\t= ");
  /**/Serial.print(brightness);
  /**/Serial.print("\t");
  /**/for (int i = 0; i < (brightness / 5); i++) Serial.print("*");
  /**/Serial.print("\n");
}

I marked the additional lines with /**/.

Here is a piece of the serial monitor output, where the bug occurred.  The columns are organised as follows: brightness before the function changed it + change = brightness at the end of this function. The * lines graphically represent the LED brightness (i.e. the last number); this allowed me to run your sketch without a physical LED, at much higher speed (I deleted the delay(60) in loop()).

183        +    3         =    186  *************************************
186        +    3         =    189  *************************************
189        +    3         =    192  **************************************
192        +    3         =    195  ***************************************
195        +    3         =    198  ***************************************
198        +    3         =    201  ****************************************
201        +    3         =    204  ****************************************
204        +    3         =    207  *****************************************
207        +    3         =    210  ******************************************
210        +    3         =    213  ******************************************
213        +    3         =    216  *******************************************
216        +    3         =    219  *******************************************
219        +    3         =    222  ********************************************
222        +    3         =    225  *********************************************
225        +    3         =    228  *********************************************
228        +    3         =    231  **********************************************
231        +    3         =    234  **********************************************
234        +    3         =    237  ***********************************************
237        +    3         =    240  ************************************************
240        +    3         =    243  ************************************************
243        +    3         =    246  *************************************************
246        +    3         =    249  *************************************************
249        +    3         =    252  ************************************************** #####
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************

The bug begins at the line I marked with ####. I'll try to narrate the events from the point of view of your function, starting from line #### (1):

Is brightness 249 in range? yes -> don't invert sign | add 3 | return
Is brightness 252 in range? no -> invert | change fade rate? yes, new fade rate = ±1 | add -1 (we just inverted the sign) | return
Is brightness 251 in range? no -> invert (here's the bug!) | change fade rate? no | add +1 (ve should subtract, but we just inverted the sign...) | return
It continues like that until a fade rate change occurs, oscillating between 251 and 252. That looks out like a constant brightness.
The fade rate increases and the oscillation values change, maybe approaching 255 (if the smaller value goes below 250 the led will continue to behave properly, but that's not our case).
Another fader rathe change causes the program to make brightness greater than 255 (in our case 254 + 2). And if you add 2 to a one-byte unsigned variable holding a value of 254 you won't get 256 (the variable can't hold that value) but 0. That's something called "integer wraparound", as Majenko pointed out in his comment to your question.

So, that was a long description of a very simple problem.
To solve it you cold for instance prevent the brightness value to be greater than 250 and smaller than 5 adding two lines to your ledChange function:

void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    /**/ if(brightness > highest) brightness = highest;
    /**/ else if (brightness < lowest) brightness = lowest;

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}


Websockets with the ESP8266 using arduino uno board

The library you linked is not for Uno with esp8266 module.

It is possible to use the ESP-01 with Uno for WebSockets client for example with ArduinoHttpClient library over the WiFiEsp library.

Better option is to use only an esp8266 development board programmed with Arduino IDE without the Uno.


Digit LED has single input, multiple outputs for each segment. Concerns about "sinking" 5v supply into digital pins

The device you have is a common anode display. This means that the anodes (+ve terminals) of all the LEDs are connected to one common pin (well, 2 pins actually, pin 3 and 8 are connected internally) . Their cathodes (-ve terminals) are what make up the remaining pins. Now, to light up any LED, you need 5 V at its anode and GND at its cathode. You have connected 5 V to pin 3, which stands for the common anode of every LED, so all that is left for any LED to turn on, is for you to connect GND to its corresponding cathode. So when you made all the remaining pins (the cathodes) OUTPUT, by default the Nano sets those pins to a logic LOW (or GND) value, so ALL the LEDs got lit up. Each LED now has 5 - 0 = 5 V across its terminals and is forward-biased.

However, when you write HIGH to any cathode, the potential difference across the associated LED/segment is now zero, because that LED has 5 V at its anode (pin 3/8) and 5 V at its cathode (as a result of writing HIGH), and 5 - 5 = 0 V so it is reverse-biased (at least 2 V or thereabouts is needed for a red LED to become forward-biased) and so the segment turns off. And this is how you control which segment is on at any time: You write a LOW to a cathode to turn on the associated segment, and write HIGH to turn it off. It sounds counter-intuitive but it follows if you think about it. Regarding your question, there's no damage being done to anything; the minimum voltage across the LED is 0 V (well below its maximum peak inverse voltage), while the maximum voltage across the LED is around 2 V, if you use the highly recommended current-limiting resistors (220/330 ohms is good) in series between each cathode and its Arduino digital pin.

Without any resistors, you will be drawing a lot of current through each pin, in total, a lot more than the Nano can safely supply. Use resistors that limit the current through each LED to 10-20mA.


I was able to break the connection with:
AT

The data sheet says to use AT+PWRM1, but it didn't work for me. Instead the above command dropped the connection to the remote device.

From the Datasheet:

Execute “AT+PWRM1” command, Module will auto into sleep mode when
power on or disconnect from remote device.


I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

To give a detailed answer the full prototype for DisplayInfo() is needed. The issue is that the literal strings are const char* and the function parameters are declared as char*.

The correct way to fix this would be to update DisplayInfo() so that the parameter types are const char*. The dirty fix is to cast the parameters in the call.

   DisplayInfo((char*) "RFID Scanner", (char*) "Starting up", HIGH, HIGH);

But I would not recommend that.

Cheers!


Post-split, where do I download the Arduino IDE?

The split is already over. They are working on merging everything that happened during the split, if they haven't already.

I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).


Leostick Receiving message from Uno using USB jumpers cables

I don't think this has any chance of working. You can't use USB to interface between the two devices, as the Leostick can't work as USB host. Your best bet is to use (software) serial.


That while loop makes perfect sense.  It' basically nudging the other end repeatedly until it replies with something - anything.

It's like sitting next to someone and poking them in the ribs every 300ms until they respond to you. Once they have responded you can then react to that response - be that to run very fast or tell them your important news.

The idea of handshaking like that is all to do with synchronisation. It ensures that both ends are ready for communication at the same time.  Once synchronised you know, to a high probability, that what you are sending will be interpreted properly, and any replies you get back will be correct.

For basic communication between two Arduinos it's really not necessary.

The simplest call-and-response protocol involves Arduino A sending a single byte as a request and Arduino B replying with a single byte. It is up to you what those bytes represent, but ASCII letters for requests are ideal since they are understandable by a human, and numbers between 0 and 255 or -128 and +127 fit in to one byte (unsigned or signed respectively). Should you want bigger numbers being sent back then the reply will have to be delimited in some way. The simplest way of doing that is to format the response as ASCII data and send it with a CR and/or LF.

Something like:

if (Serial.available()) {
    char command = Serial.read();
    switch (command) {
        case 'T':
            Serial.println(temperature);
            break;
        case 'P':
            Serial.println(pressure);
            break;
    }
}

The master end then sends either 'T' or 'P' to request temperature or pressure. It then reads characters up to a line feed and stores them in a string which it can then convert into the desired numeric data type depending on what temperature and pressure are (integer or floating point).


Arduino Uno - Variables randomly changing

You are seriously abusing the String class.  There is absolutely no need to use any Strings at all in your program.

For example:

  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

would be better written as:

  if (unitCycle == 1) {
    Serial.println(F("sec"));
  } else if (unitCycle == 2) {
    Serial.println(F("min"));
  } else if (unitCycle == 3) {
    Serial.println(F("hour"));
  } else {
    Serial.println(F("day"));
  }

And:

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

as:

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unitCycle == 1) {
        secCount++;
      } else if (unitCycle == 2) {
        minCount++;
      } else if (unitCycle == 3) {
        hourCount++;
      } else {
        dayCount++;
      }
    }
  }

And then the cardinal sin:

lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));

All that string creation, concatenation, and destruction is just evil.  Instead, use:

lcd.print(F("Sec: "));
lcd.print(secCount);
lcd.print(F(" Min: "));
lcd.print(minCount);


You use type byte for the variable ndx. Type byte is 8 bits, so the max value is 255. The variable ndx is incremented and after 255 it continues counting from 0.


We faced similar problems when using ESP8266 for the first time, Following approach to the problem was fruitful

ESP8266 is 3.3v compatible so to avoid problems make a simple adaptor circuit to make it compatible with 5v Arduino (find details here)
First thing you need to do is check and confirm if you are able to communicate with your ESP module, you can use any USB to TTL interface and connect ESP Module directly with your computer/laptop. (explained in detail here)
Use ESP8266 configuration utility, it will speed up the ESP Module setup and help get the desired product develop faster. (explained in detail here)

Hope it helps.


Monitoring multi analog ports with ACS712 current sensors

First: As written in the comments, your current code will only work once. After the first reaching of the threshold it will permanently stay in the last while loop, since analogValue can never change in there (you don't assign a new value to it). Thus this part should be removed.

To extend your code for multiple sensors, you can organize all the relevant data into arrays, so that you can loop over them. First we define an array of the used analog input pins (together with a define for the array size, so that we can later easily loop over the array and still be able to easily add further sensors):

#define SENSOR_N    2
uint8_t sensor_pins[SENSOR_N] = {A0, A1};

Then we are defining similar arrays for the thresholds and stepper positions:

uint16_t sensor_thresholds[SENSOR_N] = {570, 400};
uint8_t stepper_positions[SENSOR_N] = {90, 180};

Now in the loop() function we can surround the measurement and stepper code into a loop over the arrays. Where you used defines before, we are now using the array elements of the corresponding index:

for(uint8_t i=0;i<SENSOR_N;i++){
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
        analogValue = max(analogValue, analogRead(sensor_pins[i]));
        Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > sensor_thresholds[i]) {
        stepper.enable();  //  energize coils - the motor will hold position
        stepper.rotate(stepper_positions[i]);  //Moving motor using the degree notation in ()
    }
}

Now you still have 2 things to consider:

Depending of the number of sensors, your code currently can take rather long. With lets say 6 sensor, you are measuring for 3s in total at the worst case (when the last machine is turned on). You might want to reduce your measurement duration (500ms is rather long).
You need to add code for defining, what happens, when you turn multiple machines on at the same time. Currently that would lead to the stepper motor going back and forth; surely not what you want. The easiest thing would be to only consider the first sensor, that reaches the threshold, which then gets to set the position ("first" not in chronological sense, but in the order of the pin in the sensor_pins array). You can reach that with a break; command at the end of the threshold if condition.

Notes:

The arrays hold, what they say. sensor_thresholds holds all the thresholds. In my example 570 is the threshold of the first sensor and 400 is the threshold of the second sensor. 90 in stepper_positions is the position of the stepper for the first sensor. 180 is the position for the second sensor.
I used 2 sensors in my example. You can extend that yourself by setting the define SENSOR_N to the number of sensors and adding elements for every sensor into the arrays.
uint8_t and uint16_t are unsigned integer types with the mentioned number of bits: uint8_t has 8 bits (1 byte), uint16_t has 16 bits (2 bytes). uint8_t is the same as unsigned char or byte. uint16_t is the same as unsigned int on the Uno/Nano. I used these types, because it is a good practice to use types, that have the same size on every platform. When changing to a different platform, types like unsigned int might have a different size, like being a 32 bit unsigned integer instead of a 16 bit one. As that might break code, that relies on the specific size of the type, I try to always use types with the same size on all platforms. These types have always the same pattern. There are also: uint32_t, int16_t (signed integer) or int8_t.
I've chosen the type sizes according to the expected values. Pin numbers are typically 8bit/1 byte. That is sufficient. The thresholds are above 255, thus 8 bits are not enough, so I chose a 16 bit integer. Depending on the stepper positions, that you need, you might want to change it's type also to uint16_t.


How do I stop the slave from running the code until master sends a new value? I2C

#include "Wire.h"
volatile char x;
volatile bool received;

void setup() {
  Serial.begin(9600);
  Wire.begin(9);
  Wire.onReceive(Event);
}

void Event(char bytes){
  x = Wire.read();
  received = true;
}

void loop() {

  if (received) {
    received = false;
    Serial.print("The character that you entered in the other Arduino is ");
    Serial.println(x);
  }
}


Arduino with Ultrasonic sensor integrated but vibration motor not working according to the code

I think you have to uncomment the line that defines the motor as an output device.

//pinMode(motorPin1, OUTPUT);


Keep 5V on while sleep with LowPower library

If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY_5V pin instead of the SUPPLY_EXP_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).


I suggest using a single Arduino Mega.  It offers 54 digital I/O and 16 analogue inputs.

I suppose you could also use I2C or SPI to communicate between multiple Uno's.


It seems the toFloat() method is being a bit sloppy in its conversion.
The float closest to 51.507401 is 51.5074005126953125, which is only
0.13 ulps off. The number you got is the float right before it,
namely 51.507396697998046875, which is 1.13 ulps off. Alas, the
avr-libc functions atof() and strtod() make the same error.
I would suggest first considering whether the error is really
significant for your application: it is only about 48 cm on the
surface of the Earth. If this level of accuracy is relevant for you,
then follow Majenko's suggestion and use an integer count of
microdegrees.


How can I get two Arduinos to "talk" to each other?

Wired

Communication speed is not a factor - you only have to transmit an on/off signal. The simplest method would be to run a 4-wire cable, like a telephone cable, between the two.

The wires would be

GND
5V (maybe)
Ground floor output -> fourth floor input
Fourth floor output -> ground floor input

The steps are

Both wire 3 and 4 start LOW When ground floor button is pressed, ground floor led goes on, wire 3 is set HIGH.
Fourth floor is monitoring wire 3, when it goes HIGH, fourth floor led goes on, and    wire 4 is set HIGH
Ground floor is monitoring wire 4, when it goes HIGH, ground floor led goes off, and wire 3 is set LOW
Fourth floor is monitoring wire 3, when it goes LOW, fourth floor led goes off,    and wire 4 is set LOW
Ground floor is monitoring wire 4, when it    goes LOW, it begins waiting for a button press again.

Wire 2 can be used for 5V (or 3.3V depending on the Arduino) so that one of the devices can be powered off the other.

Wireless

The other option is to attach an RF transceiver to each Arduino, something like this would be good as it has 100m line-of-site range which you might need to get through 4 floors of concrete.

Learning

Start off with the simple wired method shown above. When it is working, connect wire 3 and 4 into the RX and TX pins and try to communicate using the serial port. Finally, move on to the wireless transceivers.


Serial monitor when port is being used by another application

Serial data can only go to one place at a time. Either your Python program can receive the data, or the Serial Monitor can receive the data. Similarly the serial port can only receive data from one place at a time.

So Windows prevents you doing something invalid by locking you out of the serial port when something else is using it.

This is normal, and entirely desired functionality.

Your simplest option is to just print what you receive in your Python program.


The pwm output of an RC receiver is the same signal used to control a servo. So if you used the servo library with Arduino to control the pwm of this device it should work fine.


Shield Compatible third party motor driver

You should do you own research as the path followed here did not result in the identically pictured nor identically model numbered item.

You indicated you are using a certain Arduino motor driver board.  On that page there is an "made by" or "by" reference to an OEM.  On the OEM's web page there is a "Dual Bipolar Stepper Motor Shield for Arduino" but the part number and the picture do not (exactly) match your original link.  Regardless, there is what they are calling a "WIKI page" for this (slightly) different motor shield.  I scanned this page and the example code.  I don't see where any device driver is mentioned.  And I don't think the code will compile by its self.

In general, I suggest people who are starting out with Arduino's to stick with well known hardware and software.  Even then I have had problems with newly released hardware.  Also check if drivers and SDKs have been updated each time you start a project.

Another approach you might entertain is to follow a path starting with the chip used on your shield.  It appears to use two DRV8825.  (But I cannot be sure as pictures and model numbers do not (exactly) match.) Here is a discussion on the a well known Arduino web site where people are talking about boards with this chip on it.


Using voltage divider to read voltage from sensor

It should work, but I don't know if its the best way.

Because the maximum voltage is 12 volts (I know you are only giving it 8, but you don't want to fry your board) you need the divider to send the Arduino 5/12 of the power.  You don't need much current, so you can use big values or resistors.  10K and 24K should work, but you should research or test this before you hook it up to you kit.


Arduino Uno as USB to Serial converter (bypass 328p)

As per your diagram, ground the reset pin on both Arduinos and connect TX to RX on the one to RX to TX on the other. Alternatively, if your Unos have a socketed 328P, you can remove it.

(This answer summarized from the comments above in order to take it off the "unanswered" list.)


So my AT 09 module is most likely faulty. I got a new HM 10 and connected it without changing any connections or code and it worked like a charm.
I do not know the exact nature of the defect but since the chip was responding to commands, I think the PCB might have been damaged.


Officially, no.  Practically, often but not always.

  If I follow the datasheet to the the letter, this configuration should not work. BUT... After some test, it did work.

The data sheet does not say that it "should not" work, it says that it is that the part is not qualified for operation at 16 MHz below some voltage higher than you want to use.  That does not mean that a given chip cannot work there, it only means that a chip that fails to may not be considered "bad".  Failure may be total and obvious or subtle.

In practice I have seen it work, both on small modified import boards and those with switchable power supply voltage.  But I also recall seeing it fail to work.

Two factors that can make a theoretical difference are part-to-part manufacturing variation and operating temperature.

Note that with an ISP setup you can change the fuses to run the chip on what was sold as a 5v external crystal board, to operate from the internal 8 MHz oscillator instead, and you can do this even while leaving the crystal on the board.  If you also change the brownout detector fuse, you can lower the voltage further, for example to operate without a regulator directly on two AA cells.  Of course that applies to the ATmega itself - any other active components on the board would have to be qualified for the intended voltage too.


Can an L293D motor driver shield do microstepping?

It would be more accurate to say that it can be used as part of a microstepping system, though it's probably not a good choice for any use today.

The L293D is merely an (effectively obsolete implementation of an) H-bridge, not a stepper motor sequencer, hence it is no more capable of autonomously driving a motor in full or half step mode than it is of microstepping - it can only do any of these when it is controlled by a sequencer, such as an L297 chip, or software running on an Arduino's processor.

Microstepping requires partially actuating the coils to interpolate between the angular positions which would be achieved by activating each in turn fully.  It can be thought of as a proportional extension of how half-stepping uses actuating both coils at the same power to achieve a halfway in between position, only now the coils are actuated at different power levels to achieve finer gradations of position, though achieving accurate interpolation requires care as the relationship is not linear.

Modern power electronics no longer use variable analog drivers, as these convert the unused power to heat.  Instead, the goal is to use switches which come as close as possible to only ever being fully on or fully off.  Reduced driver power is achieved by pulse width modulating the switch, varying the average amount of power delivered to the load over a short period of time.  In a stepper motor setting, this on-off modulation can be done to achieve microstepping and or also to achieve current regulation when a many-times-rated-voltage supply is used to allow overcoming winding inductance at high step rates.

The L293D (and its larger cousin the L298) are quite inefficient bipolar transistor bridges (they aren't very good switches compared to MOSFETs), and should probably not be chosen for new designs today.  They are, however, capable of being used to microstep a motor when actuated by a sequencer which pulse width modulates the phase signals.
Adafruit, who appear to be the original creators of this shield design, have in fact published microstepping driver code for their L293D board on github.

https://github.com/adafruit/Adafruit-Motor-Shield-library

Given that the ebay seller you link to as the source of the board is using Adafruit's own schematic on their product page, it's a bit unclear why your software is differentiating between this board vs an Adafruit one, unless by the the Adafruit board you mean their V2 shield.  The V2 design uses a more efficient TB6612FNG FET bridge, but of more relevance to microstepping offloads the sequencing task from Arduino software to a PCA9685 chip which is apparently capable of microstepping (as well as simpler modes) by itself.  Depending on the computational load and/or your  level of determination, you may be able to get the ATmega microstepping the L293D in the context of your overall project.


How to send HTTP request to specific port using Ciao?

You can find a portdefinition on your arduino in this path:

/usr/lib/python2.7/ciao/connectors/restserver/restserver.json.conf

{
 "name" : "restserver",
 "description" : "REST server connector for the Ciao Core",
 "authors": ["Arduino Team <swdev@arduino.org>;"],
 "repository" : "https://github.com/arduino-org/Ciao",
 "version" : "0.0.2",
 "params" : {
            "port" : 80
             },
 "log" : {
         "level" : "info"
         }
}

The confusing part is that your Arduino has a server client connection on it self from the cpu/linino server to the mcu/arduino client.

https://www.arduino.cc/en/Reference/CiaoRestServer


Problem with while loops while detecting frequency of a signal

Whenever you modify non-local variables in an ISR, it's important that they are declared as volatile. This tells the compiler that the contents may change unexpectedly, ensuring it doesn't use out-of-date cached copies somewhere else. If you don't do this, the code can behave in unpredictable ways, such as outputting the wrong value under some circumstances.

Since the variables are bigger than 1 byte, it's also necessary to disable interrupts around non-ISR code which uses them (e.g. in loop()). This is because interrupts could be triggered at any time, potentially half way through an operation which reads/writes them.

You can use noInterrupts() and interrupts() to disable/enable interrupt handling.


How is this simple transistor circuit suppose to work?

There are many bad schematics and pictures online, and these pictures are really bad.

Do not try to make that. You may damage the Arduino board and the transistor.

Even the picture of the BC548 is wrong. The BC548 is always
called "BC548" and never "BC-548".
The BC548 is not a good choice to drive a motor. It can only
do 100 mA continuous.
The DC barrel socket has plus and minus wrong connected.
The 12V plus is connected to the Arduino GND.
That is not okay.
The transistor in the first picture is probably a
transistor with the pins in BCE order.
A resistor is missing to the base of the transisor.
Because of the missing resistor, the Arduino board
can be damaged.
When the breadboard has a bad connection to GND,
the 12V can go to pin 9 of the Arduino board.

@Dorian, there are no mystical higher alien intelligent thoughts for that schematic. It is obvious a wrong circuit that is meant to drive a motor with PWM using a transistor.

And last but not least:
There are a few different types of computer fans. Some have a capacitor inside and some will only accept a PWM signal to a PWM input.
Are you sure that your fan is able to accept PWM for the 12V power?


How to flash a NodeMCU (ESP8266) with an external FTDI programmer?

Assuming your FTDI Basic is the 3.3V version, then yeah that will work fine provided you that manually reset the board yourself and enter the boot-loader using the buttons.
If you're independently powering the boards you may want to insert some series resistance in the RX and TX connections in case your signal receiving end is not powered while the sending side is.  In short you don't want the TX signal from one of your devices (boards) trying to power the receiving device (board) through its protection/clamp diodes.
In regard to comment about resistor value:
The value of the resistor depends on what you can get away with in terms of its effect on the signal and how much current is allowed through the clamp diodes on the other board.  A couple of Kbyte is probably sufficient, better than nothing in any case. Use a bit more if you can and still get a reliable signal through.  If you have the boards both powered before you connect them and you're careful about connecting them, then there's no opportunity for that.  It may also just be that they're robust enough that you don't need them at all.  I usually put some in though.  The second reason which I didn't state above is just that it protects you from being outright stupid and accidentally connecting them to the wrong thing; wrong signal, or to VCC or GND on the other side.


how to know the channel i receive information from when i use nRF24L01 to connect between 3 of them

The nRF24 is highly versatile and can be programmed for a number of different network topologies.  It appears you want either

One-to-many network - where the master node sends data to the slave nodes
Many-to-one network - where the master receives data from many slaves.

Both networks are achieved with the same radio channel (RF_CH) on all nodes.

For a one-to-many network you need to have a different RX address for each slave node.  Set the master TX address to the RX address of the corresponding slave  that you want to receive the data.  Done.

For a many-to-one network you are limited to 6 slave nodes.  On the master radio you will need to set the addresses of data pipes 0-5 to the slave TX addresses.  The master will be listening for data on all pipes and signal an interrupt whenever data is received on any of them.

To achieve bi-directional communication with a (practically) unlimited number of slave nodes, your best bet is to use the in-built ACK PAYLOAD feature of nRF24.  In addition to configuring a one-to-many network, you need to enable ACK payload on each radio node.  The procedure to follow is given in the nRF24L01 data sheet.  I can't recommend strongly enough how important that is to read and learn from.  You will be able to send a message from the master to one slave, and get data back from that node in the same radio transmission, auto-retransmit etc included in the bargain.  This way you also know which node the data are coming from - without needed to encode the identity of the slave node in the message.  It's incredible what these little radios will let you achieve!


Standalone ATmega328P stops responding when RX is connected

There are two things wrong with the circuit in that demo.

There is no decoupling capacitor on the power pins. This is required to keep the power stable during opertaion.
More critically: this is being powered from 3.3V, but is being run at 16MHz. That is outside specifications. You should use an 8MHz crystal to operate at 3.3V.


There is no need for a voltage divider or a level conversion on the reset pin of the esp8266. The esp8266 has internal pull-up on reset pin. To reset the esp8266 the reset pin must be connected to ground for a very short moment.

To pull the reset pin LOW with pin of the other MCU we do:

void resetEsp() {
  pinMode(ESP_RESET_PIN, OUTPUT);
  delay(1);
  pinMode(ESP_RESET_PIN, INPUT);
}

ESP_RESET_PIN is the pin wired to reset pin of the esp8266. It is not configured in setup() and it is never set HIGH (we don't want to send 5 V to esp8266). Setting the ESP_RESET_PIN to OUTPUT connects it to ground, setting it back to INPUT hands the control of the line back to esp8266 reset pin's internal pull-up.


Using NodeMCU D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins

The boot setup pins have pull-up on board (0, 2) and pull-down (15) to ensure the correct boot. io 0 (D3) is additionally wired to the reset circuit controlled over USB to put the esp8266 into bootloader a.k.a. flashing mode.

io 0 must be HIGH for normal boot, io 2 must not be LOW (can float according to spec).

If you attach a device to this pins, the device must respect the boot state. Some devices will pull-down or pull-up a wired pin. Usually it is not documented. You can't use such devices on boot config pin which requires the other state.

The pull-up and pull-down can influence the attached device or readings from the device. For some elements it can be advantageous.

Best is to use this pins for elements which would need pull-up or pull-down anyway. For example buttons/switches or sensors which behave like buttons or switches.

In my project with Wemos D1 R2 I had signal to relay module on io 0, speaker module (with amplifier) for tone() function on io 2. I could not use a relay or mosfet module on io 2. On io 15 I had a reed relay module control signal, which I didn't want to go HIGH at boot as most esp8266 io pins do.


How to improve the sampling rate of Arduino due ADC?

I haven't used the Due, but I understand its ADC is rated for 1 MHz sampling.  If that's its absolute limit then you can't expect 5 MHz.  However, judging by the Unos which I have used, you may be able to push things by limiting the number of bits.  This gives a speed boost two ways, by shortening the time the ADC uses to acquire the data, and if you limit to 8 bits you have half as many bytes to move into memory.
Do not try to use more than one channel, since then you have multiplexer delays as well.
Also, you may want to skip interrupts and just sample in a tight loop. Using this loop trick doubles the useful ADC rate of the Uno, from 50 kHz to over 100 kHz. (You'll need to figure out the actual sample rate by reading the timer before and after the loop, then divide by the loop size and take the reciprocal.)


How often can I ping an HC-SR04 ultrasonic sensor?

This ping() function is vulnerable to interrupts during the pulseIn(). This implies that a delay needs to wait for queued interrupts as from, for instance, Serial output. Input interrupts may still affect the results. This function only works in very simple sketches.

Possible solutions are to 1) disable during the pulse measurement (not the wait for pulse start), 2) use a more advanced method to allow concurrent events (such as timer capture).

Cheers!


It doesn't output 0v because it's near impossible. 0.003v is in fact very low. The LOW output, according to the datasheet, can be as high as 0.8v (when powered by 5v) and still be considered valid.

LOW does not mean 0v. It means "below the voltage threshold that is considered a LOW".


Problem using HC-12 graphical configuration utility, invalid responses

the 'SET' pin needs to be connected to ground to place (and keep) the HC-12 in setup mode. when this is done you should be able to click on the "check configuration" button and receive a popup response containing the device's current configuration.

if the popup response contains no configuration data then either the HC-12 is not in setup mode ('SET' pin not grounded), or the usb to serial bridge you are using is not working. check the bridge by disconnecting the HC-12 and shorting together TxD and RxD on the bridge. you can use any terminal emulator to check loopback is working.

feel free to join the backshed forums and ask further questions about the HC-12.

cheers,
robert rozee
(author of the HC-12 config utility)


The Arduino creators have spelled out their position on clones in a fairly lucid blog post a few years ago.

Your board comes pretty close to being a legitimate clone, but the claims about being manufactured in Italy are almost certainly false and possibly illegal.

I bought a CH340G based board myself, and apart from needing to install a different driver, it's pretty close to the original (There are a few projects that reprogram the 16U2 on a real Arduino board, but the vast majority of projects use the 16U2 as a straight serial converter, and the CH340G seems to do that job OK).

As other answers have pointed out, clone makers don't contribute to the community, so consider buying a real board occasionally. On the other hand, Arduino Mega clones are literally 25% the price of the original, so for that board, going with a clone is certainly tempting.


I have a hex file of a sketch i.e. sketchname.ino.hex. Can I find out anything from that hex file ?

That is a binary image of the compiled sketch in a hexadecimal notation. You could spend hours disassembling it if you understood the right tools to use.

  Can I see the output or anything ?

You can convert it back to a crude form of assembly language maybe, but that is all. Understanding what that means takes skill and knowledge.

  Can I upload it on arduino ?

Sure. It's a compiled program ready to be uploaded to an Arduino.

avrdude -D -patmega328p -PCOM3 -b115200 -C/path/to/avrdude.conf -c arduino -Uflash:w:sketchname.ino.hex:i


Save some arduino pins when driving a 4 digits 7 segments display

I know it's not what you asked, but you're using a lot of pins, why not try streamlining them and go to an I2C backpack? This one from adafruit includes a single 4x7 segment display.

given your comment, another option would be an I2C/SPI 7 Segment driver. (datasheet).

new edit: Actually, when I posted the above 7 segment driver, this is the one I was thinking of. I don't know why I didn't find this the first time.

max7219/7221 datasheet and digikey source:


With the I2C backpack there are three pairs of landings, A0, A1, A2, which determine the 3 LSB of the device's address, using inverted binary.

Left alone, they generate part of the F or 7 part of the address.  0x3F is common, as is 0x27.

To use more than one device it is necessary to jumper them all uniquely.

The upper bits that generate the 0x3 are hard-wired.  So is the highest bit of the lower byte.  Only the three lowest-order bits can be changed.

Since these address bits are inverted, jumpering the A0 will subtract 1 from the address.  0x3F will become 0x3E, 7 will become 6.

You have control enough to make up to 7 LCD modules on the same I2C bus.

The only caveat is that if you have more than one device writing to the various LCDs you might get collisions, which can mess up the display pretty good.

There are questions on I2C collision avoidance and detection on http://RaspberryPi.StackExchange.com if that is your situation.

Jumpering one or more of them is pretty easy - just pre-tin some wire and solder it quickly then cut off the excess.

Wire the SDA and SCL wires of the LCDs in parallel and to the SDA and SCL pins on the Arduino, usually A4 and A5.  (I always begin with a breadboard for this).  Make sure you have discrete pull-up resistors (10K is common) on each, in only one place on the bus.

If you have a DS3231 RTC module in the system, you do not need to add pull-ups because it has them internally.

If one LCD is already working then you know you have proper pull-up voltage on the bus.  (The signals are switched to the ground state to send data on the I2C bus)

So, to Summarize:

If you have two LCDs in your system you can use LCD modules that already come with different addresses, like

LiquidCrystal_I2C lcd1(0x27,....);

for the first one, then

LiquidCrystal_I2C lcd2(0x3F,.....);

for the second one.

Note that the parameters for these definitions are

LiquidCrystal_I2C lcdname(addr,en,rw,rs,d4,d5,d6,d7,bl,blpol);

0x27 and 0x3F are the most common stock addresses and 0x27 modules are getting harder to find.

If you have a 0x27 then it is very likely that if you buy a newer one it will be 0x3f. Problem solved.

The d4 and d5 in the definition specifies the pins to use for I2C.

You can run the i2cscanner program to see what it finds, once they are wired together.  If you see two different addresses, say 0x27 and 0x3F, then you are good to go.

If only 2F shows, then you want to consider soldering A0 together on one module then run the scanner again to make sure it worked.

Here is how I usually do it when both come set as 0x3f:

I have a Yellow one which is a stock 0x3F and a Blue one where I jumpered A0 to make it 0x3E.  They both are 20 x 4 displays.

Here are my definitions:  (remember, the 4,5 define SDA, SCL pins)

LiquidCrystal lcdblue  (0x3e,2,1,0,4,5,6,7,3,POSITIVE);
LiquidCrystal lcdyellow(0x3f,2,1,0,4,5,6,7,3,POSITIVE);

Then in setup() I use this:

lcdblue.begin(20,4);
lcdblue.backlight();
delay(250);
lcdblue.nobacklight();
delay(250);
lcdblue.backlight();

lcdyellow.begin(20,4);
lcdyellow.backlight();
delay(250);
lcdyellow.nobacklight();
delay(250);
lcdyellow.backlight();

And it's good to go, using pin A4 as SDA and A5 as SCL.

You know they are working as they wink their backlights at you.

If one of yours is 20 x 2 then use lcd2.begin(20,2); of course.

If you REALLY want to use other pins for your I2C bus then just change the 4,5 in the LiquidCrystal_I2C definition to the pins you want to use.  I never have met anyone who would want to do this.

Hope this helps.