title: Unclear GET request mixed values

text:
# Question
Title: Unclear GET request mixed values
In my Uno code, I access to a page in my server and retrieve that value and make decision upon that value.

I get this kind of response,

```
Connected to server
on
on
off
off
on
off
[WiFiEsp] TIMEOUT: 116

Disconnecting from server.

```

Which should just be `on` or `off`.

This is my code for testing :

```
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif

char ssid[] = "RPi";            // your network SSID (name)
char pass[] = "raspberry";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.50.1";

// Initialize the Ethernet client object
WiFiEspClient client;

int c =0;
int testLED = 12;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET /simple.txt HTTP/1.1");
    client.println("Host: localhost");
    client.println("Connection: close");
    client.println();
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
  if (client.available()) {
     c = client.read();

     switch(c){
          case '0':
                 Serial.println("off");
                 digitalWrite(testLED, LOW);
                 delay(2500);
                 break;

          case '1':
                 Serial.println("on");
                 digitalWrite(testLED, HIGH);
                 delay(2500);
                 break;
      }
        }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true);
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

My `simple.txt` file just has 1.

Why this code outputs a gibberish value? Is it a problem with the way I retrive data? Raspberry pi is working as my network server.

Thanks in advance.

# Answer
When you send a GET request in HTTP you get a HTTP response back, not just the contents of the file you requested.

For instance, your request may result in a response of:

```
HTTP/1.1 200 OK
Date: Thu, 28 Dec 2017 11:02:21 GMT
Server: Apache/2.4.25 (Ubuntu)
Last-Modified: Wed, 05 Apr 2017 09:40:30 GMT
ETag: "2c39-54c682ee19688"
Accept-Ranges: bytes
Content-Length: 3
Vary: Accept-Encoding
Connection: close
Content-Type: text/plain

1

```

As you can see there's plenty of occurrences of 0 and 1 in there to trigger your LED.

You need to parse the incoming data better. Read it line by line and only start reacting to the content after the blank line that indicates the division between header and body.
> 1 votes

# Answer
I found the answer for my question. @Majenko's answer helped me a lot.

I removed HTTP response given by the server and just changed few line in my original code. Also added `#` in-front of the number in my server's `simple.txt` file.

Also this arduino-forum post

```
void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
while(client.available() > 0)
{
  char c = client.read();
  if(c == '#')
  {
     while(client.available() == 0) { } // Do nothing while we wait for the next value
     c = client.read();
     if(c == '1'){
        Serial.println("On");
        digitalWrite(testLED, HIGH);
        delay(2500);
     }
     else if(c == '0'){
        Serial.println("Off");
        digitalWrite(testLED, LOW);
        delay(2500);
     }
  }
}

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    //client.stop();

    // do nothing forevermore
    while (true);
  }
}

```
> 0 votes

---
Tags: arduino-uno, esp8266, home-automation
---


title: RFID+Fingerprint sensor code

text:
# Question
Title: RFID+Fingerprint sensor code
I'm trying to create a security door system that uses an RFID and fingerprint sensor (Adafruit) to allow/deny access to a door. I have the fingerprint sensor and RFID hooked up to an LED, but the code isn't working very well. I want the LED to light only and only when both fingerprints and RFID are verified. Here is my preliminary code.

```
//HEADERFILES
#include <SPI.h> //rfid
#include <MFRC522.h>//rfid
#include <Adafruit_Fingerprint.h> //FINGERPRINT
#include <SoftwareSerial.h> //FINGERPRINT
#include<stdint.h> //FINGERPRINT

//rfid settings
#define RST_PIN         9          // rfid pin 9 RST_pin
#define SS_PIN          10         // rfid pin 10 SS_pin
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
String read_rfid;
String ok_rfid_1 = "cbb427b2"; //white card
String ok_rfid_2 = "0ebb14f39"; //blue key chain

//fingerprint settings
int getFingerprintIDez();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (YELLOW wire)
SoftwareSerial mySerial(2, 3);
//activates serial communication on pin 2 & 3
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

//output garage door pin
int door = 7; //motor to door

void dump_byte_array(byte * buffer , byte bufferSize) { //why so important
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void setup() {
  //RFID setup
  Serial.begin(9600);
  // Initialize serial communications with the PC
  while (!Serial);
  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  finger.begin(57600);
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 RFID
  pinMode (door, OUTPUT);
  //FINGERPRINT setup
  {
    while (!Serial);  // For Yun/Leo/Micro/Zero/...
    if (finger.verifyPassword()) {
      Serial.println("Found fingerprint sensor!");
    } else {
      Serial.println("Did not find fingerprint sensor :(");
      while (1);
    }
    Serial.println("Waiting for valid finger...");
  }

}

// OK success!

p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
  Serial.println("Image converted");
  break;
case FINGERPRINT_IMAGEMESS:
  Serial.println("Image too messy");
  return p;
case FINGERPRINT_PACKETRECIEVEERR:
  Serial.println("Communication error");
  return p;
case FINGERPRINT_FEATUREFAIL:
  Serial.println("Could not find fingerprint features");
  return p;
case FINGERPRINT_INVALIDIMAGE:
  Serial.println("Could not find fingerprint features");
  return p;
default:
  Serial.println("Unknown error");
  return p;
}
}

//DOOR/OUTPUT PIN PROPERTIES CHANGE TO REFLECT HOW FAST AND HOW LONG MOTOR     PULLS DOOR USING DIGITALWRITE; BREAK..   //USING LED FOR NOW

void open_door() {
  digitalWrite (door, HIGH);
  delay (2000);
  digitalWrite (door, LOW);
}

void loop() {
  // RFID LOOP SETTINGS                                                   `
  if ( ! mfrc522.PICC_IsNewCardPresent()) {     // Look for new cards
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial()) {       // Select one of the c ards
    return;
  }
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);
  // FINGERPRINT LOOP SETTINGS

  getFingerprintID();  // start fingerprint sensor
  delay(100);

  uint8_t getFingerprintID() {
    uint8_t p = finger.getImage();
    switch (p) {
      case FINGERPRINT_OK:
        Serial.println("Image taken");
        break;
      case FINGERPRINT_NOFINGER:
        Serial.println("No finger detected");
        return p;
      case FINGERPRINT_PACKETRECIEVEERR:
        Serial.println("Communication error");
        return p;
      case FINGERPRINT_IMAGEFAIL:
        Serial.println("Imaging error");
        return p;
      default:
        Serial.println("Unknown error");
        return p;
    }

    p = finger.fingerFastSearch();
    if (p == FINGERPRINT_OK && read_rfid == ok_rfid_1) {
      Serial.println(ok_rfid_1);
      open_door();
    }

  }

```

**And this is the error I am getting**

```
Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

