text:
Is there any way I can stop the Arduino Mega 2560 from resetting all variables after losing and reconnecting power?
I am using an Arduino Mega 2560 board. I have tried connecting a 115 Ω resistor from 5V to Reset, and 10 µf capacitor form reset to GND (to disable autoreset), and the variables still seem to reset themselves when I unplug and replug-in the Arduino. Any way to stop this from happening?
Basically I am making a device that is sensitive to time, and must run for about 2 months, but if it is unplugged, it can't lose its place in time and reset the whole program.
I think one alternative would be for me to have it actually write how long it has been running into a .txt file on the microSD card and then verify that in the start-up...
Any ideas?

You have a power supply other than the USB connection, right?

Save the variables you need to EEPROM.

Arduino Mega board has RESET-EN "jumper". If you cut the trace, it won't reset MCU by DTR from USB-to-Serial chip. If you have to upload new sketch, you'll have to short it by piece of metal.
There is also possibility to use .noinit section for storing variables, so if you don't loose power, it won't get overwritten by automatic init. However, bootloader could be messing with that memory too. So it might not help without erasing this bootloader and using ISP(SPI) interface to program it.
Or you can use for example RTC (if you already have one) and it's battery backed RAM.

If you can't give the MCU enough warning of a power-down to save its critical variables, you'll have to keep it alive with batteries, sleeping if necessary, until the power comes back.
Tying Reset high won't help. The chip resets at power-up - that's built in. In fact, a power-up reset and a grounded-Reset-pin reset behave a bit differently - see the datasheet. Even if it didn't reset on power-up, the RAM needs power to maintain its contents, so it loses them when it drops.

Take power from UPS (uninterruptable power supply).

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

Not all questions have direct answer. Variables are stored in volatile memory that doesn't work without power and upon power reset variables are reset. There is no way to stop it from happening due to Arduino (and most other uC) design restrictions. But workaround solutions are possible, as almost always ;-)   SD card, duplicate power supply, UPS, car accumulator of big capacity, Ethernet shield are just several examples.

The question is not on how to prevent power shortage but on restoring state after power shortage, hence I don't consider this answer relevant to the question. Also I guess the OP knows about UPS and did not need anyone to mention it.


text:
What if I just connect 5V DC to my UTP?
Here is the image of Ethernet shield near RJ45 socket:

These small boxes are probably SMD capacitors which may mean, that internal board is glavanically disconnected from the UTP line.
Is this true?
If this is true, then what will happen, if I pass 5V DC current just into my UTP? Won't I be able to wire appropriate conductors just into Arduino power input? Won't I be able to power Arduino this way?
The question is about not using premade PoE splitter. I have an injector, which injects 5V into line.
UPDATE
I found my injector put power to lines 4,5 and GND to 7,8. Can I take this power on Arduino side?

Not exactly. That RJ45 connector labeled HR911105A is internally connected like this:

It's possible with PoE version (but I suppose not with 5V but more like 12V or so)
Or there are variants without PoE module connected but with support, that should be possible to use 5V if you wire it correctly)
Or you can use external PoE injector and extractor:
For 100Mb networks are two unused communication pairs used as power lines:

What is the  purpose of connecting 4,5 and 7,8 on your first schematic? Lines are unused, then why to connect them this way?

HR911105A schematics just means I can't reach my power lines from board side, right?

Yes, you can't, but if you use injector/extractor from the secon picture, it doesn't matter in this case. Just don't forget wires are not suited for much current. (that's why some injectors are using 24 or 48Volts)

You could replace the RJ45 socket with a different one (-;

source: Stack Exchange

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

sort: votes


text:
Controlling 12v DC LED strips using Arduino UNO
I have 2 LED strips with 6 LEDs on each. They use a 12V power supply.
My question, how can I use them like regular LEDs using Arduino UNO? Without any MOSFETS or transistors if possible.
And can I use PWM?

The only way is to cut out the individual leds an solder some wires to them, so you can connect them directly to the Arduino (with a resistor).

Do you have a picture? And are you sure it's 12v? As 8 LEDs is a weird number.

its 6 actually.. my bad @Gerben

That makes more sense. Two sets of 3 LEDs in series.

It's not safe for the MCU without transistors or so.
You can use some kind of LED driver (for example TLC5940 with on chip PWM) or ULN2003 as 8 channel low side switch (instead of 8 transistors, PWM is possible if you do it programmatically) or many others.
With single transistor it looks like:

Where R_1 can be about 1K and transistor can be any NPN that could handle led current.

so what transistor do I actually need? and in case I do use a transistor, how am I going to wire the enitre setup?

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


text:
MQTT Callback function don't called
I'm doing a device to recongnize NFC cards with an Arduino UNO, a CC3000 wifi shield, and a PN532 NFC shield. That's ok.
So, I created a sketch with this library: https://github.com/nathanchantrell/pubsubclient
I subscribed a topic /ocean/nfc/porta. When I publish a message to it, the callback function isn't called. Moreover, when it takes a card ID it publishs to a topic sometimes then don`t work more. How to solve it?
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>
#include <Adafruit_CC3000.h>
#include <cc3000_PubSubClient.h>

#define PN532_IRQ   (4)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

char cardID[ 16 ];

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
// also change #define in Adafruit_PN532.cpp library file
   #define Serial SerialUSB
#endif

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  7
#define ADAFRUIT_CC3000_CS    10

// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "Ocean Convidado"
#define WLAN_PASS       "ocean2901"
//#define WLAN_SSID       "Ocean Lab"
//#define WLAN_PASS       "ocean3101"

// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client client;

// We're going to set our broker IP and union it to something we can use
union ArrayToIp {
  byte array[4];
  uint32_t ip;
};

ArrayToIp server = { 25, 0, 25, 172 };

void callback (char* topic, byte* payload, unsigned int len) {

    Serial.println(F("CALLBACK"));
/*
    char payload_buffer[20];

    if (strcmp (topic,"/ocean/nfc/porta") == 0) {

        byteToChar(payload, payload_buffer, len);

        if (strcmp(payload_buffer, "permitir") == 0) {
          Serial.println(F("Abreeee!!!!!!"));
        } else {
          Serial.println(F("Não abre!!!!!!"));
        }

    }*/
}

cc3000_PubSubClient mqttclient(server.ip, 1883, callback, client, cc3000);

void setup(void) {

  #ifndef ESP8266
    while (!Serial); // for Leonardo/Micro/Zero
  #endif
  Serial.begin(115200);
  Serial.println(F("Hello OCEAN NFC Reader!"));

  Serial.println(F("Inicializando NFC Reader...."));

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print(F("Didn't find PN53x board"));
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print(F(".")); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println(F("Waiting for an ISO14443A Card ...\n\n"));

  Serial.println(F("Inicializando Wifi CC3000"));

  displayDriverMode();

  Serial.println(F("\nInicializando o CC3000 ..."));
  if (!cc3000.begin()) {
    Serial.println(F("Nao foi possivel inicializar o CC3000! Os cabos estao conectados corretamente?"));
    for(;;);
  }
  else {
    Serial.println(F("Carregou"));
  }

  uint16_t firmware = checkFirmwareVersion();
  if ((firmware != 0x113) && (firmware != 0x118)) {
    Serial.println(F("Versao do firmware errada!"));
    for(;;);
  }

  displayMACAddress();

  Serial.println(F("\nDeletando perfis de conexoes antigas"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Falhou!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nTentando conectar-se a(o) ")); Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Falhou!"));
    while(1);
  }

  Serial.println(F("Conectado!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Requisitando DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (!displayConnectionDetails()) {
    delay(1000);
  }

   // connect to the broker
   if (!client.connected()) {
     client = cc3000.connectTCP(server.ip, 1883);
     Serial.println(F("Conectando em TCP"));
   }

   // did that last thing work? sweet, let's do something
   if(client.connected()) {
    if (mqttclient.connect("ArduinoUnoClient-CC3000-A2", "iotocean", "NZZOLd0O66oLS0vpajiA123")) {
      Serial.println(F("Publicando"));
      mqttclient.publish("/ocean/nfc/debug","A2 está online");
      mqttclient.subscribe("/ocean/nfc/porta");
    }
    else {
      Serial.println(F("Ouve um erro ao conectar-se ao broker"));
    }
   }

}

void loop(void) {

  delay(1000);

  Serial.println(F("Entrei no loop\n"));
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    // Display some basic information about the card
    Serial.println(F("Found an ISO14443A card"));
    Serial.print(F("  UID Length: "));Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print(F("  UID Value: "));
    nfc.PrintHex(uid, uidLength);

    if (uidLength == 4)
    {
      // We probably have a Mifare Classic card ...
      uint32_t cardid = uid[0];
      cardid <<= 8;
      cardid |= uid[1];
      cardid <<= 8;
      cardid |= uid[2];
      cardid <<= 8;
      cardid |= uid[3];
      Serial.print(F("Seems to be a Mifare Classic card #"));
      Serial.println(cardid);

          // Testa se ainda esta conectado
          if (!client.connected()) {
            Serial.println(F("!client.connected()"));
             client = cc3000.connectTCP(server.ip, 1883);

             if(client.connected()) {
               if (mqttclient.connect("ArduinoUnoClient-Office-A2")) {
                  mqttclient.publish("/ocean/nfc/debug","A2 está novamente online");
               }
             }
          } else {
            Serial.println(F("else !client.connected()"));
            // as per comment from LS_dev, platform is int 16bits
            sprintf(cardID,"%lu", cardid);

            mqttclient.publish("/ocean/nfc/id", cardID); delay(1000);
          }
          //delay(1000);

    }
    Serial.println(F(""));
  }

  Serial.println(F("Sai do loop\n"));
}