fingerprint:127: error: expected unqualified-id before '{' token

 {

 ^

exit status 1
expected unqualified-id before '{' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

I am new to this so please bear with me and explain in childish manner if possible.

# Answer
Can't say I have read what you posted here or what you're trying to do, however nonetheless I have fixed the errors in your post. This will compile no problem. Good luck with your project.

```
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
int getFingerprintIDez();
SoftwareSerial mySerial(2, 3);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

//HEADERFILES
#include <SPI.h> //rfid
#include <MFRC522.h>//rfid
#include<stdint.h> //FINGERPRINT

//RFID settings
#define RST_PIN         9          // RFID pin 9 RST_pin
#define SS_PIN          10         // RFID pin 10 SS_pin
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
String read_rfid;
String ok_rfid_1 = "cbb427b2"; //white card
String ok_rfid_2 = "0ebb14f39"; //blue key chain

int door = 7; //motor to door

void dump_byte_array(byte * buffer , byte bufferSize) {
  //why so important
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void setup() {
  //RFID setup
  finger.begin(57600);
  Serial.begin(9600);
  // Initialize serial communications with the PC
  while (!Serial);
  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 RFID
  pinMode (door, OUTPUT);
  //FINGERPRINT setup
  {
    while (!Serial);  // For Yun/Leo/Micro/Zero/...
    if (finger.verifyPassword()) {
      Serial.println("Found fingerprint sensor!");
    } else {
      Serial.println("Did not find fingerprint sensor :(");
      while (1);
    }
    Serial.println("Waiting for valid finger...");
  }
}

// OK success!

void open_door() {
  digitalWrite (door, HIGH);
  delay (2000);
  digitalWrite (door, LOW);
}

void loop() {
  // RFID LOOP SETTINGS
  if (! mfrc522.PICC_IsNewCardPresent()) {
    // Look for new cards
    return;
  }
  if (!mfrc522.PICC_ReadCardSerial()) {
    // Select one of the cards
    return;
  }
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);
  // FINGERPRINT LOOP SETTINGS
  getFingerprintID();  // start fingerprint sensor
  delay(100);
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK success!
  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
  // found a match!
  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);
}

```
> 1 votes

# Answer
```
default:
  Serial.println("Unknown error");
  return p;
}
} <-- Why?

```

Proper indentation shows that you have an extraneous closing curly brace.
> 1 votes

---
Tags: arduino-uno, serial, sensors, rfid
---


# Question
Title: How to send MFRC522 data to a C# app using a NodeMCU TCP server?
I am trying to send MFRC522 data to a C# application through a NodeMCU acting as an access point for the C# app. I have modified the code I got from this site.

```
#include ESP8266WiFi.h>
#include SPI.h>
#include MFRC522.h>

const char* AP_SSID ="IoT4143" ;
const char* AP_PASSWORD ="iot4143";

#define RST_PIN D3
#define SS_PIN D4

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

WiFiServer server(80);
WiFiClient client;

void wifiConnect() {
  WiFi.disconnect();
  WiFi.softAP(AP_SSID, AP_PASSWORD);

  int watchDog = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    watchDog++;
    if(watchDog == 60) {
      WiFi.disconnect();
      WiFi.printDiag(Serial);
      watchDog = 0;
      return;
    }
  }
  server.begin();
}

void setup() {
  Serial.begin(115200);
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
  wifiConnect();
}

void loop() {
  //Are we connected to WiFi?
  if(WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }

  //Wait for a connection attempt
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  int watchDog = 0;
  while(!client.available()) {
    delay(1);
    if(watchDog == 10000) {
      watchDog = 0;
      return;
    }
    watchDog++;
  }
  sendData();
}

void sendData() {
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  client.flush();

  // Match the request
  while(request=="READSTOP") {
    Serial.println("RFID READING STARTED..."); //Forward to C# App
    if (!mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    // Select one of the cards
    if (!mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    // Dump debug info about the card; PICC_HaltA() is automatically called
    client.print(mfrc522.uid));
  }
  Serial.println("RFID READING STOPPED"); //Stop server
  delay(1);
  client.stop();
}

```

I am very new to hardware/network programming. I don't know what will be possible errors in this code and whether it will work or not.

When I verified the code in the Arduino IDE, there was an error on this line of code:

```
client.print(mfrc522.uid));

```

> error:= no matching function for call to 'WiFiClient::print(MFRC522::Uid&)'

When the connect button in the application is clicked the "READSTART" string is sent to NodeMCU and when disconnect is clicked the "READSTOP" string is sent.

Please help!

# Answer
MFRC522::uid is a struct (see source code). There's no defined way to print it.

If you want to write the raw bytes over the TCP connection, you can just use

```
client.write((uint8_t*)mfrc522.uid.uidByte, mfrc522.uid.size);

```

If you want to write it as ASCII text, you can use the following:

```
void byte_to_str(char* buff, uint8_t val) {  // convert an 8-bit byte to a string of 2 hexadecimal characters
  buff[0] = nibble_to_hex(val >> 4);
  buff[1] = nibble_to_hex(val);
}

char nibble_to_hex(uint8_t nibble) {  // convert a 4-bit nibble to a hexadecimal character
  nibble &= 0xF;
  return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
}

void printHEX(Stream &s, uint8_t *data, size_t length) {
  char *buffer = new char[length*2];
  for (size_t i = 0; i < length; i++) {
    byte_to_str(&buffer[i*2], data[i]);
  }
  s.write(buffer, length*2);
  delete[] buffer;
}

```

Then use it like this:

```
  printHEX(client, mfrc522.uid.uidByte, mfrc522.uid.size);

```

It loops over all bytes in the UID, converts them to ASCII (hexadecimal representation, so 2 characters per byte), and then writes the text over the TCP connection.

(Note that there are many other problems with your code as well, e.g. the includes are missing the opening '\<'.)
> 1 votes

---
Tags: esp8266, arduino-ide, rfid, nodemcu, tcpip
---


# Question
Title: Controlled power-down for automotive application
I'm working on an automotive project that uses an Arduino Mega 2560.

What I need is a circuit that allows the unit to sense when the external power feed drops (triggering an interrupt?) so that the software can preserve state to the non-volatile memory and then shut down.

I was thinking some sort of capacitor/battery to run it once the eternal feed drops, but the hardware side of things is not my strong skillset - I'm more of a software kinda person.

# Answer
> 1 votes
Consider a battery backup for low power devices. This article from allaboutcircuits.com discusses how to build a 12 to 5 volt power supply with its own battery backup.

In your specific case, run a second 12 to 5 volt regulated signal to one of the processor's digital inputs. When the 12 volts shuts off, the signal to the processor's digital input will go low. Poll this input and when you see it go low shutdown the processor or put the processor into a deep sleep mode to draw as little current as possible from the back up battery.

The ATmega2560 processor may not be the best chose for this. There are processors that can drop down into the nA range and still wake up periodically to check if they should be powered all the way back up.

---
Tags: arduino-mega, power
---


title: Alternative of relay

text:
# Question
Title: Alternative of relay
I am carrying out a physics experiment using an Arduino. This experiment requires accurate time measurements of upto a millisecond. However I am using a relay to turn on/off an electromagnet and there is a maximum lag of 10ms due to the relay. I am a complete beginner. Please suggest alternative mechanisms to switch the electromagnet and save those precious milliseconds. P.S. - the magnet is driven by 12V 2.5A DC.

# Answer
> 3 votes
A relay is just an electromagnet, and the same circuit that can drive a relay can drive an electromagnet. You just need to make sure it can handle the power.

The simplest circuit is to use an N-channel MOSFET:

simulate this circuit – Schematic created using CircuitLab

Just make sure that the MOSFET can handle the required power dissipation and switches on fully at below 5V on the gate (a gate threshold voltage of less than 3V is ideal).

# Answer
> 1 votes
I think you need something like a relay driver.

On this site:

http://www.learningaboutelectronics.com/Articles/Relay-driver-circuit.php

i found this picture:

In "practical electronics for inventors (fourth edition)" is a similar picture with following text on page 445:

**"Here, an npn transistor is used to control a relay. When the transistor's base receives a control voltage/current, the transistor will turn on, allowing current to flow through the relay coil and causing the relay to switch states. The diode is used to eliminate voltage spikes created by the relay's coil. The relay must be chosen according to the proper voltage rating, etc."**

You can replace the relay with the magnet. But you will still need a diode. When you switch off the magnet it will generate a voltage and will try to push the current (there is energy saved in the coil). This diode will help it to unload the energy. Otherwise this energy can destroy something.

---
Tags: arduino-uno, relay, time, switch
---


# Question
Title: Purpose of USB (FTDI) and ICSP connectors
As an Arduino newbie I am a little bit confused about possible ways of programming and communicating with this device. I have done some research and it seems that:

ICSP is used for programming with a bootloader in MCU.

The USB (FTDI) port is used (mostly) for sending text messages to the PC and programming without a bootloader.

Am I right? How can I detect whether I have a bootloader installed (Uno R3 clone)? Thank you very much!

# Answer
The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.

The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.

The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.
> 7 votes

---
Tags: bootloader, ftdi, icsp
---


# Question
Title: How do I use the Arduino Mega as a 16-bit SPI slave?
I have to interface an Arduino Mega as a slave with a SPI master running at **1 MHz** `SCK`. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in `acc` and return local data `ret`, which is simply an integer to be incremented every transaction.

However, while the master data is stored in `acc` (verified through serial output), the data returned to the master is not the value in `ret`. Instead, the first response byte is correct (MSB of `ret`) and the second response byte is just the first byte received by the Mega, which was the value already present in `SPDR`.

How do I send the second byte of `ret` as the second byte of the response? What am I doing wrong?

```
// SPI Slave

#include <SPI.h>

// return to master
volatile unsigned int ret;

// accept from master
volatile unsigned int acc;

// MSB/LSB indicator
volatile byte SB;

void setup(void)
{

  ret = 0;
  SB = 0;

  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // set CPOL, CPHA modes
  // byte dataMode = 0;
  // SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;

}

// SPI interrupt routine
ISR(SPI_STC_vect)
{

  if(SB == 0) {
    acc = SPDR << 8;
    SPDR = ret;
    ret++;
  }
  else {
    acc += SPDR;
    SPDR = ret >> 8;
  }
  SB = (SB + 1) & 0x01;

}

void loop(void)
{
  // interrupt processing only
}

```

**Edit** Changed `SCK` from 16 MHz to 1 MHz

# Answer
> 2 votes
I'm late to the party, but...

I experienced exactly the same issues having a Arduino Uno as a SPI slave communicating to a Arduino Mega as SPI master. My conclusion is that the slave must take some time to process the SPI transfer of the first byte (your code in the SPI interrupt handler), but the master is not waiting for it. So the transfer of the second byte starts before your handler is completely executed, so the master receives the same byte again.

In my case, I fixed this with an ugly sleep in the master before sending the second byte:

```
SPI.beginTransaction(spi_settings);
word input = 0;
digitalWrite(spi_devices[port].pin_ss, LOW);
input |= SPI.transfer(output >> 8) << 8;
delayMicroseconds(20); // Must give time to slave to read first byte
input |= SPI.transfer(output);
digitalWrite(spi_devices[port].pin_ss, HIGH);
SPI.endTransaction();

```

Not elegant, but it works.

# Answer
> 1 votes
You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.

> In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of the clock signal, the minimum low and high periods should be: Low period: longer than 2 CPU clock cycles. High period: longer than 2 CPU clock cycles.

This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz).

Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:

1. Time between slave mode chip select and clock must be stretched to compensate for the ISR latency.
2. The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).

Cheers!

---
Tags: arduino-mega, spi
---


# Question
Title: Can I measure multiple photoresistors from one pin?
I would like to make a laser sensor to detect light coming from a 650nm diode. My current idea would be to use CdS photoresistors/LDRs. I want to measure a few (4-8?) at once, where light falling onto any one of them generates a signal - I don't care from which sensor it actually came. However, I would like to put as many sensors on as few pins as possible.

I've already somewhat figured out that putting LDRs in parallel isn't ideal, because any changes in voltage will become smaller the more I use. Instead, it would seem like a better idea to build some kind of 'switch' by putting each LDR together with a fixed resistor and a transistor. How exactly would a circuit for this look like, or are there better ways to do it?

# Answer
> 1 votes
If response time is critical (on the order of about a quarter of a second) consider using photo diodes instead of Cadmium sulfide cells.

Also, consider using an Arduino with more ADC ports. The number of ADC ports is usually a constraint of the processor used. Different Arduinos use different processors. Some may have more ADC ports.

Finally, to utilize a single ADC port for multiple unknown resistances, consider using a resistor network where all the unknown resistances and a known pull down resistance are connected to the ADC port. Then, in turn, using as many Arduino digital pins as there are unknown resistance, apply a digital high to only 1 unknown resistance. Keeping the digital pins to all the other unknown resistance in a high impedance state. That is, change them from OUTPUT to INPUT digital ports. Then take an ADC sample. Apply this same procedure for all the other unknown resistances. Consider adding a delay after changing the state of the digital pins to allow for the ADC input to acclimate to the new voltage.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 0 votes
I think you can take them paralel to each other and in series with a simple resistor. The point within the series can be used as input voltage. Everytime the input voltage is higher than the reference voltage you can generate an interrupt from the comparator. This means if one of x resistors decreases its value this will affect the upper half resitance. Simply it will decrease the value too. Because of this the input voltage will increase and will be above of the reference voltage. This will produce interrupt (signal).

The Question is how accurate will it work. The resistors are nor 100% accurate because of that the circuit will not work accurate. What can accept? What is OK and what not?

---
Tags: sensors, arduino-nano, photoresistor
---


# Question
Title: Arduino Due not executing code after power on
My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.

I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.

My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?

What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.

EDIT: Adding picture and link to the board used. https://www.amazon.de/gp/product/B016D5KYF6/ref=oh\_aui\_detailpage\_o00\_s00?ie=UTF8&psc=1

# Answer
After some more research I found out that

a) the issue applies to some Due boards only, not all

b) newer boards seem to have fixed the issue

c) there's a software (firmware update) and hardware (10k resistor) solution

I went with the hardware fix shown here: http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/

I did not have an SMD resistor at hand, so mine looks ancient but does the job. Hope that helps others, too.

addendum:

The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.

The fix is simple: you just solder a 10K resistor across the top of this mosfet:

resistor about to be soldered on

resistor designated as R99
> 1 votes

---
Tags: arduino-due, reset
---


title: prgramming arduino led on then off

text:
# Question
Title: prgramming arduino led on then off
i want the led to light at the beginning and stays like this for a while then turns off, so i wrote:

```
int led=13;
void setup() {
  pinMode(led,OUTPUT);
}
void loop() {
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}

```

as i understand it should start with high means on digitalWrite(led,HIGH)...and stays like this for 5000us delay (5000) then it should turn off with digitalWrite (led,LOW). but why its not working, it starts with off for afew seconds then stays on..what i understand wrong with these simple steps ????

# Answer
> 1 votes
It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.

# Answer
> 1 votes
The "loop()" will keep repeating itself, turning the led on and off forever. If you want turn the led on just once, put the commands for turn the led on in "setup()" section:

```

void setup() {
    pinMode(led,OUTPUT);
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}
void loop() {
}
```

Other method would be add a variable to count how much times the led should light. I copied the following sketch from here

```

int ledPin =  13;    // LED connected to digital pin 13
int alreadyBlinked = 0;

// The setup() method runs once, when the sketch starts
void setup()   {
pinMode(ledPin, OUTPUT);    // initialize the digital pin as an output:
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
     if(alreadyBlinked == 0)
     {
            digitalWrite(ledPin, HIGH);   // set the LED on
            delay(5000);                  // wait for five seconds
            digitalWrite(ledPin, LOW);    // set the LED off
            alreadyBlinked = 1;
      }
}

```

When the variable "alreadyBlinked" is set to 1, the led will not turn on again.

# Answer
> -1 votes
That delay does not do anything but wasting 5 seconds...you need to do like:

```
void loop() {
    digitalWrite(led,HIGH);
    delay (2500);
    digitalWrite (led,LOW);
    delay (2500);
}

```

The code runs sequentially...in your code after turning off the led it immediately turns it on again and waits 5 seconds...this is so fat that you do not notice it.

---
Tags: led, arduino-uno
---


# Question
Title: Is there GUI to flash a sketch with new variables?
I'm dabbling in a project and would like to add a feature, but I need some help from the community.

My project returns a response from the wunderground api and lights an led based on the temperature in the response. I plan to enclose the circuits and use a single led on the enclosure to display the temperature. I have most of the sketch logic knocked out, but need help with sharing the project.

If I gave this project to someone, they would need to update the sketch to include their wifi name and password, as well as the zip code where they live.

Is there a way I can do this without using the arduino ide? A use case for this would be: the user plugs the arduino into their machine, the gui loads, the user would enter variables, and then the board would get flashed with the new variables.

Is this a pie in the sky proposition, or something that could be implemented?

Thanks for your input.

# Answer
> 2 votes
The common way to do this is to build the configuration UI into your program. Then the user has no need to be messing with the firmware.

Since your device has WiFi this can easily be done by serving a configuration web page that is loaded in the browser. But how can you make a connection before the credentials for the WiFi router have been configured? The answer is for the device to serve as an access point (AP). So you connect a computer with WiFi to the device's AP, open the configuration page in the browser on that computer, and then configure the credentials as well as any other configurations you might like.

The configuration parameters are written to EEPROM so that they will be preserved.

In its most simple form there would be a specific IP address that must be opened in the browser but more user friendly is to create a captive portal so that after connecting to the AP any URL opened in the browser will load the configuration page.

Of course all this will increase the memory usage of your program and apparently you are using the Arduino Uno so this is fairly scarce to begin with. You'll need to determine whether there is enough extra memory for it.

---
Tags: arduino-uno, wifi, ui
---


title: Arduino Uno alarm interrupt

text:
# Question
Title: Arduino Uno alarm interrupt
I am trying to create a temperature-humidity monitor using Arduino and I want to power it using a battery. So, power efficiency is of interest. I am trying to put the Arduino to sleep for x-time (10sec for testing now). I am using a DS3231 alarm as an interrupt on pin 2 to wake-up. I am using the tutorial here along with its associated RTClibExtended library. Here is the code I am using:

```
#include "DHT.h"
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <stdlib.h>
#include <avr/interrupt.h>      // library for interrupts handling
#include <avr/sleep.h>          // library for sleep
#include <avr/power.h>          // library for power control

#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int interval_sec=10; //An alarm every 10 sec
DHT dht(DHTPIN, DHTTYPE);

void setup () {

  Serial.begin(9600);

  delay(3000); // wait for console opening

  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);

  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);

  Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

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

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    /**Temperature and Humidity**/
    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit
    //float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    //if (isnan(h) || isnan(t) || isnan(f)) {
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C\t");

    delay(3000); // wait for console

    /**INTURRUPT**/
    DateTime nextAlarm = now + TimeSpan(0, 0, 0, 10);
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.minute(), nextAlarm.hour(), nextAlarm.second());   //set your wake-up time here
    rtc.alarmInterrupt(1, true);
    delay(3000); // wait for console
    attachInterrupt(0, wakeUp, LOW);       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);

    Serial.println();
    delay(3000);
}

void wakeUp()        // here the interrupt is handled after wakeup
{
}

```

The Arduino is going to sleep as expected, but not waking up. Where am I going wrong?

Here is the output:

> Initialisation complete. 2017/6/7 (Wednesday) 12:42:49 Humidity: 36.90 % Temperature: 25.60 \*C
> Alarm at:12
> 42
> 59

# Answer
After trying for a few hours, I was able to figure it out.

The change required is:

```
rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1);   //set wake-up time here

```

So, in the original code, the order of arguments as well as the number of arguments passed to *rtc.setAlarm()* was wrong. Even though we are not interested in the "day" part (last argument) for setting the alarm, it requires a value. Using *ALM1\_MATCH\_HOURS* ensures that we match the alarm time to seconds, minutes, and hours ignoring the day part.

**Improvement**

Instead of hardcoding the alarm interval, the global variable called *interval\_sec* can be set at the top and used to set the alarm time:

```
DateTime nextAlarm = now + TimeSpan(0, 0, 0, interval_sec);

```
> 0 votes

# Answer
In RTClibExtended.h it is important to always include all arguments: seconds, minutes, hours, daydate. If 0 value is used then this means "always" for that argument.

**Example:**

```
RTC.setAlarm(ALM1_MATCH_SECONDS, 30, 00, 0, 0); // activate every minute at 30 seconds
RTC.setAlarm(ALM2_MATCH_MINUTES, 0, 01, 0, 0); // activate every hour at 01 minutes
RTC.setAlarm(ALM1_MATCH_HOURS, 33, 18, 0); // activate every day at 18:33

```

(note: this example is copied from RTClibExtended.h examples, author does not adhere to his own rule to include seconds, even in ALM2. But it works). Any suggestions or corrections are welcomed!
> 0 votes

---
Tags: arduino-uno, interrupt, rtc
---


# Question
Title: Connecting multiple clients to a server in Wifi
What is the best method or retrieving information such as temperature from multiple wifi clients with a ESP8266-01 ? I have one server and five client running with ESP8266. I have seen post ang Get method. JSON files. client-server transfers. What is the best method to do that ? I am reading temperature so I do not need the clients to be all connected at the same time. So reading the client one after another in a loop would be great. thanks in advance

Ken

# Answer
you do not need http for this. use plain socket communication. create a WiFiServer on every 'sensor' and ask from the main esp8266 over WiFiClient object. the WiFiServer creates a WiFiClient object and the Clients can exchange what you want.

snippet from my code:

```
void loop() {
  WiFiClient client = telnetServer.available();
  if (!client) {
    delay(100);
    return;
  }
  if (client.status() != 4) {
    client.stop();
    delay(1000);
    return;
  }
  while (client.connected()) {
    if (!client.available())
      continue;
    char c = client.read();
    if (c == '\n') {
      long v = s.toInt();
      s = "";
      analogWrite(PWM_PIN, v);
      v = readElSens();
      client.println(v);
    } else {
      s += c;
    }
  }
  delay(100);
}

```
> 0 votes

---
Tags: esp8266, wifi
---


title: Multiple delays

text:
# Question
Title: Multiple delays
I have a sketch with multiple functions in it. The 2 main functions in that sketch are `get_data` and `post_data`.

Now these functions are called from `loop()`. The thing is I want these functions to run at different times. Basically I want the `get_data` function to run once every 4 minutes and the `post_data` function to run once every hour. How can I achieve that?

As far as I know, you can't run multiple programs together on an Arduino Mega.

P.S: I'm new to Arduino programming.

# Answer
I imagine that you tried to figure out how to do it whit the `delay()` function (if it's not your case, it is for most Arduino beginners). Well... you can't use `delay()` in this case (and in most other cases) because it completely blocks the program for a given time (1) (except for interrupts, but i won't treat interrupts here). In general it is better not to use delays, except for very simple programs or in initialisation routines (i.e. in stuff you usually put in `setup()`).

---

Since your delays are quite long I imagine that you don't need much precision (i.e. you don't need to be more precise than a millisecond). So you could do like that:

```
void setup() {}

// Times at which we last called the functions
// (These are global variables, which are in general best avoided)
unsigned long lastGetData = 0;
unsigned long lastPostData = 0;

void loop() {

    //                           min.  sec.  milliseconds
    if(millis() - lastGetData >= 4   * 60  * 1000) {

        lastGetData = millis();
        get_Data();
    }

    //                            min.  sec.  milliseconds
    if(millis() - lastPostData >= 60  * 60  * 1000) {

        lastPostData = millis();
        post_Data();
    }
}

void get_Data() {
    // ...
}

void post_Data() {
    // ...
}

```

**Notes:**

* millis() returns the time since the startup of the Arduino in millisecond. To get more precision you could also use micros() which returns the same but in microseconds (then you would need to multiply the number in the if condition by 1000).
* you can add as much functions as you want whit different execution delays. But you must keep every function as short as possible, i.e. you must not use `delay()`s, because while executing a function if the time to execute another function comes that function will only be called after the end of the current one.
* I used the `=>` sign, and not `==`, so that even if the loop doesn't evaluates one if condition in the very milliseconds in which it becomes true it can positively evaluate it some milliseconds later (e.g. after the end of another running function).
> 1 votes

# Answer
I think you can use timer for it. In microcontroller with c you can use interrupts. You will need one timer and two compare interrupts. In the interrupts you can set different flags.

For example in first interrupt:

```
....
getSomething = true;
....

```

For example in second interrupt:

```
....
postSomething = true;
....

```

For example in your loop:

```
....
if(postSomething){
//your code to post something
postSomething = false;
}

if(getSomething){
//your code to get something
getSomething = false;
}

```

These functions are only called when the timer interrupt is called (the time reached). In the Handler you set the flag (do not execute big code). In loop you can check if a flag is set and execute than the code. I think in Arduino you can do the same.
> 0 votes

# Answer
If you don't need absolute precision, I've written a timer class that doesn't use an interrupt: TimerAction. Usage to simply subclass the base object, define an `action()` method in the subclass, construct your subclass defining the time interval to run, and place a call to the object's `loop()` method in your main `loop()` function in every sketch.

In your case, you'd create a subclass for each of your `get_data` and `post_data` actions. This would require two objects to be constructed, and both of them having their `loop()` method called in the main `loop()` function.
> 0 votes

# Answer
If it works in your situation:

```
void loop() {
  static int n;

  delay(4 * 60000);
  get_data();

  if (n-- == 0) {
    post_data();
    n = 14;
  }
}

```

You may need to adjust the 14 and post-decrement to fit your needs.
> 0 votes

---
Tags: arduino-mega, arduino-ide
---


# Question
Title: Accessing digital pins from the Atmega 16u2 on the Uno
I'm running a custom firmware on the ATmega16U2 (Switch-Fightstick). Is it possible to access the digital pins of the UNO from the ATmega16U2?

# Answer
No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.
> 3 votes

# Answer
There is a 4-pin header JP2 on the board that brings out the following pins from the '16U2

```
PB4, PB5, PB6, PB7

```

and the ICSP connector

```
PB1, PB2, PB3

```
> 1 votes

---
Tags: arduino-uno, pins, atmega16u2
---


# Question
Title: Replacing several pinMode() and digitalWrite() pins with an array
I'd like to 'clean up' some code that involves several `pinMode()` and `digitalWrite()` lines by using a single line of an array. I'm very new to both arrays so I'm a bit confused. The following examples are sections from code that controls a 4 digit, 7 segment LED.

```
// Define display pins
// Digit pins (common cathode)
int digit1 = 13; //Display pin 1
int digit2 = 12; //Display pin 2
int digit3 = 11; //Display pin 6
int digit4 = 10; //Display pin 8
// Segment pins
int segA = 2; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = 6; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
  pinMode(segA, OUTPUT);
  pinMode(segB, OUTPUT);
  pinMode(segC, OUTPUT);
  pinMode(segD, OUTPUT);
  pinMode(segE, OUTPUT);
  pinMode(segF, OUTPUT);
  pinMode(segG, OUTPUT);

  pinMode(digit1, OUTPUT);
  pinMode(digit2, OUTPUT);
  pinMode(digit3, OUTPUT);
  pinMode(digit4, OUTPUT);
}

#define SEGMENT_ON  LOW
#define SEGMENT_OFF HIGH

  switch (numberToDisplay){

  case 0:
    digitalWrite(segA, SEGMENT_ON);
    digitalWrite(segB, SEGMENT_ON);
    digitalWrite(segC, SEGMENT_ON);
    digitalWrite(segD, SEGMENT_ON);
    digitalWrite(segE, SEGMENT_ON);
    digitalWrite(segF, SEGMENT_ON);
    digitalWrite(segG, SEGMENT_OFF);
    break;

```

Defining pins:

I'm pretty sure the code below is the correct way to store the pins as an array (but please correct me if I'm wrong).

```
digitPins[] = {13 12 11 10};
segPins[] = {2 3 4 5 6 7 8};

```

**`pinMode():`**

I understand I could use a for loop to set the pin modes but is there an even simpler way? Would something like this work?

```
pinMode(digitPins[], OUTPUT);
pinMode(segPins[], OUTPUT);

```

**`digitalWrite():`**

I could access the appropriate pin from the array to use in `digitalWrite()` like the code below but that would result in the same number of lines of code (and be even more confusing). Is there another option?

```
digitalWrite(segPins[1], HIGH);

```

# Answer
> the correct way to store the pins as an array