void displayDriverMode(void)
{
  #ifdef CC3000_TINY_DRIVER
    Serial.println(F("CC3000 is configure in 'Tiny' mode"));
  #else
    Serial.print(F("RX Buffer : "));
    Serial.print(CC3000_RX_BUFFER_SIZE);
    Serial.println(F(" bytes"));
    Serial.print(F("TX Buffer : "));
    Serial.print(CC3000_TX_BUFFER_SIZE);
    Serial.println(F(" bytes"));
  #endif
}

void charToByte(char* chars, byte* bytes, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
      bytes[i] = (byte)chars[i];
}

void byteToChar(byte* bytes, char* chars, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
       chars[i] = (char)bytes[i];
}

uint16_t checkFirmwareVersion(void)
{
  uint8_t major, minor;
  uint16_t version;

#ifndef CC3000_TINY_DRIVER
  if(!cc3000.getFirmwareVersion(&major, &minor))
  {
    Serial.println(F("Unable to retrieve the firmware version!\r\n"));
    version = 0;
  }
  else
  {
    Serial.print(F("Firmware V. : "));
    Serial.print(major); Serial.print(F(".")); Serial.println(minor);
    version = major; version <<= 8; version |= minor;
  }
#endif
  return version;
}

/**************************************************************************/
/*!
    @brief  Tries to read the 6-byte MAC address of the CC3000 module
*/
/**************************************************************************/
void displayMACAddress(void)
{
  uint8_t macAddress[6];

  if(!cc3000.getMacAddress(macAddress))
  {
    Serial.println(F("Unable to retrieve MAC Address!\r\n"));
  }
  else
  {
    Serial.print(F("MAC Address : "));
    cc3000.printHex((byte*)&macAddress, 6);
  }
}

/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

Output of Arduino IDE:

O sketch usa 28.438 bytes (88%) de espaço de armazenamento para
  programas. O máximo são 32.256 bytes. Variáveis globais usam 1.546
  bytes (75%) de memória dinâmica, deixando 502 bytes para variáveis
  locais. O máximo são 2.048 bytes. Pouca memória disponível, problemas
  de estabilidade podem ocorrer.

I don't see any attempts to publish to /ocean/nfc/porta in your code. You are publishing from another node? Your broker is local? Post everything you get in the serial monitor.

I solved the problem. There is a bug on CC3000, so need to use WatchDog to reset for each while.


text:
How to insert a power button on Arduino Nano
I've an Arduino Nano to which a Micro Servo 9g is connected. The Arduino board and consequently the servo are powered by a USB powerbank connected to the board with a USB mini cable.
My question is: Is there a way to insert a power switch so I can turn on/off the board without plug/unplug the USB (that now is the way I use) ?
I was thinking to cut the USB cable and work with the positive of it but if someone has an alternative or any tips I'd really appreciate it. Thanks!
EDIT: If is needed I could make a wiring diagram.

Cutting a usb wire would be the easiest. Otherwise you'd have to cut traces in the pcb and attach wires. Not recommend for beginners. You can actually buy usb cable with a switch.
Another alternative would be to put the microcontroler in sleep mode and have it use very little power.

Thanks for your reply. If Arduino is in sleep mode does the servo still work?

I think that if you deattach the servo in software it doesn't use that much power. Otherwise you'd have to connect power to the servo using a transistor, so you can power it down during sleep.

As Gerben said, you can buy a cable with a switch built in.


text:
Problems with transmission between ATtiny85 and Arduino Uno with 433MHz RF modules and Manchester
I am trying to transmit from an ATtiny85 running at 16MHz internal clock to an Arduino Uno with the Manchester Library.
The problem is that the Arduino is not receiving any data.
I have hooked an oscilloscope to the ATAD/DATA pin of the transmitter, and I can see data being transmitted. I have also done the same thing on the DATA pin of the receiver, and it shows data being received. But the Arduino Uno is not detecting anything.
I have tried having an Arduino Uno sending data to itself, which does work, but the data gets dropped very often.
Here is the source code of the transmitter:
#include <Manchester.h>

#define TX_PIN 3  //pin where your transmitter is connected

uint16_t transmit_data = 2761;

void setup() {
  pinMode(1,OUTPUT);
 man.setupTransmit(TX_PIN, MAN_1200);
}

void loop() {
  digitalWrite(1,HIGH);
  man.transmit(transmit_data);
  delay(200);
  digitalWrite(1,LOW);
  delay(200);
}

And this is the code on the receiver:
#include "Manchester.h"

#define RX_PIN 4
#define BUFFER_SIZE 22

uint8_t buffer[BUFFER_SIZE];

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
}

void loop() {
  if (man.receiveComplete()) {
    uint8_t receivedSize = 0;
    // do something with the data in 'buffer' here before you start receiving to the same buffer again
    receivedSize = buffer[0];
    for(uint8_t i=1; i<receivedSize; i++)
      Serial.write(buffer[i]);
    Serial.println();
    man.beginReceiveArray(BUFFER_SIZE, buffer);
  }
}

This is the code I used to test with only the Arduino Uno:
#include <Manchester.h>

#define RX_PIN 7
#define TX_PIN 8  //pin where your transmitter is connected

uint16_t transmit_data = 2761;
int lastTransmit = 0;

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.setupTransmit(TX_PIN, MAN_1200);
  man.beginReceive();
}

void loop() {
  if (millis() - lastTransmit > 200) {
    man.transmit(transmit_data);
    lastTransmit = millis();
  }

  if (man.receiveComplete()) {
    uint16_t m = man.getMessage();
    Serial.println(m);
    man.beginReceive();
    //start listening for next message right after you retrieve the message
  }
}

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

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

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

Yeah, I will try modifying the code. The code I used is just sample code. Probably just faulty connections or RF modules


text:
Cannot power up Arduino Uno + Ethernet Shield with other than computer USB
I have successfully wrote a sketch for Ethernet Shield and Arduino. If I plug it into computer's USB, it works.
But if I plug into any other power source, like USB power adapter from iPhone or laboratory power source to power socket -- it doesn't work.
LEDs are doing various strange bursts, very different than if powered from computer.
What can be the reason?
UPDATE
I have updated sketch so that it doesn't refer serial:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
// B6-62-C5-CC-48-81
byte mac[] = {
  0xB6, 0x62, 0xC5, 0xCC, 0x48, 0x81
};
IPAddress ip(192, 168, 10, 90);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

long requestCount = 0;
long upCounts[] = {0, 0, 0, 0, 0, 0};
long downCounts[] = {0, 0, 0, 0, 0, 0};
int currVals[] = {0, 0, 0, 0, 0, 0};
int prevStats[]= {0, 0, 0, 0, 0, 0};
int upThreshold = 1024-32;
int downThreshold = 32;

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
//  Serial.print("server is at ");
//  Serial.println(Ethernet.localIP());
}

void loop() {

  for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
    int sensorReading = analogRead(analogChannel);
    currVals[analogChannel] = sensorReading;

    if( prevStats[analogChannel] == 0 ) {
      if( currVals[analogChannel] >= upThreshold ) {
        prevStats[analogChannel] = 1;
        if( requestCount>0 ) {
          upCounts[analogChannel] ++;
        }
      }
    }
    else {
      if( currVals[analogChannel] < downThreshold ) {
        prevStats[analogChannel] = 0;
        if( requestCount>0 ) {
          downCounts[analogChannel] ++;
        }
      }
    }
  }

  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    //Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        //Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 2");  // refresh the page automatically every 2 sec

          client.print("X-Inthemoon-Request-Count: ");
          client.println(requestCount);
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("X-Inthemoon-Analog-To-Digital: ");
            client.print("Channel=");
            client.print(analogChannel);
            client.print("; ");
            client.print("Min-Value=0; ");
            client.print("Max-Value=1023; ");
            client.print("Value=");
            client.print(currVals[analogChannel]);
            client.print("; ");
            client.print("Up-Change-Count=");
            client.print(upCounts[analogChannel]);
            client.print("; ");
            client.print("Down-Change-Count=");
            client.print(downCounts[analogChannel]);
            client.println(";");
          }

          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin
          client.print("Was counting: ");
          if( requestCount>0 ) {
            client.print("YES (request count is ");
            client.print(requestCount);
            client.print(")");
          }
          else {
            client.print("NO");
          }
          client.println("
");
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(currVals[analogChannel]);
            client.print(", up changes count is ");
            client.print(upCounts[analogChannel]);
            client.print(", and down changes count is ");
            client.print(downCounts[analogChannel]);
            client.println("
");
          }
          client.println("");

          requestCount++;
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    //Serial.println("client disconnected");
  }
}