Your array initializers are almost right; you just need to separate the values with commas:

```
digitPins[] = {13, 12, 11, 10};
segPins[] = {2, 3, 4, 5, 6, 7, 8};

```

You will need to call pinMode() in a loop; it doesn't accept arrays as arguments.

> How about for digitalWrite() where its a mix of HIGH and LOW?

There are (at least) two ways: Make arrays of HIGH and LOW values, matching the digitPins\[\] and segPins\[\] arrays one-for-one, respectively. Or for easier maintenance, declare a data structure (`struct`) of a pin # and a value; make an array of those. It's a bit more complex but also more useful. So, for example:

```
typedef struct {
    uint8_t pinNum;
    bool pinVal;
} pinInit_t;

pinInit_t digitPins[] {
    {13, HIGH},
    {12, LOW},
    {11, LOW},
    {10, HIGH}
};

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

```

`struct` is short for "data structure"; it lets you combine data of different types into a single named and addressable unit. `typedef` declares a new data type, and says "Don't allocate any memory just now; this (pinInit) is just a description. I'll use it later on." It makes pinInit a named data type, usable wherever you can use a native data type AND a multi-valued data type (such as an array) is permissible.

Thus, we can make an array of `pinInit`s (pin-# / boolean-value pairs) just by using the name of the new type.

Then your initializing code might look like:

```
uint8_t i;
for( i = 0; i < sizeof(digitPins)/sizeof(pinInit_t); ++i ){
   pinMode(digitPins[i].pinNum, OUTPUT);
   digitalWrite(digitPins[i].pinNum, digitPins[i].pinVal);
}

```

The expression `sizeof(digitPins)/sizeof(pinInit)` evaluates to the number of initializers (# of bytes in the array / # of bytes in one array member).

The expression `digitPins[i].pinNum` means: "in the pinInit array digitPins, get the i-th element..." (remember, this is a pair of values), "... and take value of the member "pinNum". A little more complex, the first time we think about it, but look at how easily the array reads. And a hint about reading that expression: I read it backwards: "the pinNum member of the i-th element of the digitPins array."

Tomorrow, or next month, when we need another pin, no need to update 2 arrays (remembering of course, to keep them in sequence with each other!); just add another 2-valued element to the one digitPins\[\] array.
> 7 votes

# Answer
***\[ADDITIONNAL CODE and EXPLANATION OF THE CODE\]***

This is the function that is used in the link posted in the comments:

```
void number(int num)                        //num is the number to display
{
  for(int i=0; i<7; i++)                    //going through the 7-segments (7 leds)
  {
    digitalWrite(segment[i], nums[num][i]); //tell the arduino to turn on or off which led
  }
}

```

It is great because you can use it by calling:

```
number(/*the number you want to display*/);

```

Using a for loop will avoid copying and pasting a buch of things. It also permits you do save a lot of memory.

Then, to display a small 0-9 timer, you can do this:

```
for(int i=0; i<10; i++)
{
  number(i);            //display the number
  delay(1000);          //wait 1sec
}

```

---

***\[ORIGINAL ANWSER\]***

Use an array and a for loop.

```
int segments = {2,3,4,5,6,7,8}; //declaring the pins

void setup() {
  for(int i=0;i<8;i++)
  {
    pinMode(segments[i], OUTPUT); //declaring them as outputs
  }
}

```

It's very useful. Do the same for the digits too.

This method works in many cases:

* many sensors, switches
* many outputs such as leds, relays, transistors
> 3 votes

# Answer
# Custom method usage

Used reference: https://stackoverflow.com/a/33235154/5500092

You can use a custom method like this:

```
template<size_t size>
void pinMode(const uint8_t (&pin)[size], uint8_t mode) {
    for (size_t i = 0; i < size; ++i) {
        pinMode(pin[i], mode);
    }
}

template<size_t size>
void digitalWrite(const uint8_t (&pin)[size], uint8_t val) {
    for (size_t i = 0; i < size; ++i) {
        digitalWrite(pin[i], val);
    }
}

```

Then you define an array with the pins:

```
uint8_t displayPins[4] = {13, 12, 11, 10};
uint8_t segmentPins[7] = {2, 3, 4, 5, 6, 7, 8};

```

And finally in your setup use:

```
void setup() {
    pinMode(displayPins, OUTPUT);
    pinMode(segmentPins, OUTPUT);
}

void loop() {
    // Your logic with digitalWrite.
}

```

---

# Your logic

PS: For your logic, you can even use:

```
template<size_t size>
void digitalWrite(const uint8_t (&pin)[size], const uint8_t (&val)[size]) {
    for (size_t i = 0; i < size; ++i) {
        digitalWrite(pin[i], val[i]);
    }
}

```

And define for each segment number a custom value array.

```
uint8_t zero[7] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW};
...

```

Or even:

```
uint8_t segment[][7] = {{HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW }, // 0
                        {____, ____, ____, ____, ____, ____, ____}, // 1
                        {____, ____, ____, ____, ____, ____, ____}, // 2
                        ...
                        {____, ____, ____, ____, ____, ____, ____}}; // F

```

And use:

```
digitalWrite(segmentPins, segment[5]); // print 5

```
> 0 votes

---
Tags: c++, array
---


# Question
Title: Need to set a FAILSAFE in an if else loop
This works but I would like to have a timed failsafe...

If the `FLOAT_PIN` goes `LOW` for more than 3 seconds, it will turn `SOLENOID_PIN` to `LOW`.

I can't figure out how to incorporate it into my loop. I tried `delay()` and started playing with `millis()` but all I keep finding is LED blinking samples...

I'm not very good with C++ - still learning.

```
const int FLOAT_PIN = 8; // Pin connected to FLOAT switch
const int SOLENOID_PIN = A0; // SOLENOID pin - active-high

void setup() {
  Serial.begin(9600);
  // Since the other end of the FLOAT switch is connected to ground, we need
  // to pull-up the FLOAT switch pin internally.
  pinMode(FLOAT_PIN, INPUT_PULLUP);
  pinMode(SOLENOID_PIN, OUTPUT);
}

void loop() {
  int floatswitch = digitalRead(FLOAT_PIN); // Read the state of the float switch

  if (floatswitch == HIGH) {
    // If the pin reads high, water is OFF.
    Serial.println("Switch closed");
    digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
  } else {
    digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
  }
}

```

# Answer
This is one of those cases when thinking in terms of a finite state machine makes the programming quite straightforward. Here I would use three states:

* In the `OFF` state, the switch is `LOW` and the solenoid is off
* in the `ON` state, the switch is `HIGH` and the solenoid is on
* in the `DELAYING` state, the switch is `LOW`, but the program is keeping the switch `HIGH` for three seconds.

The possible transitions are:

* `OFF``ON` when the switch goes `HIGH`
* `ON``DELAYING` when the switch goes `LOW`
* `DELAYING``OFF` after three second in this state
* `DELAYING``ON` when the switch goes `HIGH`.

The last transition is meant to ensure that `LOW` states of the switch that last less than three seconds do not turn the solenoid off.

And here is a tentative implementation. Keep your constants and your `setup()`, and replace your `loop()` with this:

```
const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

void loop() {
    static enum {OFF, ON, DELAYING} state;
    static uint32_t start_delay;
    int floatswitch = digitalRead(FLOAT_PIN);

    switch (state) {
        case OFF:
            if (floatswitch == HIGH) {
                Serial.println("Switch closed");
                digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                state = ON;
            }
            break;
        case ON:
            if (floatswitch == LOW) {
                start_delay = millis();
                state = DELAYING;
            }
            break;
        case DELAYING:
            if (floatswitch == HIGH) {
                state = ON;
            }
            else if (millis() - start_delay >= DELAY_TIME) {
                digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                state = OFF;
            }
            break;
    }
}

```
> 1 votes

---
Tags: arduino-uno, programming, sketch
---


# Question
Title: 4-digit 7-segment display resets when common pin set to HIGH
I'm trying to make a simple stopwatch application with my Arduino Mega 2560 and a 4-digit 7-segment display, but the leftmost three digits only light up for a split second before they go out every time the counter increments up. The rightmost digit is counting normally.

After going back to basics to diagnose the problem, I've discovered that every time one of the common pins is set back to high so I can pick another digit to manipulate, the digit goes blank.

Code for my basic program, which should display "0123" on my display.

```
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);
  delay(5);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);
  delay(5);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

}

void loop() {
}

```

But all the display shows is a 3 on the rightmost digit. I followed the video in this guide and hooked my Mega up the same way. Is this still the right way to code a 4 digit display to make all the digits display different numbers, or is this normal behavior?

# Answer
These 4-digit LED displays use *multiplexing* which means that (to keep the pin count down) you only display each digit for a brief time. Because of the eye's persistence of vision, if you repeatedly display the 4 digits they all appear to be lit up.

I have a video that illustrates this effect with a LED sign. There are a lot more than 4 digits, but the video gradually shows what happens if the delay between each digit is reduced. Watch it through to the end or you won't get the effect. It is about 45 seconds long.

In your case, as jsotola suggested in their answer, if you move the code which displays the digits out of `setup` and into `loop` then the code is done repeatedly, which means that the digits are now displayed repeatedly, and you should see all of them.

Since, in your original code, you had the display code in `setup` then it was done once, and the final digit was the only one you saw.
> 0 votes

# Answer
This should work (sort of). It will be flickery, but it should give you a starting place to work from.

```
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {

  // put your setup code here, to run once:
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);
}

```
> 1 votes

---
Tags: arduino-mega, 7-segment
---


# Question
Title: Using a 4*4 keypad to enter an integer value
I have a 4\*4 keypad and I want to use it to enter a number. I will then use this number as a delay to a LED or a motor to run for the specified time. This is my sample code:

```
#include<Keypad.h>
#include<LiquidCrystal.h>
const byte numRows = 4; //number of rows on keypad
const byte numCols = 4; //number of columns on keypad

char keymap[numRows][numCols]=
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'X', '0', 'Y', 'D'}
};

char value[4]="";
int index = 0;

byte rowPins[numRows] = {22,23,24,25}; //Rows 0 to 3
byte colPins[numCols]= {26,27,28,29}; //Columns 0 to 3

Keypad key= Keypad(makeKeymap(keymap), rowPins, colPins, numRows,numCols);

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
lcd.begin(20,4);

lcd.print("       WELCOME      ");
delay(100);
}

void loop() {
char keypress = key.getKey();
while (keypress != NO_KEY){
  if (keypress == 'X'){
      lcd.clear();
      for(int j=0;j<=4;j++){
        value[j]=0;
      }
      index=0;
      }
   else if (keypress == 'Y'){
      int amt = atoi(value);
      digitalWrite(13, HIGH);
      delay(amt);
      }
   else
      value[index]=keypress;
      index++;
    }
}

```

How do I read the value returned by the keypad as an integer? (When I press 3 I want to read 3 not "3").

# Answer
You can easily read by this line of code

```
value = anyDigitFromKeypad - 48

```

e.g value = "3"-48 = 3
> 2 votes

# Answer
Your problem is that you have your keypress matching inside a while loop. That means it will, once matched once, continue matching over and over again as infinitum. You need to replace your while with an if so it only runs once for each keypress.
> 1 votes

---
Tags: programming, c++
---


# Question
Title: Low-power detect rise and fall of input signal
For a very low-power-project (where I want to keep the micro-controller asleep or powerless as much as possible), I need to detect the rising and the falling of an input-signal (which could power-on the controller and send a signal).

I tried sleeping and waking up the controller via an interrupt, but it would be even better to switch of the controller completely and just power up when there is a change in input signal (only a few times a day, with a signal length of several minutes).

Making the controller powerless (and processing all there is to be done in the setup before switching off again) is a better solution than the deep sleep solution, because of the low frequency of occurence of the input signal changes.

The output does not have to be exactly 30 seconds, it can be any other value. It could use a power latch.

I looked at monostable circuits but they only detect (generate a pulse) on rising.

Does anyone have a solution (which only costs a few uAmps) for this?

Thanks.

*Addendum:*

*Voltage is 3.3V, current is "as low as possible" because this circuit should work as long as possible on a few cells. The input signal is generated by a mercury switch mounted on a bridge (which can be opened and closed)...*

*Instead of waking up from deep sleep (and being able to calculate the number of hours the circuit can last on an small battery) it is far better to power off "completely" and being able to calculate the number of activations from the bridge-movement (as long as the electronics I am looking for consume less than the deep sleep). Power consumption by the micro-controller+circuits is in deep sleep \>10mA (too much for battery).*

# Answer
You can generate a pulse on any edge of a signal using some logic gates. For instance combining a rising edge detector with a falling edge detector and adding a time delay would probably achieve what you want:

simulate this circuit – Schematic created using CircuitLab

Simulate it here.

The length of time the pulse is on for is (roughly) defined by the time constant of R1 and C1. That's T=RC, so in this instance 100 x 0.0000001 = 10uS.

for a time of (say) 30 seconds, you will want to massively increase those values. For example, 470uF and 80K would give you around 32 seconds.

Power consumption? Well, that's all dependent on the logic gates and how you build the circuit. 74HC chips are pretty efficient now (far better than the old 74LS ones), but you will want to reduce it down to as few chips and gates as possible. That means converting the circuit to just one gate type (for example NAND) and reducing redundancy in the circuit to minimise power consumption.
> 0 votes

---
Tags: esp8266, power, sleep, esp32
---


# Question
Title: LED fade class strobes for unknown reason
**Okay, so here is what I'm trying to accomplish:**

I have four LEDs, under my fish tank, that I want to fade in and out. I want each LED to fade at a different rate, start at a different "brightness" with PWM, and get a "new" fade-rate every once in a while. Ultimately, it'll make the bottom of the fish tank "pulse" in a "natural" way.

The code I'm using to accomplish this can be found in my GIT repo. There is also a GIF of it "working," there.

---

**Now, here is my problem:**

Every once in a while, one of the LEDs (not a specific one) will stop fading and start blinking like a strobe light. I'm not sure what's causing this blinking, since it seems to happen randomly.

The other three LEDs seem to continue to fade in/out while the "bad" LED is spaz-ing out, and it doesn't seem to be isolated to a specific LED. It also doesn't seem to affect only one LED at a time, although it's usually only one LED "blinking" and any given time... but I have seen two going at the same time.

It also doesn't seem to be specific to the "high" or "low" PWM levels, either... it can happen at "bright" levels, "dim" levels, or even in the middle of the fading transition.

---

**Here's what I've tried:**

I've tried different Arduino boards, and I've taken the LED count down to a single LED. I've changed variable types from bytes to ints, and back and forth with that tactic. I've been combing through this sketch all day, and I don't see anything that stands out to me as causing the problem.

So, now I'm turning to you all, hoping that someone will be able to see where I've screwed up my code.

Thank you, in advance!

---

**EDIT:** Since I've been asked for direct posting of my code, instead of just a link to the source code:

Here is the main .ino file:

```
#include "led_controller.h"

// Set pin numbers for each LED
byte led1 = 3,
           led2 = 6,
           led3 = 9,
           led4 = 11;

void setup(){
    pinMode( led1, OUTPUT );
    pinMode( led2, OUTPUT );
    pinMode( led3, OUTPUT );
    pinMode( led4, OUTPUT );
}

// Initialize our four classes for our four LEDs
LED a( led1 ),
    b( led2 ),
    c( led3 ),
    d( led4 );

void loop(){
    a.ledChange();
    b.ledChange();
    c.ledChange();
    d.ledChange();

    delay( 60 );
}

```

And the header file with the class:

```
// Create our custom LED class
class LED{
    private:
        // Set higest and lowest brightnesses for LEDs
        byte highest = 250,
             lowest = 5;
        byte pin, brightness, isNeg; // Random necessary variables
        int change; // Set the inc/decrement rate for the LED
        int checkNeg(); // See if our change rate is negative, or not
        void changeChange(); // Get a new change rate
    public:
        LED( byte led ); // Define our constructor
        void ledChange ();
};

// Define our constructor
LED::LED( byte led ){
    pin = led;
    changeChange();

    // Set the initial LED brightness by random
    brightness = random( lowest, highest );

    // Randomly determine if the LED will start brightening or darkening
    if( random( 1, 2 ) == 1 )
        change *= -1;
}

// Get a new change rate
void LED::changeChange(){
    change = random( 1, 4 );

    if( isNeg )
        change *= -1;
}

int LED::checkNeg(){
    if( change < 0 )
        return 1; // If `change` is negative, return true
    return 0;
}

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

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

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

    brightness += change; // Adjust the LEDs brightness

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

```

# Answer
> 0 votes
I added some `Serial.print()` statements to your code to point out the bug:

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

```
void LED::ledChange() {

  /**/Serial.print(brightness);

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

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

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

  }

  brightness += change; // Adjust the LEDs brightness

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

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

```

I marked the additional lines with `/**/`.

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

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

```

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

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

---

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

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

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

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

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

    brightness += change; // Adjust the LEDs brightness

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

```

---
Tags: c++, led, pwm, class
---


title: DAC using Arduino Leonardo

text:
# Question
Title: DAC using Arduino Leonardo
I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.

First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.

Am I going towards the correct direction? If not, please any suggestion would be helpful.

# Answer
Yes you are going in the right direction.

**Comparators**
You haven't as yet detailed how you plan to connect the 2 comparators to the Arduino, but I imagine it would be something similar to this:

simulate this circuit – Schematic created using CircuitLab

In the circuit above, X and Y are either high or low based on the analog voltages of A, B, C & D. I have created a truth table below with some arbitrary voltages to output. The `value` column corresponds to the value needed for the `analogWrite()` function.

Note: If you need your analog output to be able to source some current you can add an Op-Amp in a unity gain configuration at the output of the RC filter.

---

**Examples To Read**
To output the analog value, the 4 best suited inbuilt examples/tutorials to look at are:

Dimmer: Send serial values to change the brightness of an LED.
Fading: Use an analog output (PWM pin) to fade an LED.
Analog In Out Serial: Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
Read ASCII String: Parse a comma-separated string of integers to fade an LED.

What all of these examples have in common is the `analogWrite()` function:

```
// writes the analog value (range from 0 to 255):
analogWrite(pin, value);

```

*Dimmer* is a simple example where a serial value is read and then output on one of the PWM pins.
*Fading* is probably the most basic example of using the analogWrite() function (PWM output).
I included *Analog In Out Serial* as it uses the map() command.
I included *Read ASCII String* as it shows how to parse multiple values on the serial string.

---

**PWM Pins**
You can use pins 3, 5, 6, 9, 10, 11, and 13 on the Arduino Leonardo to output the PWM using the `analogWrite()` function.

---

**Control**
I recommend the following tutorials for your control. You could either use the if-else command or the switch-case command.
> 1 votes

---
Tags: arduino-ide, arduino-leonardo
---


title: for loop running infinitely

text:
# Question
Title: for loop running infinitely
```
void writereg() {
  digitalWrite(latchPin, LOW);
  for (int i = 7; i >= 0; i--) {
    digitalWrite(clockPin, LOW);
    Serial.print("wswitch&&&&&&");
    Serial.print(i);
    Serial.print("----------------------");
    digitalWrite(dataPin, switches[i].stat);
    Serial.println(switches[i].stat);
    digitalWrite(clockPin, HIGH);
  }
  digitalWrite(latchPin, HIGH);
  touched = false;
}

```

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.

This is my switch class:

```
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

```

# Answer
After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.

This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).

Heavy use of `String` variables is a likely explanation for the observed behavior. Also a lot of string literals are putting more pressure on memory in the OP program.

Here are my suggestions:

1. Replace all `"..."` string literals with flash-stored strings with `F("...")`. That will reduce the initial SRAM size used.
2. Replace all `String` variables with pure C-string (`char*` and char arrays) and use standard C string functions such as `strcpy`, `strcat`, `strlen`, `strcmp`, `strchr`... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
3. Use `const` whenever possible (instead of variables that waste memory)
4. Use the smallest type needed for each variable, e.g. avoid `int` (2 bytes) when you need to store a boolean value, prefer `bool` type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.
> 8 votes

# Answer
Like jfpoilpret said, it looks like `i` is being treated as an `unsigned char` or `uint8_t` causing it to never go below zero. Instead it wraps around to 255, the max value of an 8-bit unsigned integer, as you can see in line 9 of your output. The condition to remain in the loop is `i >= 0` which means the loop will never exit. A solution is to add a case for if `i` is above the starting value:

`for (int i = 7; i >= 0 && i <= 7; i--) {`

I would recommend finding out why `int` is being treated as `uint8_t` for any future projects
> 0 votes

# Answer
I have noticed that you have incorrectly declared the switches array.

Your code:

```
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

```

It should be:

```
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

struct Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

```

Alternatively, you could make a typedef struct:

```
typedef struct
{
  int num;
  bool stat;
  bool touched;
}Swtch;

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

```

References:
https://stackoverflow.com/a/32185804/6075112
https://overiq.com/c-programming/101/array-of-structures-in-c/#initializing-array-of-structures https://stackoverflow.com/a/3275389/6075112
> -1 votes

---
Tags: arduino-uno, serial, programming, array, shift-register
---