The situation is the same:
https://youtu.be/vypaNOxZ5KI
It is plugged into Samsung tablet USB power of 2A, so insufficient current is unprobable reason.
UPDATE 2
I also tried to remove inclusion of SPI.h
UPDATE 3
If I connect another Arduino board  (but of the same vendor, it is from AliExpress), the behavior is the same.
UPDATE 4
I have compiled blink example and it works in any combination. If I connect Ethernet shield, then it blinks with both LEDs on Arduino board and on Ethernet shield.
UPDATE 5
I bought different Ethernet Board and it doesn't work too.
Please help. Have anybody ever powering Arduino + Ethernet not from USB?

This is basically unanswerable. Either your software requires communication from a host PC to function, or else some part of the setup is not what it is described to be.

Software is just Ethernet sample from here: https://www.arduino.cc/en/Tutorial/WebServer It is true that is contains writing to serial. Can this explain my situation?

Is the Ethernet shield status LEDs the same if you disconnect the network cable?

@MikaelPatel definitely not. If no Ethernet cable, then only power LED shines. If ETH cable connected, then other green LED bursting. But not the same way as when board works (if connect computer USB).

Have anybody ever powering Arduino + Ethernet not from USB? - yes I have one sitting around plugged into a wall-wart and connected to the (ethernet) network. It certainly works in that configuration.

It is plugged into Samsung tablet USB power of 2A, so insufficient current is unprobable reason. - I just measured my Uno and Ethernet card operating, and they were drawing about 200 mA of current.

Have you tried to measure voltage on board in different configuration ? This would help choosing between hardware and software problem (although update 4 makes me think about SW)

@Julien where to measure while connecting to computer?

@Julien can you check SW, what can be wrong there?

Between pins GND and 5V on the header. You should have between 4.5 and 5.5 on computer. The interesting measurement is on the not working power sources. I've not seen anything obvious in the source. You will need to learn to debugg ;)

@Julien can you provide some hints about how to debug in my situation?

@Dims Have you done the voltage measurements ? I think when ethernet powers up the peak current consumption makes the device reset. Try also pressing reset button instead of just plugging the USB. does this give same issue ? For debug, as the problem only occurs without connection to computer we cannot use print. You may try to add some 1s delays and LED blink before and after "critical" function call to see if the code is executed of if the device resets (or write some flags to EEPROM).

Sorry I didn't see this earlier but I suspect you have a bad earth, because:

It works with the PC
You are using a wall wart
You are wiring your board to another electrical source (Ethernet)
You are saying the LEDs are flashing differently.

Run a lead from the GND connector on the board to an Earth point.
(It might be the Ethernet that is at fault, but unless you have access to the switch I don't know how you could ground that properly)

Indeed, bring the board over to a friend's house, check if it also happens there.

Good idea, will try!

There should be absolutely no difference between powering your Arduino from a computer USB port or a wall plug, especially if you keep your serial monitor closed.
So this is the debug procedure I would advice:

disconnect the shield
connect the Arduino and upload a firmware with

no calls to Serial, but the most important one you must avoid is the while loop in the setup() function
a short blink of an LED (you can use the onboard one, if you wish so) every time the loop() function iterates

power your Arduino (without the shield attached) from your computer with no serial consoles and check the LED blinks at constant intervals
power your Arduino (without the shield attached) from your wall plug and check the LED blinks at constant intervals
disconnect the wall plug, attach the ethernet shield without an ethernet cable, reconnect the wall plug and check the debug LED and the LEDs on the shield are all blinking as expected
plug the ethernet cable and hit the Arduino reset button and check all the LEDs are blinking as expected

Possible faults i can currently think of:

STEP 3

the firmware running on your board is incorrect: double check the compilation and upload process has completed successfully and you have no error in the Arduino IDE console

STEP 4

the firmware still contains some code which expects some input from the serial console: start opening the libraries you use in search for such code
the voltage measured at the board between GND and 5V pins is insufficient and the board browns out: check the voltage is above 4.5V and the USB cable is not damaged or faulty

STEP 5

some of the code inside the ethernet shield library is trying to read data from a serial connection: check the library code again
some of the components on the ethernet shield are faulty and they are pulling enough current from your wall wart to actually make your board go into protection (hard to believe, a 2A serious wall plug should be much better power source than your PC)

STEP 6

same as for step 5, but your ethernet cable might be playing a role

This might not be an answer per se, but it might help you find out the answer you need.

This won't work, the code is designed to run Ethernet shield and may be blocking forever at some point if the shield is not present. Moreover Dims already wrote that a simple blink code works with and without Shield. The problem only seem to occur when using the ethernet library.

@Julien i didn't open the Ethernet library, so I can't state you are either right nor wrong when you say may be blocking forever, but I believe he can give a try to this.
Also, he said the board is blinking with the blink sketch, but I am suggesting to use a LED pulse at the beginning of his loop() function as a debug measure.... something you also suggested in the comments.

Maybe your laboratory power source is of poor quality. A computer's USB is a good power source. Try using a pack of 4x1.5v AA batteries. I have use this setup with arduino+ethernet shield+cheap servo.

Tried eveything, including this.

Maybe the alimentation part of your arduino is broken. Do you have another one to test ?

I too have had this problem with a Mega.  It was working with my SCADA package, running on linux and you could ping the Mega/ Ethernet board, but then something changed, and it wouldn't run/ read using the ehternet port.  Had two units, and both behaved the same.
When connected to the programming laptop ( runing W7) and the ethernet port, and running serial monitor, ethernet functions would work.  De powering and repowering using W7 usb port wouldn't work.  Tried removing all calls to Serial.print(ln) via if Debug type logic , didn't fix the problem.
Restoring the Serial messages didn't change the behaviour.
The "fix" is to press the reset button on the ethernet board after powering up, power source independent.
Giving the stack a general reset via the reset pins doesn't work, it needs to be the reset button on the ethernet module.
Did it via the unit connected to the linux machine and instantly got ping, and the SCADA system reading data.
If anyone can shed more light on the need to reset the ethernet module after power up I would be delighted.

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


text:
Uploading .hex to ATTiny13 using Arduino
I would like to upload a .hex to ATTiny13V (or '13A) using Arduino Uno R3.
I think I know everything to do, but ATTiny13 ISP support and Arduino IDE is a bit search-and-find, and I have some grey-areas in my understanding of how this all works together.
I got here by:
-Finding an Instructable that did something I liked, and there's a ATTiny13V used, a .hex to upload, and C source if I want to modify the source.  Right now I do not need to modify the source, the available .hex is fine.
-I then looked for a way to have AVR programing from OS X.  This seems a little problem, many AVR programmer hardware work great under Windows but seem to have mixed results under OS X.  I saw Arduino could be used for this under OS X.
-I looked on local craigslist for Arduino, someone was selling a Uno R3 with some extras for a great price, and here we are.   And now I have a lot more projects I wish to complete!
I am using Arduino 1.6.10 (from the .cc not the .org).
I read on stackexchange and other places that smeezekitty's core13 works for the ATTiny13.
elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/
That's great, but: If I am not using any of the Arduino-specific commands, I don't think I need the bootloader, correct?  I think it is not really a bootloader but builds support for some of the Arduino-specific higher-level commands used by sketch files.
Do I even need the ATTiny13 core files if I hook the pins up properly between the '13 on a breadboard and the Arduino (as per here:  https://create.arduino.cc/projecthub/arjun/programming-attiny85-with-arduino-uno-afb829 ).
I really do not understand what the Arduino IDE/bootloader is doing for me as an abstraction layer.  Do I need the bootloader if I'm not using any of the higher-level Arduino-specific commands on the chip?  HOw about the core files for ATTinyanything vs specifically ATTiny13?
The hex file and C source I will be using are here:
http://www.instructables.com/id/Programmable-LED/
My nextstep will be to modify the source. The C source looks like it references some AVR-specific header files.  I see that the ArduinoIDE uses avrdude so maybe things will compile anyway?
I feel like I'm close but not 100% in my understanding of what I need to do, with the tools I have on hand.
Thanks for your help- I am not above a step-by-step.
Main question 1:  I have a .hex file, an Arduino and IDE 1.6.10, OS X, and breadboard and useful components.  What do I need to do to put the hex on this ATTiny13?
Main question 2: Jumping-off points for taking the C source I linked, tweaking it a bit, building a hex, and uploading that.  I am not against moving it to a sketch if I have to, but it would be good for me to learn how this works before I mode to the IDE.
I have a small software background, am comfortable taking that C source and making changes and compiling (assuming I can find the needed .h files), but this is my first time working with any multiprocessors.

Your computer cannot talk directly to the ATtiny. You need some piece of
interfacing hardware between them. This is called an ICSP (or ISP)
programmer. You also need software to drive the programmer, typically
avrdude.
If you do not have a programmer, you can buy one (I had success with
some very cheap USBASPs), or you can program an Arduino Uno to behave
like an ISP programmer. You do this by uploading into the Arduino a
program called ArduinoISP, like explained in the tutorial Using an
Arduino as an AVR ISP (In-System
Programmer). You will
typically use the Arduino IDE and the Arduino core for the Uno to
compile and load ArduinoISP into your Uno. Once this is done, you can
use the Arduino as a programmer and burn your .hex into your ATtiny.
If you want to compile your own programs for the ATtiny, you will need
the avr-gcc compiler and the avr-libc. These are bundled with the
Arduino IDE, so you already have them. You will need an Arduino core for
the ATtiny only if you want to use the Arduino APIs and libraries.
Otherwise you can write plain C programs with noting else than the
avr-libc and avr-gcc.
Edit: To compile a plain C program, you can type something like
this:
avr-gcc -mmcu=attiny13a -DF_CPU=1200000 -Os -Wall -Wextra flickled.c -o flickled.elf
avr-objcopy -O ihex flickled.elf flickled.hex

This assumes your source file is called flickled.c and your ATtiny
runs at 1.2 MHz.

This worked great, I've programmed both .hex and new sketches into the ATTiny13 using the Uno as ISP. Thank you!


text:
HC 08 Module with Arduino Uno
I recently bought the HC 08 Bluetooth module (link here). As the specs state, this module supports Bluetooth 4.0 which indicates that it supports BLE (Bluetooth low energy).
My goal is to be able to use something similar to the CurieBLE library: I want to code services and characteristics on my Arduino so I can discover those on LightBlue (iOS).
I searched the internet for some guidelines, but I only found code using AT commands and honestly I don't know anything about those.
Can you please recommend any source to achieve the goal?
Update
After following the connections in this link (In Spanish I guess but helpful), I was able to discover the Arduino on LightBlue. The characteristic name was Tx/Rx and I was able to write, read and subscribe to notifications (data coming in). Of course if would be better to find something that allows the definition of services and characteristics.


text:
How to purge incoming Xbee packets from the buffer?
I have a need to receive a specific confirmation packet after commanding my transmitting Xbee to stop sending normal packets.
My buffer still has normal packets in it when this happens, so next time I call readPacket(), I don't want to see them. So right before I call my stop command, I try to purge the incoming buffer like this:
void burnSerial(void) {
  while (xbee.readPacket(20)) {
    xbee.getResponse().getRx16Response(rx16);
  } //read all available responses
    // only do this when not in a constant stream of responses or it may hang.

  while (Serial.available()) { Serial.read(); }
  //burn whatever may be in serial buffer
}

But this doesn't work. The next time I call xbee.readPacket(), I see tons of normal packets before I finally see my confirmation packet. Why don't these functions do anything for me at all?

It means there's a lot of latency between your issuing a command and getting a confirmation of the command's effect. When you send the command, it's best that you wait and read packets until you find the confirmation and then you return from the function or do whatever else you want to do. There is no need for a separate burnSerial() function, nor should you blindly discard data. So basically, the sequence of operations should be:

Send the command
Read packets until you find the 'confirmation' identification marker
Return or exit

This assumes that your transmitter only sends confirmation after it has halted the stream.


text:
How to control cold to hot (blue to red gradient) RBG LED strip/bulb with a rotary encoder?
I'm doing a project for university and I am struggling to code and set up a rotary encoder that can control hot-cold variations. Much like the idea of communicating temperature selected by turning a dial. I would either like to control a single strip of RGB LEDs or a single bulb (changing and fading between colours at the same time).
I would like to have the dial turn from 0 - 180 degrees and relate to intense blue changing to intense red and all the colours in between as increments.
I have an Arduino Uno.
Thank you!

Which part of that are you having a problem with? Reading the rotary encoder or making the LED(s) light up in the right way?

The SE format works best asking 1 question and getting 1 answer.  And, you'll get a lot more responses here if you give your project a try first.  Then, if you get stuck, ask a question about the issue you are having problems with.  That said, break your project into two parts.  There are plenty of on line web pages regarding rotary encoders.  And plenty of on line web pages which talk about RGB LEDs.

Did you miss to add your source code, components and wiring?

If you want a dial that turns from 0 to 180, is a rotary encoder the best option? Generally this component is used either (a) as a rotational speed sensor; or (b) because we've got used to having seamless rotary controls. A potentiometer would be better suited, and easier to include.

You probably want to use the HUE color scheme instead of RGB and then just map the HUE value to the analog value of a potentiometer.

I'm voting to close this question as off-topic because it's a low quality post, showing no effort to solve the problem on his own.

Well as I understand you want to use a rotary encoder ? Rotary encoder can turn freely. Which you can read via arduino easily with a library. You can count a number(let's say x) from 0 up to 255, and write that number to one of the color. For the other color write 255-x so when blue is fading down the red is increasing. But I suggest you to use a potentiometer which has a limited turn (about 270 degrees). Connect it to arduino's one of the analog read pins. It will give you a 10 bit value which is between 0-1023 . You can scale this down to 0-255 range with map function. [Example:  "x = map(x,0,1023,0,255);" ] after that just follow the same process as before.

http://playground.arduino.cc/Main/RotaryEncoders is where the rotarty encoder libraries are. From there you can use PWM on the outputs as said. There are also some addressable RGB strips/modules that incorporate a driver IC such as adafruit neopixels where you can just write values for colour and brightness to the IC fairly simply, depending on your level of electronics knowledge.


text:
Minimal Arduino using ATmega32U4
I am a newbie and I would like to build my own minimalistic ATmega32U4 based arduino compatible board. Can anyone please tell me which parts resistors/capacitors (and maybe one status led) I need to connect it over usb to my computer? Thanks in advance.

It's all in the datasheet.

Several Arduinos and Arduino-compatible boards use the ATmega32U4.
Many of them have published open-source plans that show exactly what components are used and how they are connected. They may not be the absolute minimal number of components, but it seems clear that you don't need more components than a known-working board:

1 ATmega32u4
1 16 MHz crystal
2 22pF ceramic caps (for crystal)
1 uF decoupling cap
1 pushbutton
1 10 KOhm pull-up resistor (for pushbutton)
1 LED
1 220 Ohm resistor (for LED)
1 USB socket
2 22 Ohm resistors (between USB socket and ATmega32u4)

Alas, there are two unnecessarily difficult hurdles between newbies and getting a new ATmega32u4 device connected over USB to a computer:

The ATmega32u4 and nearly every other device that communicates over USB is only available in SMT packages with pins at 0.8 mm pitch or even closer together.
Most people find packages with pins at 2.54 mm pitch easier to handle and plug into a breadboard.
Installing a bootloader into any new processor chip is often tricky.

As Russel already pointed out, you can save a lot of time by starting out with an Arduino or Arduino-compatible board that already has the chip soldered on and the bootloader programmed in, bypassing the above unnecessarily difficult hurdles.
A few Arduinos and Arduino-compatibles (with links to schematics, etc.) that use the ATmega32u4:

Bootloading an ATmega32u4 with Arduino
Teensy 2.0 (ATmega32u4 USB dev board)
Arduino Leonardo; Arduino Leonardo
Arduino MICRO
SparkFun Pro Micro (Arduino-compatible)
FLORA - Wearable electronic platform: Arduino-compatible
Adafruit Feather 32u4 Basic Proto
Installing Arduino Bootloader on an ATmega32u4; Installing Arduino Bootloader on an ATmega32u4

One other crucial factor to consider: USB's timing requirements are pretty precise. That requires that the crystal oscillator create quite a precise frequency. Breadboards and precise frequencies do not go together due to the massive capacitance they impose on the circuitry. That makes it very very hard to get USB actually working from a breadboarded chip.

@Majenko: I agree that breadboards add a huge amount of capacitance, with bad effects on timing circuits. However, Jeff Murchison and many of the people commenting on his blog (first link) somehow got USB working on a breadboard, so apparently it's not very very hard.

Building your own may be worthwhile from a learning point of view, but makes minimal sense otherwise. You can buy Arduino clones (legal) from China for under $US5 each - good enough quality, assembled, working.
You cannot build one for that.
A DIY minimalist Arduino requires a running processor - see datasheet for the processor of choice as Ignacio says.Probably decoupling capacitors and maybe one or two resistors and maybe 1 or 2 small capacitors. If you cannot derive the needed information from a datasheet you do not know enough to sensibly do it by yourself. There are many on-web ~= minimalist implementations to copy.
If you want onboard USB you'd usually use a USB-serial converter but this can be done by "bit bashing" if you truly want a minimalist implementation>
BUT - just buy one and use the large amount of time gained to learn related things of more immediate use.

The '32U4 has built-in USB device support, so a USB-UART bridge isn't required unless you want to connect the hardware UART to a second computer.


text:
Help with usbasp pinout
I am having trouble figuring out the pinout of my 6 - pin USBasp Chinese clone that I got off eBay.
BEFORE YOU TELL ME TO LOOK AT THE PINOUT DIAGRAMS, I can tell you that my version of the usbasp has no way of telling which way is up and which ways is down. Images:

Did you look at the triangle on the side of the connector?

The pin labeled “Or this pin?” is pin number 1: look at the key on the left side of the connector.

Look at the following pinout diagram (from telecnatron.com):

The right-hand diagram above shows the USBASP-board pin-header pin assignments, when you are looking into the pin-header.  The header shell will have a triangle marking pin 1.  Note that pin 1 is on the same side of the connector as the key (the ridge on the cable connectors, the slot on the pin-header shell).  Each socket on the cable also will have a triangle marking pin 1.


text:
digitalPin giving lower voltage than Vcc
I am using an ATTINY88 for a project that requires to turn on an LED. Right now I am using pin PA1(ADC7/PCINT25). I noted, however, that when the pin is ON, I get about half the voltage that is connected to Vcc. I checked the voltage in other pins and they are close to Vcc. Will anyone know, what could be the reason for this?
I figure this pin has an internal resistor enable, but I am not certain.

Do you have a resistor in series with the LED?

I disconnected everything from the pin and I still get half the Voltage in Vcc when that pin is HIGH. In fact, all the pins on that side of the chip give half the voltage when they are on, while other pins give voltage near Vcc. I think those pins on that side of the chip have a resistor enable???

this behaviour might happen if you have PA1 set as input and pull up resistor enabled. Check the datasheet for Port A sub-section. It defines that it will source current when enabled.

is there a way to disable such resistor? I have that pin set as OUTPUT

You should connect the AVCC pin to VCC. From the datasheet (emphasis
mine):

AVCC is the supply voltage pin for the A/D converter and
  a selection of I/O pins. This pin should be externally connected to
  VCC even if the ADC is not used. [...]
The following pins receive their supply voltage from AVCC:
  PC7, PC[5:0] and (in 32-lead pack- ages) PA[1:0]. All other I/O
  pins take their supply voltage from VCC.

That sounds like a really bizarre design choice to me... reminds me why I use PIC and not Atmel chips ;)

@Majenko It is little bit bizare, but connecting AVcc to Vcc is stated in every datasheet for every AVR with AVcc pin. And yet it's common rookie mistake.

It probably makes internal wiring in the chip simpler, and possibly reduces noise.

do you know why is this needed (connecting AVcc to Vcc)?. My circuit works just fine without that connection and it includes several AnalogReads....also, I wonder if it will increase battery consumption? I will test this.

@Camilo: Why it is needed? The excerpt of the datasheet I quoted is, I think, quite explicit. Your circuit may work without that because 1) the internal logic is powered through VCC, 2) the AVCC node is getting some parasitic power through some I/O pins or some internal gates.

@NickGammon I would have thought it would have increased noise. Digital switching noise from the pins used for digital purposes imposed on the analog circuitry.

Yes, but those are the analog (ADC) pins anyway (of course you can use them for digital if you want). Having the ADC pins have two power sources could be complex (one for digital work, one for analog work). So if you stick to using the "digital-only" side for digital switching and the analog-side for analog reading, the two power supplies now keep them separate, rather than running an internal wire, with its digital noise from digital switching, from one side of the chip to the other. So I wouldn't call it bizarre. It sounds quite sensible to me.

That indeed fixed the problem. it should be noted that that part of the chip includes several analog pins as well as two or three digital pins. On the other hand, connecting aVCC to Vcc, actually reduced current by a few mA. It should also be noted that that connection requires a 100nf ceramic capacitor and a small inductor, to cut any noise form external voltage variations.

@Camilo: This is listed as an "analog noise canceling technique". If you do not use the ADC, you can connect AVCC just like VCC, with only the 100 nF cap.


text:
Find RSSI of Mobile Device Without Connecting
I have a device in which a user connects their mobile device to an arduino uno via a HM-10 bluetooth transponder.  I want to be able to calculate the approximate distance between the user and the transponder by hopefully using the RSSI methodology:
 d = 10 ^ ((TxPower - RSSI) / 20)

My goal is for the user to send a connection request to the HM-10, the uno to then calculate the distance, and if greater than x meters away, reject the request.  I realize RSSI based distance is an estimate at best but that is fine for my purposes.
With that in mind, I have two questions:
1.) Is an HM-10 able to capture the RSSI strength of a mobile device to
    calculate distance?
2.) Can it do so WITHOUT connecting first based on the
    initial request of the mobile device?

This seems to be an HM-10 question, not an Arduino question.  If you control the firmware on the HM-10, you could have it refuse (/ignore) the connection request.  But be aware that RSSI based distancing may be dissapointing, especially if you do not know the output power of the mobile.  Where people try to do it in the other direction, the beacons include their measured field strength in the advertising packet as an attempt at calibration.

What problem are you facing?
Usually, if I have a question, I try to google it myself, with reasonable results. I'll post an answer in which I'll try to help you though.

Do you have the bluetooth module working in the regular operating mode already? Tell us what you did, what worked and what didn't.

You have two questions, but what makes you think you can't find these out?
When you want to know what a device can do (and thus can't do) you should check the devices' datasheet. I believe it is this file.
Bluetooth (and gsm) devices often work by sending AT commands. For example: "AT+PIO" to set/query GPIO pins of the module.
You can send "AT+RSSI?" to get a response on the RSSI value.

Not everything can be mentioned in the datasheet though. If you can't find any sources on it, it's most likely not a feature.
The only way to add a "validation function" within the bluetooth connection code, would be to re-write the firmware of the device.
But, you could:

Connect (with everyone using the right pin)
Check their RSSI
Disconnect if it doesn't match your criteria

I'm not sure if this module can have multiple connections, I didn't really see a way to disconnect a single connection. If not, you could even toggle the power to the module to "disconnect" the client(s).


text:
Strobe Frequency Calculation, how its done?
I'm using the Arduino sketch for LED stroboscope found here: http://mehax.blogspot.co.uk/2011/02/arduino-stroboscope.html.
Also below, I've inserted the loop part where this calculations are made:
void loop() {
// this while is a workaround for timer limitations using micros vs millis
sensorValue = analogRead(analogInPin);   //take potentiometer reading
hold = sensorValue*55 + 400;             //add some time to scale and for code execution
microsCurrent = micros();                // collect current time
if (microsCurrent > microsPrev + hold){  //set up timing loop
frequency = 1000000/(microsCurrent - microsPrev);
microsPrev = microsPrev + hold;            //set up millis for delay stuff

//set all 6 LEDs high (they were already plugged in)
digitalWrite(3,HIGH);
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
delayMicroseconds(.02*hold);  //leave LEDs on long enough to see

//set all LEDs low
digitalWrite(3,LOW);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);

if(millis() > millisSerial + 200){
  millisSerial=millis();    //reset timer
  holdFrequency = 1000000/hold;
  //do some math to find values
  rpm = frequency * 60;

I want to use this code in my project, but I don't really understand how this code calculates the stobing frequency.
So, I have following questions:

Why "hold" variable is calculated in the given way?
Why "microsCurrent", "microsPrev" and all other timings are executed?
How "frequency is calculated"?
What is "hold frequency" variable?

Sorry, I'm very new to Arduino and don't know much coding.
Will appreciate very much your help!

About that program you are using: you may want to take a look at the comment I just posted in the author's blog.

Why "hold" variable is calculated in the given way?

hold stores the intended delay between the strobe pulses, i.e. the
stroboscope period. It is computed as an affine function of the
potentiometer cursor position because... well, that's the simplest way
to make it user-adjustable. 400 µs is the shortest period that
(according to the program author) one may reasonably want to set.

Why "microsCurrent", "microsPrev" and all other timings are executed?

See the Blink Without
Delay Arduino
tutorial.

How "frequency is calculated"?

From the code:
frequency = 1000000/(microsCurrent - microsPrev);

The frequency is the inverse of the period. The period is the time
elapsed between this strobe and the previous one. The numerator is a
conversion factor to get the frequency in hertz from a period in
microseconds.

What is "hold frequency" variable?

It's the intended frequency (inverse of the intended period),
disregarding the timing jitter that makes the actual instantaneous
frequency slightly different.

Thanks for your prompt reply!
This made almost everything clear in my head.
So, the "frequency" variable shows the real strobe frequency (taking into consideration the possible delays), while "hold frequency" is the intended freq., but it's not used to display anything in this code, right?
and what kind of delays there might be?
Thank you.

@George: I am still examining the code, and I believe there is a bug. holdFrequency seems to have the correct average frequency, which is probably the most relevant datum. frequency is computed from the difference between the actual time of the current pulse and the intended time of the previous one. It can therefore carry a slight bias.


text:
Is it possible to program an ESP8266 12F using an Arduino Nano?
I just got my ESP8266, but I am unable to program it. Since it can't be connected to via USB, I was wondering if I can program it using an Arduino or perhaps use it as a shield for an Arduino Nano. I haven't been able to find a good guide online. Any help is greatly appreciated.

Why can't connect via usb?

Yes, you can program it with Arduino but its a bit complex that way. You will need a separate Linear Regulator with Adjustable Output to get it hooked up with the Arduino.
 Its way better to have an FTDI adapter to program it.
But if you still want to know, there is a tutorial below,
Upload Bareminimum sketch so that no program is running on the Arduino.

Is it possible to program an ESP8266 12F using an Arduino Nano?

Yes, but it is much easier to use a FTDI for USB-to-Serial adaptation. Two buttons are also needed to activate the ESP8266 programming mode.
Cheers!

Actually that tutorial has some fairly serious problems.  It claims the regulator is an "LM1117" but neglects to mention that this part comes in various voltage ratings, and it neglects to mention capacitors required by the regulator data sheet.  The author might have gotten away with it using the part they had on hand, but it is not good guidance.

Could you suggest a link to a better tutorial? Please feel free to update.


text:
Arduino Wire.h send double to lcd
I'd like the double number 200.00 shown as 200.00 on my LCD screen.
For instance, when I pass just a number (int) like 40 to the LCD, it uses it as an ASCII code to show a character on the display.
Now I want to send a double to it and it should be displayed as a double.
#include <Wire.h>

void setup() {
   Wire.begin(0x63);
}

double f;
void loop() {

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(f); //<- How to do this?
  Wire.write("Hz");
  Wire.endTransmission();
}

The Arduino Wire class does only support write() of byte, string and vector of bytes. To write a double it must first be converted to a string. This can be done with the standard C library function dtostrf().
double f;

void loop() {
  char buf[10];

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(dtostrf(f, 0, 2, buf));
  Wire.write("Hz");
  Wire.endTransmission();
}

The class inherits from Print (via Stream) so that the overloaded member function print() for double can be used. In that case:
double f;

void loop() {
  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.print(f);
  Wire.write("Hz");
  Wire.endTransmission();
}

Please note that the maximum number of bytes to write (between beginTransmission and endTransmission) is limited to 32 in the standard configuration of the Arduino core.
Cheers!

Use Wire.print(), instead of Wire.write() which is intended only to output single bytes or byte arrays.


text:
Understanding memory fragmentation due to char arrays in functions
This is similar to:
Is this function subject to memory fragmentation?
I am trying to get my head around Memory fragmentation in Arduino's and embedded systems in general.
Currently I have a function in a __lcdAux__ Class which is responsible for doing basic operation on the lcd.
One of the members of the class is a char array double2StrBuff1 which is used with __dtostrf()__ to create a double which is then passed to sprintf. So the following function (__lcdAux::UpdatePosition__) is responsible for updating the position on the lcd.
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

Currently, I am under the impression that by defining once the class as a global variable and then using it throughout the program, then the char array is allocated only once memory space. Therefore by using it afterwards no memory fragmentation occurs.
However, I read that functions allocate space on the stack which is immediately recoved when the function is exited. Therefore I am curious if the following declaration is any different in terms of memory fragmentation.
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char double2StrBuff1[10];
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

To sum up:

by putting  the declaration for variable __char double2StrBuff1[10];__  inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function (therefore there is no need to declarate a member variable on the class level),

OR

is the fact that __double2StrBuff1__ is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

PS: Because some might point out that  __"X: %s"__ is worse in terms of memory usage and fragmentation, I'll state the following. Instead of the format string __"X:%s"__ I use a _PROGMEM const char_ array and __strcpy_P()_, but to simplify the question I replaced it with the literal string , since I feel that is another problem.

The term memory fragmentation refers to heap fragmentation (when using malloc/free or new/delete). https://en.wikipedia.org/wiki/Memory_management

by putting the declaration for variable char double2StrBuff1[10];
  inside the function, is the memory allocated from the stack and
  therefore recovered upon exiting the function

This is correct.

is the fact that double2StrBuff1 is a pointer means that the pointer
  is allocated in the stack but the values are located in the heap
  (therefore what I am doing makes sense)?

No, double2StrBuff1 is not a pointer, it's an array. In C and C++,
when you use an array identifier, it decays to a pointer in many
situations. However, for the purpose of memory allocation, an array is
very different from a pointer.
Heap allocation only happens when using malloc() and new.

Could you point me to some reading material which will improve my understanding of how array identifiers are different to pointers?

@NMech: Take a look at this question (and its answers, and maybe the linked references) on Stack Overflow: What is array decaying?.

The examples in the question above use 1) global and 2) local aka stack allocation and do not give heap fragmentation. The heap is not involved.
Below is a version that may give heap fragmentation (though a very low risk):
void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char* double2StrBuff1 = (char*) malloc(10);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
    free(double2StrBuff1);
}

Please not that heap allocation is very slow compared to stack allocation.
C/C++ does not have any implicit heap allocations (in the language). A local array in a function is allocated on the stack and removed when the function returns. The only library functions that can generate stack fragmentation are setjmp and longjmp if used to create a spaghetti stack.


text:
Motor Shield and HC-06 Bluetooth Module competing for pins
So my problem is this, I have an Arduino Uno with an Adafruit Motor Shield (1.0) and an HC-06 Bluetooth Module and I want to use them at the same time, the problem is that the Motor Shield uses all the ports that I need for the HC-06 (TX, RX, GND and VCC). In addition to all that, my project needs to be light weight (It's a quadcopter). Is there any way that I could use both of them at the same time?
Thanks in advance!

The motor shield doesn't actually use the TX and RX pins. Though as a shield it will go into all the arduino pins.
You could either solder some wires to the TX and RX pins, or use something like the proto shield to sandwich in the middle of it, and connect the BT module onto this shield.
You could also remove all the male headers from the motor shield, and replace them with stacking headers

Thank you, but what about the ground pin? Could I find an alternate power supply or something?

Unlike the digital pins, you can connect multiple devices to a single Vcc or GND pin. The motor shield also has some free pads that you can use for 5v and GND (near the analog pins).

I was wondering if is not easier to just solder some stacking headers on the analog, ground and +5 area

Ok so i had the same problem but i found like the easiest solution. So what i did was scrape the wire end to the copper using a knife or a wire cutter. And then place it in the Arduino holes and then squeeze the motor shield on top of it. Works like a charm!


text:
Arduino Due ( Atmel Microcontroller) IC Heat up and led goes off
I was connecting L293d Motor Driver IC with an Arduino Due Board. May be due to wrong connections, but when I made the grounds common, the Arduino LED goes off and Atmel IC heats up. When I reconnect my Due board with my PC anytime, the LED turns on and slowly dims to off and Atmel IC fries up.
I wanted to repair it. What should I do?
I have checked the input voltage of the AMS1117 3.3V regular IC as 3.8 V, while the output is 2.2 V. If I externally give 5 volt at input again, the input voltages drops. The regulator is loading.
I thought of replacing the regular IC?
Will that work?
Also I externally powered the Board with 3.3V by its pin labeled "3.3V" . The LEDs glow on and did not go off. But the Atmel Microcontroller IC becomes very hot.
What should I do?

Trash it and get a working board.

Motor driver boards exist to allow an MCU to control a motor without having to supply its power. If you try to power motors from the Arduino as well, they draw too much current and things get hot or damaged.
The 3.3v pin is only for supplying modest amounts of current at 3.3v from a 5v Arduino. You can not back-power the board with it. I don't know what happens if you try, but I bet it isn't good...

Supplying 3.3V to the board and trying to draw from the 5V connection will damage the voltage regulator. Since the ATmega16U2 on the board draws from 5V, well...

I have disconnected the motor driver and when i give USB power. Led glows for short period of time and then turns off. At the same time MCU heats up. and i am unable to upload any code in it. Does changing a regular will fix it up?

@MasoodSalik MCU heating up without anything connected to outputs means it's more or less destroyed. Something reached break down voltage and now it's permanently conductive.


text:
Best way to assign value to lot of variables
I'm building web based remote control system for esp8266. In arduino IDE, using the ESP libraries. To, send data to the server, I'm using http post.
For some settings, I need to transfer 30 or so, different values over a single post request.  And assign it to different type of variables.
so, from this:
192.168.1.101/testpost?lenght=10&1=100&2=true&3=1800&4=125

i need this:

uint8_t brightness = 100;
bool randomOrder = true;
uint16_t Delay = 1800;
uint8_t Position = 125;

This is the relevant code. Basically, my idea is, to send the lenght of the array (will be different each time.) in the first argument.
Than create a for loop that put every value in a array into variable pointers. But, since lots of different type variables going on, i'm not sure how to do that.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//values i need to set in a single post.
uint8_t settings0;
bool brightness;
uint16_t randomOrder;
uint8_t Delay;

void setup {
//relevant code that handels post request.
server.on("/testpost", HTTP_POST, []() {

String ZeroValue = server.arg("lenght");

int lenght = ZeroValue.toInt();

//this doesnt really work, but its a starting idea.
int* SettingsArray[4] = {&settings0, &brightness, &randomOrder, &Delay};

for( int i = 0; i < lenght; i++) {

     String PresetSettings = server.arg(i);
     SettingsArray[i] = PresetSettings.toInt();
    }
});
}

Ultimately, I can just do that, but I'm wondering if there is a more elegant solution.
brightness = SettingsArray[1];
randomOrder = SettingsArray[2];
Delay = SettingsArray[3];
Position = SettingsArray[4];

The WebServer class supports argument lookup by name. This should allow HTTP argument parsing that does not require length and/or specific order:
192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

And parse with:
brightness = server.arg("brightness").toInt();
randomOrder = server.arg("randomOrder").toInt();
Delay = server.arg("delay").toInt();
Position = server.arg("position").toInt();

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.
String arg = server.arg("argName");
val = (arg.length() == 0 ? defaultVal : arg.toInt());

Or simply:
String arg = server.arg("argName");
if (arg.length() != 0) val = arg.toInt();

Cheers!

Thank you! didn't notice i can do that, that simplify code on front end as well.


text:
Controlling a digital 12V addressable RGB led strip with Arduino?
I have a 12V addressable RGB strip that I want to control with an Arduino, the chips are ws2811s, is there a way to do this as the Arduino is 5V and 3.3V?

Can you post a link to where you got them? What pins are on the strip?

How did you plug to arduino can you show me pictures or diagram? i also have 12v addressable rgb strip

The only signal you need to worry about is DIN (data in) which is normally 5V from an Arduino. Use that to switch a MOSFET or transistor to convert the digital pulses to 12V. In other words, the Arduino switches the transistor, the transistor outputs 0 or 12 V.

Judging by this link you still just send 5V digital switching to the strip.

The data signal never needs to be 12 volts. The 12 volt pixels all drop the voltage down to about 5 volts to operate the chip. Usually just a resistor and a zener diode, sometimes just a resistor.

In other words, connect the "power" pin to +12V, and the ground pin to Gnd from your power supply.
Connect the Din (data in) to your Arduino pin directly. Of course, also connect the Arduino ground to the ground pin.

Also see this Youtube video. On the comments he says:

These 12v WS2811 "pixels" still use 5v signalling. You simply connect the 12v source power directly to the strip, tie the ground to the arduino and then treat them as if they were a 5v strip.

So i could just hook up a TIP120 MOSFET between the arduino and the DIN?
Or could i just connect the strip as 12v and connect the ground to the arduino and treat it as a 5v strip?

No, I was wrong. See amended answer.

Got the strip from a local store, but it has 4 pins: VCC, 2 ground and DO/DIN, guessing the ground is common and i only need to use 1?

Got it working, cheers!

If it has 2 ground pins I would ground both of them, to be safe.


text:
How many sensors can be supported by a single Arduino unit?
I am a beginner in the Arduino world. I made some basic projects of the book that comes with the starter kit (it's was borrowed by a friend of mine) and also I used a humidity, a temperature sensors and a LCD display.
I want to buy an Arduino Uno for measure room temperature, humidity, carbon monoxide, carbon dioxin and maybe a couple more variables. I will to use 4 sensors, 1 buzzer, 1 LCD display and 1 ESP8266 serial WIFI wireless module.
After this work I will add for functionalities but as I have a lot of components I am not sure if the Arduino Uno can supports them because it has a limited quantity of pins.
Do I need an Arduino with more pins? what if I use all these pins and I need more? Can the Arduino Uno be expanded with more pins?
As the Arduino Uno is a very small computer, can its processor support all these components and their operations?

That would depend on their unspecified details, but consider that the esp8266 is a substantially more capable computer than a classic arduino you might be better just using that.

It would be best if you asked 1 question per post.

You can increase pins using shift registers

I'll be more clear, you should ask your other questions.  Just ask them in a different posts.  You probably should consider asking about temperature , co, ect sensors in different posts.  As some are non-linear, others need age compensation, still others need temperature compensation.

As a beginner you have a lot of valid questions.  As Arduino is not just UNOs I would suggest you look at the Arduino web site at all the flavors offered.  As you advance in Arduino world you will find Mega's offer more pins, Yun's can provide a Linux flavor and the MKR1000 has IoT entry.

Since the Uno has support for I2C and SPI, the exact number of pins isn't the limiting factor.

Don't forget that you also have the 10digital and 1 analogue pins on the ESP8266(E), which is a 32 bit processor capable of running at 160MHz.  Using it for WiFi to serial is like buying a Ferrari to nip 1/2 a mile to the shops once a week.

And don't forget to mark an answer as accepted, if it answers your question. This way the question will not bump again to the homepage in the "unsolved" list

An Uno has more than enough pins for the devices you described.

A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
An MQ-7 Carbon Monoxide sensor needs one analog pin.
An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
A Piezo buzzer needs one PWM pin.
The LCD with a Hitachi interface needs four digital pins.
The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.

I think you want to know how many sensors 1 Arduino can support.  But just in case, I am answering both interpretations of the title of your question:

How many different types of sensors can an Arduino support?:

With the correct software and hardware, the Aruidno can interface with almost any kind of sensor.  The exceptions include but are not limited to sensors which produce more data than an Arduino can process (such as a video camera) or sensors that require fast responses (such a time of flight laser distance sensors (LIDAR)).

How many sensors can an Arduino support at the same time?:

This depends on what processor resources are needed.  If the sensor needs the ADC there 6 channels on most Arduinos.  If you need more, there are hardware solutions.  But many here have suggested to simply add a 2nd Arduino.
To specifically address your laundry list:

room temperature

Thermistor connected to ADC.  But most are not linear, so you will have to create a look up table.

humidity

I think there is a SPI module on the market to do this.

carbon monoxide

These sensors usually require an amplifier.  And change with age & temperature.  So a lot of software here as well as hardware.

carbon dioxin

Not sure about this one.

buzzer

Self osculating? Then you only need a logic output.

1 LCD display

Alpha & numeric? Most have 4 or 8 pin Hitachi interfaces.  But you can look for a SPI or serial port LCD so as to conserve on Arduino pins.

ESP8266

This is just a serial device.  You will need the Ardino's serial port.
I'll leave it up to you to make a detailed assessment of the necessary processor resources.  Because you need to first pick out the specific hardware you will be using.
That's half the battle.  The other half is verifying the libraries for all these sensors and communication devices will not interfere with one another.  That I will leave up to you as it is not an easy task to wade through all the code for all the different libraries you will be using.  And, again, until you pick out exactly what sensors and devices you will be using it is impossible to even start analyzing as we wouldn't know which libraries to look at.

This answer has been flagged as "not an answer". Can you please elaborate on the question asked? That is, "how many sensors can an Arduino support?". I see where you are going with this answer, but it is a bit tangential.

I will try.  But the question is broad.  Since no one answered the question after almost a day, I thought to give it a try.

I think it's worth adding that you can have many I2C devices connected to the Arduino's I2C bus, so it's a good option if you need one Arduino drive many sensors. Same for SPI, except for the "slave select" line.

The question itself is a bit broad, but I'll try and provide some insight here.
The number of sensors that can be supported, and the number of pins they require, will depend on what sort of interface they use.

If your sensor has an analog interface, you will need an analog input pin for each sensor.
If your sensor has an I2C interface, you can have multiple devices sharing the same pins (a bus) provided that they have different I2C addresses (often configurable with jumpers on the device).
If your sensor has an SPI interface, you can have multiple devices using the same pins (a bus), except that each will need a chip select PIN connected to a digital I/O pin on your Arduino so that it can 'select' each device.
If your sensor has a serial interface, you can generally only have one device.

To add complexity to the problem, you can get expansion modules for the Arduino that will give you extra analog pins or other communication interfaces.
With the long list of sensors you have above, you may also be hard-pressed for program space, as most sensors will need code and/or libraries to interface with them. The Arduinos with more pins (such as the MEGA) also have more program space.
I would encourage you to do some further research on the sensors you want to use, and finding out what interface they use, and what Arduino libraries are available for them. This way, you can fully understand the requirements and limitations of any parts you want to use.
Further reading:

https://www.arduino.cc/en/Reference/Wire (I2C interface)
https://www.arduino.cc/en/Reference/SPI (SPI interface)
https://www.arduino.cc/en/Reference/Serial (Serial interface)
https://www.arduino.cc/en/Guide/Libraries (Using libraries)
https://www.arduino.cc/en/Tutorial/HomePage (Arduino tutorial)

Look at the MUX Shield, I just used one to add 48 Inputs to a MEGA making it capable of having 98 Inputs or Outputs


text:
Should I buy a retired Arduino?
I am a beginner who would like to buy an Arduino Yún (58 dollars).
It is retired so will I have any problem?
Else I can buy an Arduino Uno and an Arduino Yún Shield. But in this case I don't understand the difference between an Arduino Uno + Arduino Yún Shield and an Arduino Uno + ESP8266 serial WIFI wireless module.
Arduino Yún Shield: I can't find the price. I only found an Iduino.

ESP8266 serial WIFI wireless module: 7 dollars.

The yun has a coprocessor running a compact embedded linux distro, while the esp8266 is a simpler MCU running bare metal software or at most an RTOS.  Cost wise the latter clearly wins, though you seem to have been quoted quite a markup for it.  But your basic question is "primarily opinion based"

Yún has ethernet and USB. Which may or may not be interesting. You should get what you need, and only more if you can afford it. You could do an Arduino Uno  & ESP8266 & rasperry pi. For thuis combo there is an elaborate amount of tutorials, and will learn you about both microcontrollers and single board computers.

When a board is retired, it may:
- get no support (never had support from Arduino zelf though)
- not be readily available.
Which may or may nog be a problem.
The biggest problemen with retired boards is that they often didn't sell very well.
So they may:
- target niche applications.
- not have a lot of people post tutorials on it.
- not have/get elaborate answers on Arduino.se
I believe you should only get something that fits your needs.
Usually you van get away with an Uno, and since there are millions if (beginner) tutorials, i'd pick that as my first Arduino.
If you want to do anything more "pc-like" like USB, camera or a "server", my first pick would be a raspberry pi.
Also, since there are hundreds of tutorials.
You can choose to do it with a yún, and it may work, but you should check if there are tutorials/documentation for whatever you'd like to do with it.

It is retired so will I have any problem?
It depends on what you want to do with your arduino. If you need a project that requires future support then dont buy a retired board. If you just want to do basic beginners stuff (like blinking LEDs, controlling motors, sending serial information wired or with an add on shield to send wireless information)-then any arduino can do these basic projects and probably at a cheaper price than 58 dollars.

The question of the Arduino Yun being retired can be answered here:
http://www.arduino.org/forums/yun/retriered-boards-894?p=3495&hilit=Retired#p3495
At least regarding Arduino.org the answer is no. The Yun is not retired.

The Yun has also been recently moved from the retired section of the arduino.cc products page to the active products chart. I think this is a result of the dispute between .cc and .org being settled.


text:
Arduino project feasibility
Question completely rewritten
Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.
However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

a non-latching Hall sensor is to be connected to Analog 0, analogRead() to return a [0,1023] value, used as a proximity sensor. This should be straight forward.

Question →

while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.

Why a downvote, very new to Arduino are the questions too obvious?

Because your question is too broad. If you are a beginner, start with simpler projects (blinking LED, control the LED via serial, now try it with a motor, read a sensor and print it to serial, try to combine those projects, ...). After you know how to use do simpler stuff, you can use them together to make more complex projects. And learn to structure your program as a state machine and use millis() instead delay() or else doing multiple stuff at the same time won't work or be buggy. With that, you would be able to ask more specific questions.

Completely rewrote the question to simplify the text and go to the point.

Yes, this is possible, but you will need to learn about doing non-blocking serial communication on the Arduino, and perhaps on the PC side as well (though you may just be able to use a terminal program there).  Getting non-blocking serial right is unlikely to be either easier or harder on Arduino than on most other embedded platforms - it is entirely do-able, but tricky, and there are a lot of mistakes that can make for a system that "works sometimes".  The key will be to make few assumptions - don't assume when characters will arrive, or how much time will be between them, etc.

@ChrisStratton Ah.. so there is no convenient USB I/O function.. Did a lot of serial in the past, and wished I could avoid that! Thanks anyway

Your classic Arduino is conceptually a serial device.  On a board such as the Uno the USB port goes through a USB-serial converter (though implemented in a second MCU).  On one such as the Leonardo it actually runs into the application processor, but the default handling still treats it as a serial device.  It is true that USB is different - it both has greater latency, but also if used as USB all the way through gives you some framing possibilities missing in legacy serial.  These tend to be advanced topics however.

It's perfectly doable. As Chris Stratton puts it, it's all about
implementing non-blocking serial communication:

whenever you receive a character, you store it in a buffer
whenever you have a complete command in the buffer, you process it and
reset the buffer

For a line-oriented protocol, it may look something like:
/* Process incoming characters if any. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];  // incoming command
    static int length = 0;           // command length

    int data = Serial.read();
    if (data == '\r') {              // complete command
        buffer[length] = '\0';       // terminate the string
        if (length)
            exec_command(buffer);    // process
        length = 0;                  // reset buffer
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;     // buffer incoming character
}

For a more complete example, you may want to take a look at this simple
Arduino command line interpreter. You connect a terminal
emulator to the Arduino at 9600/8N1, type the "help" command and it
displays:
mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

You can use it as a template, replace existing commands or add new ones
(the interpreter is just a long if ... else if ...) and – since
it's all non-blocking – add whatever you want to loop().


text:
A more elegant way to deal with timers without using delay()?
I am looking for a more elegant way to write a function that performs timer-based tasks as in the case of the code below, which essentially collects 5 sample values from a microphone module over a given period of time and then computes their average. It is important that it does not use the delay() function because other tasks are supposed to run in the background which should not be affected by the delay.
  int sensorPin = A0;
  int ledPin = 13; //  pin for the LED
  int sensorValue = 0; // variable to store the value coming from the sensor
  unsigned long timer;
  int interv = 50;
  unsigned long sampleArray[] = {0, 0, 0, 0 , 0};
  unsigned long millisaver;

  void setup ()
  {
    pinMode (ledPin, OUTPUT);
    Serial.begin (9600);

  }

  void loop ()
  {

    if (millis() > 2000) {
      if (millis() < 2050) {
        millisaver = millis();
        timer = (int) millisaver;
        Serial.println(timer);
      }
      if ( millis() > timer && millis() < timer + interv ) {
        sampleArray[0] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv && millis() < timer + interv*2 ) {
        sampleArray[1] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*2 && millis() < timer + interv*3 ) {
        sampleArray[2] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*3 && millis() < timer + interv*4 ) {
        sampleArray[3] = sensorValue = analogRead (sensorPin);

      }
      else if ( millis() > timer+interv*4 && millis() < timer + interv*5 ) {
        sampleArray[4] = sensorValue = analogRead (sensorPin);
      }
      else if ( millis() > timer+interv*5) {
        unsigned long averageVal = (sampleArray[0] + sampleArray[1] + sampleArray[2] +sampleArray[3] + sampleArray[4])/5 ;
        Serial.println(averageVal);
        millisaver = millis();
        timer = (int) millisaver;
      }
    }
  }

Other than using interrupts?

Might be possible to adjust the ADC clock frequency to match 20 Hz and use the ADC interrupt for data collect.

yes, other than using interrupts, if possible.

@Grovelli why not an interrupt? That is precisely what they're for. The Arduino libs are great, but at some point, you're going to want to understand the actual Mcu on the board. I know the data sheets are daunting, but it is well worth diving in.

By the way, do you know what the average of a sound wave is over time? You don't need a microphone to discover that it's 0.

I should have been more precise in my description concerning what average value I want to refer to, namely the average of volume peaks (but you are right, in the present form it will be 0).

For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure
ADC with Timer 0 Overflow and use every 20 measure only.
But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.
As an auto trigger source can be used one of these:

Free Running Mode
Analog Comparator
External Interrupt 0
Timer/Counter 0 Compare Match A
Timer/Counter 0 Overflow
Timer/Counter 1 Compare Match B
Timer/Counter 1 Overflow
Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:
void setup() {
    Serial.begin(57600);

    // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
    ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
    ADCSRA |= _BV(ADATE); // enable auto trigger mode
    ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

    analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
}

int8_t sample_count = 0;
int8_t sample_index = 0;
uint16_t  samples[] = {0, 0, 0, 0, 0};
uint16_t sample_sum = 0;

void loop() {
    if (ADCSRA & _BV(ADIF)) {
        ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
        if (++sample_count == 20) {
            sample_count = 0; // reset sample_count, as we wan't every 20th

            sample_sum -= samples[sample_index];
            samples[sample_index] = ADC; // read value
            sample_sum += samples[sample_index];

            if (++sample_index == 5) { // reset index and count and send average
                sample_index = 0;
                Serial.println(sample_sum);
            }
        }
    }
}

Thank you for your detailed answer! I will research on the ADC auto trigger mode as I am frankly new to it.

You probably shouldn't mess with TIMER0's timing. The Arduino libs use that timer for things like millis(). Which libraries use which timers is described here. https://arduino-info.wikispaces.com/Timers-Arduino

@RubberDuck I didn't mess with TIMER0 timing. I did't touch it at all. I've just used it as auto trigger source to perform ADC conversion every 1.024ms and I'll use every twenty measure of these.

My misunderstanding @KIIV

You need to make a function which is pretty much completely self contained. Within the function should be a counter so it knows which sample it is on, and a timestamp to know when it should next run. The function should also inform the caller when it has a full sample set to process.
I haven't tested this (don't know if it even compiles) but something like this might work:
bool getSample(uint8_t pin, unsigned long *samples) {
    static uint32_t ts = millis();
    static uint8_t sampleNumber = 0;

    if (millis() - ts >= 50) {
        ts += 50;
        samples[sampleNumber++] = analogRead(pin);
        if (sampleNumber == 5) {
            sampleNumber = 0;
            return true; // We have 5 samples
        }
    }
    return false; // We don't have 5 samples yet.
}

// ... later ...

if (getSample(sensorPin, sampleArray)) {
    // Process Samples
}

You didn't say what you want to do with those samples. If you want to
estimate the level of sound intensity, your whole approach is completely
wrong. First, your sampling rate (20 Hz) is way too low: you should
sample at least at twice the frequency of interest, typically at
8 kHz or more. Then you have to subtract the DC offset added by the
microphone module, then square the result in order to get an
instantaneous intensity, then low-pass filter to get a usable intensity
reading. As Majenko said, if you average (or low-pass filter) the
samples before squaring, you would detect zero sound.
I've written a sound meter program for an Arduino Uno that does exactly
that, and it's available as a GitHub Gist:
sound-meter.ino.
It uses the auto-trigger mode as explained by KIIV, but with free
running mode instead of a timer. This gives 9.6 kHz sampling rate.

My apologies, I just realized low_pass() was not a standard function off a library.

@Grovelli: It's an exponentially weighted moving average, the digital analog of an RC filter: one of the simplest low pass digital filters you can make.


text:
Port D isn't Working as Input
I'm using an Atmega328p SMD with 32 pins.  I'm trying to get several pins on Port D to function as inputs.  As outputs, they work fine, but for some reason, not as inputs.  Here's a simple example of what I'm dealing with.
void setup() {

DDRB |= (1<<PB3);  //Set up an output on PB3 for an LED
DDRD = B00000000;  //All of Port D set as inputs
DDRC = B00000000;  //All of Port C set as inputs
}

void loop() {

int Power = (PIND & (1 << PORTD5));  //Read input

  if(Power == 1){
PORTB |= (1 << PORTB3);      //set high
  }
  else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

I get no response from my LED like this, no matter which pin on Port D I use as an input.  But when I simply change over to Port C, it works fine.
int Power = (PINC & (1 << PORTC5));  //Read input

Ideas?

You check if power is 1, but it will never be 1. Instead it will be 1<<5 or 32. Better use:
if(Power != 0){
  PORTB |= (1 << PORTB3);      //set high
}
else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

That looks like it worked.  But now I have to ask why would it work on Port C as the way I had it?

Sorry, I figured that out.  I was using PC0, so I guess that would equal 1.  Sorry for the confusion in the example by using PC5, I didn't think that was an issue.

I was puzzled by that too. Glad you figured it out. Best of luck,