# Question
Title: Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins?
I'm using a CD4094 shift register to power my LEDs along with a ULN2003A darlington transistor array. I want to hook up the LEDs to an external power supply of 12V (common anode).

The cathodes of little groups of LEDs will be connected to the ULN2003A which is connected to the shift register which will get its data from the arduino (the digital pins which i assume work at 5V).

My question is, if I connect the Vdd pin of the shift register to the 12V external power supply, will it still function as intended through the Arduino?

# Answer
> 2 votes
No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.

Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.

---
Tags: arduino-uno, led, shift-register
---


title: Change range of IR programatically

text:
# Question
Title: Change range of IR programatically
I am building a IR-based laser tag system. The basics are working fine. One feature, that I want to have, is different weapon modes with different ranges.

How can I change the range of an IR transmitter with as little hardware as possible, or at best, completely in software?

# Answer
Consider using a Sharp Distance Sensor in addition to your shoot / confirm-hit inferred LED & receiver.

This Sharp distance sensor is specified to detect objects that reflect IR light from 100 cm-500 cm.

> How can I change the range of an IR transmitter with as little hardware as possible, or at best, completely in software?

I believe the sensors produce an analog output that can feed into an Arduino's ADC. So software (by itself) can be used to adjust the threshold distance.

Similar devices I have used have a narrow sensing field. They only reported the distance to objects directly in front of them. Also, I found they were effected by defective (burning out?) florescent light sources. We assumed failing florescent light sources produced IR radiation similar in frequency as used by the sensor's IR emitter. Also, the analog output is slightly stair stepped in the unit we tested. I say this in case you were expecting to use increase relative accuracy of several readings if not precision of any given reading.
> 1 votes

# Answer
Instead of modifying the TX power, why not make the receiver read the light level. You just need to transmit some data, like the weapon ID.

If it works you could send more information, including how stable the weapon that hit the target was, during the shoot, using an accelerometer.
> 1 votes

# Answer
Let us assume you are using an ordinary inferred LED and a type of inferred detector used in remote control entertainment equipment.

Inferred LED modulation is simple and is well documented on the web.

The inferred receiver is a complex device. It contains, among other features, an Automated Gain Control (AGC) circuit and a Phase Locked Loop (PLL) circuit. The AGC adjusts the gain and makes it impossible to gauge the power of one IR source relative to another. The PLL "locks onto" the signal.

Consider using and adjusting the power of a secondary inferred LED transmitter transmitting at the same time as the primary LED transmitter is being received. The secondary inferred LED transmitter is local to the inferred LED receiver and transmits a unique code. The primary inferred LED transmitter is part of the opponent's equipment and transmits a unique code. Slowly reduce the power of the secondary inferred LED source until the code switches from the secondary source to the primary source. The power used by the secondary inferred LED when the switch occurs should be proportional to the distance to the primary inferred LED.

In the above scenario we have used the AGC to "hide" the primary source until we reduced the power of the secondary source to just below that of the primary source. And we used the PLL to "lock onto" the strongest signal.
> 1 votes

---
Tags: ir
---


# Question
Title: I am running 1.6.5, but the folder says 1.6.3?
I just downloaded the latest version of the Arduino software (1.6.5). However, when I look into the Application Support folder under Library (I have a mac), I find that I have a folder named 1.6.3:

Library ▸ Arduino15 ▸ packages ▸ arduino ▸ hardware ▸ sam ▸ 1.6.3

Does this mean there is a hidden 1.6.5 folder that I am not seeing?

BTW, this issue surfaced, because I am trying to fiddle around with the ADC clock speed, but it seems that nothing is happening:

```
void setup() {
  #define ADC_FREQ_MAX = 1;
  Serial.begin(9600);
  Serial.println(ADC_FREQ_MAX);
}

void loop() {
}

```

gives me:

```
opamp.ino: In function 'void setup()':
opamp:2: error: expected primary-expression before '=' token
opamp.ino:4:18: note: in expansion of macro 'ADC_FREQ_MAX'
opamp:4: error: expected primary-expression before ')' token
opamp:4: error: expected ';' before ')' token
expected primary-expression before '=' token

```

# Answer
> 1 votes
1.6.5 is the version of the Arduino IDE.

1.6.3 is the version of the Arduino SAM Boards package that you have installed.

> Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via **Tools \> Board \> Boards Manager** are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

1. **Tools \> Examples \> 01.Basics \> BareMinimum**
2. **Sketch \> Show Sketch Folder** \- this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

> BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.

# Answer
> 0 votes
The error you see is because of the equal sign in your #define. That equal should not be there. So the line that uses it ends up being.

Serial.println(= 1);

Which is obviously wrong.

---
Tags: arduino-ide, arduino-due
---


# Question
Title: ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt?
I am using a vibration switch with a pin change interrupt on an ATTiny85 to wake the processor and run some code when the vibration switch grounds an input pin. The circuit is battery-powered, so sleep mode is important. I would now like to add another input switch (momentary pushbutton) between an internal pullup on the ATtiny and ground to use as a soft latching switch to accomplish on/mode/off (power-on/case-selection/power-off). I'd like the vibration-wake-sleep code to be one of the cases selectable by the pushbutton. The ATtiny85 has one hardware interrupt (pin2 aka INT0), and the rest are pin change interrupts available on the other I/O pins. After reading around, my understanding is that the pin change interrupts *cannot* be separated to run pin-specific code, as they all trigger the same pin change interrupt effect. Is that correct? To put it another way, do I need to put my pushbutton on the hardware interrupt pin, or can I put it on any old I/O pin and still be able to use the vibration switch on another I/O pin only when I select that mode, without it triggering the same effect as the pushbutton every time there's a vibration? Or is there a better way? I'm trying to minimize the number of components, as this is a space-constrained project. Thanks!

# Answer
> 1 votes
If you have one dedicated interrupt signal, and enable the shared pin change interupt *for only one* pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.

Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt. In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.

Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register. The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it. However, contact bounce is typically a more serious problem when *releasing* a contact than closing it.

Some things you can do:

* In the ISR, don't actually do anything, but set an "interrupt happened" flag. Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that. You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.
* You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt *disabled* until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out. Then you can re-enable the interrupt and go back to sleep.

Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.

# Answer
> 0 votes
> Or is there a better way?

Read the data sheet to see if it has individual flags for those pins.

Short of that, read and keep track of the pin states in the use to see which pins may have changed.

---
Tags: interrupt, attiny, battery, switch, attiny85
---


# Question
Title: Arduino UNO two SoftwareSerial ports communication
I am working on a project involving bluetooth and wifi communications. Both of them are wired up to the Arduino and communicate to it using two software serial port. The scenario is the one in the picture attached.

What I am doing is:

* retrieve the sensor value
* send it from the BT slave module to the master one (wired up to Arduino)
* take it and send it, using AT commands, through the WIFI channel (the WIFI module is a ESP8266-01) to a web server.

The problem is that if I start listening to the BT serial port (BTSerial.listen()) I am not able to properly send the sensor values through the WIFI connection. But if I comment out the lines related to the BT sotware serial, and try to send fixed value to the web server, the sending terminates succesfully.

In my opinion there are some problems with the BTSerial.listen() and WIFISerial.listen() calls, since they are not able to switch from one the the other correctly.

I saw the TwoSerialPort example provided into the Arduino IDE and I tried to apply it into my code but it still not works to me.

Does anyone have a idea which would be the problem? Does anyone already faced with this problem or a similar one?

Hoping to be as much clear as possible, thanks in advance to anyone would help me.

Filippo

**\[EDIT\] Added two code snippets**

```
// This method prepares the AT commands will be send to the ESP8266-01 module in order to upload the values on the web server
void send2server(String ip, int port, String file, int t, int h, int p) {

  String queryString = "temp=";
  queryString.concat(t);
  queryString.concat("&hum=");
  queryString.concat(h);
  queryString.concat("&press=");
  queryString.concat(p);
  Serial.println(queryString);

  // Prepare and exec the AT+CIPSTART command provideing the TCP connection init
  String CIPSTART_cmd = "AT+CIPSTART=\"TCP\",\"" + ip + "\"," + port + "";
  exec_cmd(CIPSTART_cmd, 1000);

  // Prepare the POST request
  String httpPOST_cmd = "POST /";
  httpPOST_cmd.concat(file);
  httpPOST_cmd.concat(" HTTP/1.1\r\n");
  httpPOST_cmd.concat("Host: ");
  httpPOST_cmd.concat(ip);
  httpPOST_cmd.concat("\r\n");
  //httpPOST_cmd.concat("Accept: */*\r\n");
  httpPOST_cmd.concat("Content-Length: ");
  httpPOST_cmd.concat(queryString.length());
  httpPOST_cmd.concat("\r\n\r\n");
  //httpPOST_cmd.concat("Content-Type: text/html\r\n\r\n");
  httpPOST_cmd.concat(queryString);

  // Calculate the POST request length
  unsigned int len = httpPOST_cmd.length();

  // Prepare and exec the AT+CIPSEND statement with the POST request length just calculated
  String CIPSEND_cmd = "AT+CIPSEND=";
  CIPSEND_cmd.concat(len);
  exec_cmd(CIPSEND_cmd, 1000);

  // Exec the HTTP POST request
  exec_cmd(httpPOST_cmd, 1000);

  // Close the connection
  exec_cmd("AT+CIPCLOSE", 1000);
}

// This method execute each AT command in the previuous method
void exec_cmd(String cmd, int delayTime) {
   byte i = 0;

   while(1) {
      Serial.println("invio comando");
      WIFISerial.println(cmd);
      while(WIFISerial.available()) {
         if(WIFISerial.find("OK")) {
            i = 8;
         }
      }
      delay(delayTime);

      if(i > 5)
         break;

      i++;
   }

   if(i == 8) {
      Serial.println("OK");
      //return true;
   } else {
      Serial.println("ERRORE");
      //return false;
   }
}

```

The problem is the code goes properly till the AT+CIPSEND command, then the POST request is sent but no good feedback arrives, ending with the "ERRORE" error message.

**\[EDIT 2\] Attached serial monitor output** This is the serial monitor output when I execute the skecth. It seems to work properly but it does not upload any value.

# Answer
> 0 votes
This answer provides full details on choosing "good" combinations of hardware and software serial ports. To summarize:

* Use the `HardwareSerial` port (i.e., `Serial`) for one of the devices. You can still use it for debug prints, as long as the device has some kind of command "format". For example, if commands start with "AT", just make sure that none of your debug prints start with "AT". It is the absolute best choice. You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
* Use `AltSoftSerial` for the other device. It is the most efficient software serial port, and it can be used at the same time as `Serial`. It only works on two specific pins.
* `NeoSWSerial` is the next best choice, at limited baud rates. It can be used with the above choices, but transmitting on `NeoSWSerial` prevents them from receiving.
* `SoftwareSerial` is the worst choice. Receiving **or** transmitting on `SoftwareSerial` prevents all of the above from receiving anything. It disables interrupts for long periods of time.

---

### UPDATE - Here is the most reliable configuration:

Your code will have something like this:

```
#include <AltSoftSerial.h>
AltSoftSerial BT; // 8 is RX, 9 is TX

#define WIFI Serial  // 0 is RX, 1 is TX (disconnect 0 to upload new sketch)

void setup()
{
  WIFI.begin( 115200 );
  BT.begin( 9600 );
}

void loop()
{
  if (BT.available) {
    char c = BT.read();
    // do something with the character
       ... save them until '\n' arrives?
         ... then parse some values?

    if (values all received) {
      Serial.print( F("Sending values") ); // this is the WIFI port, but
          //  the ESP8266 ignores this debug print because it doesn't
          //  start with "AT".

      WIFI.println( F("AT+ ...") ); // all the AT commands
          ...
      WIFI.print( btValue1 );    // and the BT values
          ...
    }
  }
}

```

---
Tags: arduino-uno, bluetooth, wifi, softwareserial
---


title: Maximum Delay time

text:
# Question
Title: Maximum Delay time
I am designing a driver for a Bipolar stepper motor using Arduino Mega 2560 and DRV8825 Stepper driver.

In my application, a stepper motor (Nema 24) will run for 5 minutes and stop for 2 minutes. I have doubts about is what is the maximum time an Arduino Mega can delay the process, or how much a maximum time `delay()` function will last, or work in programming?

# Answer
> 4 votes
*Note: there's an existing question here this should be closed as a duplicate of, but that is proving hard to find. So until someone does find it...*

The arduino `delay()` function creates a *blocking* delay of the provided number of milliseconds. The argument is an `unsigned long` which on a 16-bit Arduino is a 32-bit unsigned integer type, having a maximum value of 4,294,967,295. Since these are milliseconds, the maximum `delay()` would be 4,294,967.295 seconds, or about 49 days.

However, you can easily achieve longer delays by using counting variables to count up instances of shorter delays. At an extreme, by using up available memory for keeping track of such counting, you can readily achieve theoretical delays exceeding the age of the universe.

Note that the Arduino `delay()` function is *blocking*, which is to say that nothing else (except interrupts and on-chip hardware peripherals) runs during it. This is often undesirable. A more useful solution might be to make a loop taking say 20 milliseconds to run, as the result of a `delay()` and a few housekeeping operations, and then run this over and over again while counting. Or you could make a 1 second loop, or whatever you choose.

---
Tags: arduino-mega, stepper
---


# Question
Title: Compilation Error: "cannot declare 'client' to be of abstract type 'Client'"
I know, it isn't my original code, but I'm using this for a larger project that I am currently working on. I keep getting this error message: "cannot declare 'client' to be of abstract type 'Client'". here's the code:

```
// RoboSapienServer.cpp
// RobosapienServer - Web enable a RoboSapien
// Kevin N. Haw
// http://www.KevinHaw.com/RoboSapienServer.php

// This project combines the default webserver example in the IDE distribution and Karl Castleton's(http://home.mesastate.edu/~kcastlet) RoboSapienIR (http://playground.arduino.cc/Main/RoboSapienIR).
// Source code merged from those two sources.

// Include files
#include <Ethernet.h>
#include <string.h>
#include <WebServer.h>

//////////////////////////////////////////////////////////////////
// Begin Web Server specific variable deinitions
//////////////////////////////////////////////////////////////////

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// KNH, 02/09/2010 - Change IP address to use local subnet at home
//byte ip[] = { 10, 0, 0, 177 };
byte ip[] = { 192, 168, 1, 177 };

// Server for web requests
EthernetServer server(80);

// Define field name in the submitted form
#define SUBMIT_BUTTON_FIELDNAME "RSCmd"

// String for HTTP request variables
char pcHttpReqRsCmd[20] = {'\0'};

volatile int viRobsapienUrlCmd = -1;  // A robosapien command sent over the URL of a webpage HTTP request

//////////////////////////////////////////////////////////////////
// Begin Robosapien specific variable deinitions
//////////////////////////////////////////////////////////////////

// Some but not all RS commands are defined
#define RSTurnRight       0x80
#define RSRightArmUp      0x81
#define RSRightArmOut     0x82
#define RSTiltBodyRight   0x83
#define RSRightArmDown    0x84
#define RSRightArmIn      0x85
#define RSWalkForward     0x86
#define RSWalkBackward    0x87
#define RSTurnLeft        0x88
#define RSLeftArmUp       0x89
#define RSLeftArmOut      0x8A
#define RSTiltBodyLeft    0x8B
#define RSLeftArmDown     0x8C
#define RSLeftArmIn       0x8D
#define RSStop            0x8E
#define RSWakeUp          0xB1
#define RSBurp            0xC2
#define RSRightHandStrike 0xC0
#define RSNoOp            0xEF

// Subset of additional codes pulled from http://www.contrib.andrew.cmu.edu/~ebuehl/robosapien-lirc/ir_codes.htm
#define RSRightHandSweep  0xC1
#define RSRightHandStrike2 0xC3
#define RSHigh5           0xC4
#define RSFart            0xC7
#define RSLeftHandStrike  0xC8
#define RSLeftHandSweep  0xC9

#define RSWhistle         0xCA
#define RSRoar            0xCE

int IRIn = 2;            // We will use an interrupt
int IROut = 3;           // Where the echoed command will be sent from

boolean RSEcho = true;    // Should Arduino Echo RS commands
boolean RSUsed = true;    // Has the last command been used
volatile int RSBit = 9;   // Total bits of data
volatile int RSCommand;   // Single byte command from IR
int bitTime = 516;        // Bit time (Theoretically 833 but 516)
// works for transmission and is faster
int last;                 // Previous command from IR

//////////////////////////////////////////////////////////////////
// Begin Robosapien specific code
//////////////////////////////////////////////////////////////////

// Receive a bit at a time.
//  NOTE: Unused in the RoboServer aplication
void RSReadCommand() {
  delayMicroseconds(833 + 208); // about 1 1/4 bit times
  int bit = digitalRead(IRIn);
  if (RSBit == 9) { // Must be start of new command
    RSCommand = 0;
    RSBit = 0;
    RSUsed = true;
  }
  if (RSBit < 8) {
    RSCommand <<= 1;
    RSCommand |= bit;
  }
  RSBit++;
  if (RSBit == 9) RSUsed = false;
}

// send the whole 8 bits
void RSSendCommand(int command) {
  digitalWrite(IROut, LOW);
  delayMicroseconds(8 * bitTime);
  for (int i = 0; i < 8; i++) {
    digitalWrite(IROut, HIGH);
    delayMicroseconds(bitTime);
    if ((command & 128) != 0) delayMicroseconds(3 * bitTime);
    digitalWrite(IROut, LOW);
    delayMicroseconds(bitTime);
    command <<= 1;
  }
  digitalWrite(IROut, HIGH);
  delay(250); // Give a 1/4 sec before next
}

// Set up RoboSpapien functionality
void RSSetup()
{
  pinMode(IRIn, INPUT);
  pinMode(IROut, OUTPUT);
  pinMode(10, OUTPUT);
  digitalWrite(IROut, HIGH);

  attachInterrupt(0, RSReadCommand, RISING);

  last = RSNoOp;

  // Make robot burp to indicate setup is complete
  RSSendCommand(RSBurp);

}

// Loop for RoboSapien functionality
// Write only functionality - send the command from the web page to the robot, ignoring any input from the remote
void RSLoop()
{
  // Has a new command come in from the server?
  if (viRobsapienUrlCmd != -1)
  {
    // New command - send it to robot
    Serial.print("Sending command to RoboSapien: ");
    Serial.println(viRobsapienUrlCmd, HEX);
    RSSendCommand(viRobsapienUrlCmd);

    // Now clear command
    viRobsapienUrlCmd = -1;
  }
}

//////////////////////////////////////////////////////////////////
// Begin Webserver Specific Code
//////////////////////////////////////////////////////////////////

// Print ourt MIME and HTML header at top of webpage
void HtmlHeader(Client client)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("<HTML>\n<HEAD>");
  client.println("  <TITLE>Kevin's Arduino Webserver</TITLE>");//
  //  client.println("  <META HTTP-EQUIV=\"refresh\" CONTENT=\"5\">");
  client.println("</HEAD><BODY bgcolor=\"#9bbad6\">");
}

// Print the footer at the bottom of the webpage
void HtmlFooter(Client client)
{
  client.println("</BODY></HTML>");
}

// Print a submit button with the indicated label wrapped in a form for the indicated hex command
void SubmitButton(Client &client, char *pcLabel, int iCmd)
{
  client.print("<form method=post action=\"/?");
  client.print(iCmd, HEX);
  client.print("\"><input type=submit value=\"");
  client.print(pcLabel);
  client.print("\" name=\"" SUBMIT_BUTTON_FIELDNAME "\">");
  client.println("</form>");
}

// Parse an HTTP request header one character at a time, seeking string variables
void ParseHttpHeader(Client &client)
{
  char c;

  // Skip through until we hit a question mark (first one)
  while ((c = client.read()) != '?' && client.available())
  {
    // Debug - print data
    Serial.print(c);
  }

  // Are we here for a question mark or did we run out of data?
  if (client.available() > 2)
  {
    char pcUrlNum[3], *pc;

    // We have enough data for a hex number - read it
    for (int i = 0; i < 2; i++)
    {
      // Read and dump data to debug port
      Serial.print(c = pcUrlNum[i] = client.read());
    }
    // Null terminate string
    pcUrlNum[2] = '\0';

    // Get hex number
    viRobsapienUrlCmd = strtol(pcUrlNum, &pc, 0x10);
  }

  // Skip through and discard all remaining data
  while (client.available())
  {
    // Debug - print data
    Serial.print(c = client.read());
  }
}

// Set up webserver functionality
void WebServerSetup()
{
  Ethernet.begin(mac, ip);
  server.begin();
}

// Web server loop
void WebServerLoop()
{
  Client client = server.available();
  boolean bPendingHttpResponse = false; // True when we've received a whole HTTP request and need to output the webpage
  char c;  // For reading in HTTP request one character at a time

  if (client) {
    // Loop as long as there's a connection
    while (client.connected()) {
      // Do we have pending data (an HTTP request)?
      if (client.available()) {

        // Indicate we need to respond to the HTTP request as soon as we're done processing it
        bPendingHttpResponse = true;

        ParseHttpHeader(client);
      }
      else
      {
        // There's no data waiting to be read in on the client socket.  Do we have a pending HTTP request?
        if (bPendingHttpResponse)
        {
          // Yes, we have a pending request.  Clear the flag and then send the webpage to the client
          bPendingHttpResponse = false;

          // send a standard http response header and HTML header
          HtmlHeader(client);

          // Put out a text header
          client.println("<H1>Kevin's RoboSapien Webserver</H1>");

          client.println("<table border cellspacing=0 cellpadding=5><tr>");
          client.println("<td>");

          // Create buttons
          SubmitButton(client, "WakeUp", RSWakeUp);
          SubmitButton(client, "Roar", RSRoar);
          SubmitButton(client, "Whistle", RSWhistle);
          SubmitButton(client, "High5", RSHigh5);
          client.println("<br>");

          client.println("</td><td>");

          SubmitButton(client, "LeftArmUp", RSLeftArmUp);
          SubmitButton(client, "LeftArmIn", RSLeftArmIn);
          SubmitButton(client, "LeftArmOut", RSLeftArmOut);
          SubmitButton(client, "LeftArmDown", RSLeftArmDown);
          SubmitButton(client, "LeftArmSweep", RSLeftHandSweep);
          client.println("<br>");

          client.println("</td><td>");

          SubmitButton(client, "RightArmUp", RSRightArmUp);
          SubmitButton(client, "RightArmIn", RSRightArmIn);
          SubmitButton(client, "RightArmOut", RSRightArmOut);
          SubmitButton(client, "RightArmDown", RSRightArmDown);
          SubmitButton(client, "RightArmSweep", RSRightHandSweep);
          client.println("<br>");

          client.println("</td></tr></table>");

          client.print("<br><br><br>URL Hex no: ");
          client.print(viRobsapienUrlCmd, HEX);
          client.println("<br />");

          // send HTML footer
          HtmlFooter(client);

          // give the web browser time to receive the data
          delay(1);
          client.stop();
        }
      }
    }  // End while(connected)
  }
}

//////////////////////////////////////////////////////////////////
// Begin arduino entry points
//////////////////////////////////////////////////////////////////

void setup()
{
  // open the serial port at 9600 bps:
  Serial.begin(9600);

  // Print greeting
  Serial.println("Kevin's RobSapien Server");

  RSSetup();
  WebServerSetup();
}

void loop()
{
  RSLoop();
  WebServerLoop();
}

```

# Answer
You can't use Client directly like that. It's just an abstract class. You have to use one of the classes like EthernetClient or WiFiClient that implements it.

Client is like a shell of a class. It says that there will be classes that act as clients and will have this basic form. But it doesn't have any code, just the outline. The base classes that implement that abstract class like EthernetClient or WiFiClient actually have the code to actually BE a client.
> 2 votes

# Answer
I would guess the problem lies here:

```
void HtmlFooter(Client client) {
    client.println("</BODY></HTML>");
}

```

(Also the HtmlHeader function)

When you call that function you make a new Client object and copy the contents of your existing object into it. Since Client is pure virtual you can't do that. Instead you should be working with a reference as in the other functions:

```
void HtmlFooter(Client &client) {
    client.println("</BODY></HTML>");
}

```
> 0 votes

---
Tags: ethernet, compilation-errors
---


title: Arduino USB and 9V

text:
# Question
Title: Arduino USB and 9V
I'm working on a project for interfacing the Arduino with the Raspberry Pi. I need to be able to exchange serial data between the two using the USB port.

My question is, can I do that while having the Arduino powered, by using a 9 V battery connected to the DC pin and at the same time have serial data connection using the USB port?

# Answer
Yes, you can. Arduino can be connected to multiple power sources at the same time.

From this excelent page about Arduino power, I cite:

> Arduino is provided with a comparison circuit that controls a type P MOSFET; if a tension is found on Vin (powering from the JACK or from the Vin socket), the MOSFET is interdicted and the possible presence of voltage coming from the USB port is ignored; in the opposite case, the MOSFET will connect the USB port’s 5 V to the 5 V socket, hence below the regulator, thus powering Arduino.
>
> Therefore it is clear that if you apply the voltage to the USB port and an external source to the JACK socket at the same time, it will be this last one to power the circuit, while the USB connection will keep working for the data exchange with the computer and no longer as a power source. We remind that in both cases the 5 V socket cannot be used as input, but only as output.
> 3 votes

---
Tags: arduino-uno, power, usb, raspberrypi, serial-data
---


title: SPI MOSI receive error

text:
# Question
Title: SPI MOSI receive error
I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send `'2'`, slave is receiving `'2'`. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.

Master Code:

```
void setup() {
  Serial.begin(9600);
  Serial.println("Master");
  digitalWrite(SS,HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop() {
  digitalWrite(SS,LOW);  //  Slave select to low
  received1 = SPI.transfer(test);  // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
  Serial.println(received1);
  digitalWrite(SS,HIGH);
}

```

Slave code:

```
void setup() {
  Serial.begin(9600);
  Serial.println("Slave");
  pinMode(MISO,OUTPUT);
  SPCR |= _BV(SPE);
  process = false;
  SPI.attachInterrupt();
}
ISR(SPI_STC_vect){
  received = SPDR;  // the data received by slave is slored in **received** variable(the variable is char type)
  Serial.println(received);
  process = true;
}
void loop() {
  if(process){
    SPDR = jj;  // Updating SPDR to send data from slave. jj is char type
    process = false;
  }
}

```

# Answer
> 0 votes
I have found a solution for this problem in a blog.

Link: http://www.gammon.com.au/forum/?id=10892

I modified my master code and got my desired result.

Master code:

```
byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (2000);
  return a;
} // end of transferAndWait

void loop() {
  digitalWrite(SS,LOW);
  transferAndWait (10);
  received1 = transferAndWait (11);
  digitalWrite(SS,HIGH);
  Serial.println(received1);
}

```

The response will be "collected" next time through the loop. That's why we need to keep a dummy `transferAndWait()` function first and then the result of that transfer will be stored in `received1` variable.

---
Tags: arduino-uno, serial, arduino-ide, communication, spi
---


# Question
Title: How to control RC power switch with Arduino-/Adafruit-Board?
I want to control (switch on/off) a solenoid valve via an RC power switch and an Adafruit M0 Feather Bluefruit LE. The RC power switch is this one, and this is the Adafruit Board Pinout.

My assumption was that I have to wire up the servo wire connector of the power switch with the Adafruit board like I would do with an ESC and control it via PWM (my guide tells me that possible pulse widths are between 870 and 2,220 µs). I am connecting the white cable (I assume it's the impulse wire) of the power-switches' servo-connector with a PWM-capable GPIO pin and the black cable (I assume it's the minus wire) with the GND pin of the Adafruit Board, like I did with an ESC, which is working fine with the servo library of Arduino.

My problem is that the solenoid valve is showing no reaction. Am I thinking the right way or am I completely wrong?

Thank you and many thanks.

# Answer
I fixed the problem by myself. If you want to arm an RC power switch, do it like arming an ESC with your sketch. The servo connector wires have to be connected as follows:

* (white) PWM-capable GPIO
* (red) positive wire of your battery
* (black) negative wire of your battery

The simple solution was that the power switches got less/no power.
> 0 votes

---
Tags: servo, pwm, adafruit, remote-control, switch
---


# Question
Title: Library to set internal analog gain of the Arduino?
My original question was if there is a library that covers the internal **comparator** and **differential** and **gain** modes for the Arduino Uno, Mega 2560, Leonardo, Due, Zero, M0.
The answer is obvious: "No". To my surprise there is not even a start to make it and neither a collaboration to gather usefull code.

If you know pieces of code (Arduino compatible and documentation for which pins) for the analog comparator and gain, then please tell me about it, and I put them in this list.

# Answer
> 3 votes
I would recommend you to check Nick Gammon's example on using the analog comparator by means of configuring the relevant flag bits of registers in the ATmega328. Sample code from the link, by Nick:

```
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

```

# Answer
> 2 votes
You seem to be interested mainly in ATSAMD21. There is an application note from Atmel, AT11480: Analog Comparator Application Examples, which may be of interest for you.

From the *Getting started* section (3.1, page 8):

> The AC \[Analog Comparator\] example project has to be opened from New Example Project option in Atmel Studio. Using the option Atmel Studio → File → New → Example Project will open the New Example Project from ASF or Extensions window. The project named Analog Comparator Examples – SAM D21 Xplained Pro has to be opened.

There you'll find example code that might be useful for you, as it will show how to configure and manage the registers involved in using the analog comparator of the ATSAMD21. Namely, the example code is related to the following example applications:

1. Level crossing detector.
2. Window mode operation.
3. Preventing false spike detection.
4. Gray signal frequency measurement.
5. SleepWalking with analog comparator.

If you look into the first case (**level crossing detector**) for guidelines for where to start from, you can see that the application example goes through the following steps:

1. Enable alternate function H (AC/CMP\[0\]) for pin PA12 so that the comparator 0 output is directly routed to the pin.
2. Select GCLK Generator 0 as GCLK source for AC module. The GCLK Generator 0 is clocked from internal OSC8M oscillator whose output is set to 8MHz.
3. Select AIN\[0\] pin (PA04) as positive input and internal voltage scaler output as negative input for comparator 0. The voltage scaler register is set to a value of 9 corresponding to a voltage output of 0.5156V.
4. Set comparator 0 in continuous comparison mode with hysteresis and filter mode disabled.
5. Enable comparator 0 output to be routed to I/O pin and select interrupt mode as toggle so that comparator output toggles when positive input crosses the negative input (both during rising and falling).
6. Enable comparator 0 and then enable the AC module.

You could get from that example code some ideas about the registers to be configured and managed, and then try to use that knowledge for creating (or even reusing) some code within the Arduino IDE.

Hope it helps...

# Answer
> 0 votes
What you are trying to do can be easily done via simple programming of the channels bits in the ADV module - the datasheet is your best friend here.

So if you want to take this one, take a look at the datasheet and that's all there is to it.

Happy to provide a sample piece to get you going.

# Answer
> 0 votes
I tried to find further information that would help you about the ATSAMD21, but I only managed to find the source code for the definitions of the Analog Comparator Controller (ACC), the Power Management Controller (PMC), and some example code as well. The example code follows, to avoid this being a link-only answer:

```
 #include "asf.h"
 #include "stdio_serial.h"
 #include "conf_board.h"
 #include "conf_clock.h"

 #define VOLT_REF   (3300)

 #define MAX_DIGITAL (4095)

 #define DACC_CHANNEL_0 0

 #define DACC_ANALOG_CONTROL (DACC_ACR_IBCTLCH0(0x02) \
                           | DACC_ACR_IBCTLCH1(0x02) \
                           | DACC_ACR_IBCTLDACCORE(0x01))

 #define ADC_CLOCK 6400000

 #define ADC_STARTUP_TIME_SETTING 0x8u

 #define ADC_TRACK_SETTING 0x0u

 #define ADC_TRANSFER_SETTING 0x1u

 #define ACC_SELPLUS_AD5  0x5u
 #define ACC_SELMINUS_DAC0  0x2u
 #define ACC_EDGETYP_ANY  0x2u
 #define ACC_INVERT_NO 0x0u

 #define STRING_EOL    "\r"
 #define STRING_HEADER "-- ACC IRQ Example  --\r\n" \
         "-- "BOARD_NAME" --\r\n" \
         "-- Compiled: "__DATE__" "__TIME__" --"STRING_EOL

 void ACC_Handler(void)
 {
     uint32_t ul_status;

     ul_status = acc_get_interrupt_status(ACC);

     /* Compare Output Interrupt */
     if ((ul_status & ACC_ISR_CE) == ACC_ISR_CE) {

         if (acc_get_comparison_result(ACC)) {
             puts("-ISR- Voltage Comparison Result: AD5 > DAC0\r");
         } else {
             puts("-ISR- Voltage Comparison Result: AD5 < DAC0\r");
         }
     }
 }

 static void configure_console(void)
 {
     const usart_serial_options_t uart_serial_options = {
         .baudrate = CONF_UART_BAUDRATE,
         .paritytype = CONF_UART_PARITY
     };

     /* Configure console UART. */
     sysclk_enable_peripheral_clock(CONSOLE_UART_ID);
     stdio_serial_init(CONF_UART, &uart_serial_options);
 }

 static void dsplay_menu(void)
 {
     puts("-- Menu Choices for this example--\n\r"
             "  s: Set new DAC0 output voltage.\n\r"
             "  v: Get voltage on potentiometer.\n\r"
             "  m: Display this menu again.\r");
 }

 static int16_t get_input_voltage(void)
 {
     uint8_t i = 0, uc_key;
     int16_t us_value = 0;
     int8_t c_length = 0;
     int8_t ac_str_temp[5] = { 0 };

     while (1) {
         while (uart_read(CONSOLE_UART, &uc_key)) {
         }
         if (uc_key == '\n' || uc_key == '\r') {
             puts("\r");
             break;
         }

         if ('0' <= uc_key && '9' >= uc_key) {
             printf("%c", uc_key);
             ac_str_temp[i++] = uc_key;

             if (i >= 4)
                 break;
         }
     }

     ac_str_temp[i] = '\0';
     /* Input string length */
     c_length = i;
     us_value = 0;

     /* Convert string to integer */
     for (i = 0; i < 4; i++) {
         if (ac_str_temp[i] != '0') {
             switch (c_length - i - 1) {
             case 0:
                 us_value += (ac_str_temp[i] - '0');
                 break;
             case 1:
                 us_value += (ac_str_temp[i] - '0') * 10;
                 break;
             case 2:
                 us_value += (ac_str_temp[i] - '0') * 100;
                 break;
             case 3:
                 us_value += (ac_str_temp[i] - '0') * 1000;
                 break;
             }
         }
     }

     if (us_value > (5 * VOLT_REF / 6) || us_value < (1 * VOLT_REF / 6)) {
         return -1;
     }

     return us_value;
 }

 int main(void)
 {
     uint8_t uc_key;
     int16_t s_volt = 0;
     uint32_t ul_value = 0;
     volatile uint32_t ul_status = 0x0;
     int32_t l_volt_dac0 = 0;

     /* Initialize the system */
     sysclk_init();
     board_init();

     /* Initialize debug console */
     configure_console();

     /* Output example information */
     puts(STRING_HEADER);

     /* Initialize DACC */
     /* Enable clock for DACC */
     pmc_enable_periph_clk(ID_DACC);
     /* Reset DACC registers */
     dacc_reset(DACC);
     /* External trigger mode disabled. DACC in free running mode. */
     dacc_disable_trigger(DACC);
     /* Half word transfer mode */
     dacc_set_transfer_mode(DACC, 0);
     /* Power save:
      * sleep mode  - 0 (disabled)
      * fast wakeup - 0 (disabled)
      */
     dacc_set_power_save(DACC, 0, 0);
     /* Timing:
      * refresh        - 0x08 (1024*8 dacc clocks)
      * max speed mode -    0 (disabled)
      * startup time   - 0xf (960 dacc clocks)
      */
     dacc_set_timing(DACC, 0x08, 0, 0xf);
     /* Disable TAG and select output channel DACC_CHANNEL */
     dacc_set_channel_selection(DACC, DACC_CHANNEL_0);
     /* Enable output channel DACC_CHANNEL */
     dacc_enable_channel(DACC, DACC_CHANNEL_0);
     /* Setup analog current */
     dacc_set_analog_control(DACC, DACC_ANALOG_CONTROL);

     /* Set DAC0 output at ADVREF/2. The DAC formula is:
      *
      * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
      * ----------------------------------- = --------------------------
      *              MAX_DIGITAL                       digit
      *
      * Here, digit = MAX_DIGITAL/2
      */
     dacc_write_conversion_data(DACC, MAX_DIGITAL / 2);
     l_volt_dac0 = (MAX_DIGITAL / 2) * (2 * VOLT_REF / 3) / MAX_DIGITAL +
             VOLT_REF / 6;

     /* Initialize ADC */
     /* Enable clock for ADC */
     pmc_enable_periph_clk(ID_ADC);
     /*
      * Formula: ADCClock = MCK / ( (PRESCAL+1) * 2 )
      * For example, MCK = 64MHZ, PRESCAL = 4, then:
      *     ADCClock = 64 / ((4+1) * 2) = 6.4MHz;
      */
     adc_init(ADC, sysclk_get_cpu_hz(), ADC_CLOCK, ADC_STARTUP_TIME_SETTING);

     /* Formula:
      *     Startup  Time = startup value / ADCClock
      *     Transfer Time = (TRANSFER * 2 + 3) / ADCClock
      *     Tracking Time = (TRACKTIM + 1) / ADCClock
      *     Settling Time = settling value / ADCClock
      * For example, ADC clock = 6MHz (166.7 ns)
      *     Startup time = 512 / 6MHz = 85.3 us
      *     Transfer Time = (1 * 2 + 3) / 6MHz = 833.3 ns
      *     Tracking Time = (0 + 1) / 6MHz = 166.7 ns
      *     Settling Time = 3 / 6MHz = 500 ns
      */
     /* Set ADC timing */
     adc_configure_timing(ADC, ADC_TRACK_SETTING, ADC_SETTLING_TIME_3,
             ADC_TRANSFER_SETTING);

     /* Channel 5 has to be compared */
     adc_enable_channel(ADC, ADC_CHANNEL_5);

     /* Enable clock for ACC */
     pmc_enable_periph_clk(ID_ACC);
     /* Initialize ACC */
     acc_init(ACC, ACC_SELPLUS_AD5, ACC_SELMINUS_DAC0,
             ACC_EDGETYP_ANY, ACC_INVERT_NO);

     /* Enable ACC interrupt */
     NVIC_EnableIRQ(ACC_IRQn);

     /* Enable */
     acc_enable_interrupt(ACC);

     dsplay_menu();

     while (1) {
         while (uart_read(CONSOLE_UART, &uc_key)) {
         }

         printf("input: %c\r\n", uc_key);

         switch (uc_key) {
         case 's':
         case 'S':
             printf("Input DAC0 output voltage (%d~%d mv): ",
                     (VOLT_REF / 6), (VOLT_REF * 5 / 6));
             s_volt = get_input_voltage();
             puts("\r");

             if (s_volt > 0) {
                 l_volt_dac0 = s_volt;
                 /* The DAC formula is:
                  *
                  * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
                  * ----------------------------------- = --------------------------
                  *              MAX_DIGITAL                       digit
                  *
                  */
                 ul_value = ((s_volt - (VOLT_REF / 6))
                     * (MAX_DIGITAL * 6) / 4) / VOLT_REF;
                 dacc_write_conversion_data(DACC, ul_value);
                 puts("-I- Set ok\r");
             } else {
                 puts("-I- Input voltage is invalid\r");
             }
             break;
         case 'v':
         case 'V':
             /* Start conversion */
             adc_start(ADC);
             ul_status = adc_get_status(ADC);
             while ((ul_status & ADC_ISR_EOC5) != ADC_ISR_EOC5) {
                 ul_status = adc_get_status(ADC);
             }
             /* Conversion is done */
             ul_value = adc_get_channel_value(ADC, ADC_CHANNEL_5);

             /*
              * Convert ADC sample data to voltage value:
              * voltage value = (sample data / max. resolution) * reference voltage
              */
             s_volt = (ul_value * VOLT_REF) / MAX_DIGITAL;
             printf("-I- Voltage on potentiometer(AD5) is %d mv\n\r", s_volt);
             printf("-I- Voltage on DAC0 is %ld mv \n\r", (long)l_volt_dac0);
             break;

         case 'm':
         case 'M':
             dsplay_menu();
             break;
         }
     }
 }

```

I'm afraid you'll have to study how to configure the registers, taking the datasheet and, as a guideline, **the ACC and PMC definitions linked above**.

---
Tags: arduino-due, arduino-leonardo, atmega32u4, analog-sampling, arduino-zero
---


# Question
Title: Feasibility of project with 50 leds working independently
I don't have much knowledge in Arduino and I'm about to start a new project which I believe can be done with it.

There will be 50 boxes with a led in top of each one. The user will type a number in a keyboard (1 to 5 for example), and then based on a table, the leds according to that number should light up.

It will have some overlaps, for example, Number 1 would light led 1, 2 and 3, while Number 2 would light leds 1, 2, 3 and 4.

Could I build such a project with arduino? Or are there too many inputs/outputs (keyboard, 50 leds)? I was thinking to buy an Arduino Uno to start learning, but first I'd like to know if it's feasible.

Thanks already

# Answer
> 4 votes
depending on how you want to control your LED's there are several options. firstly to be clear you could not feasibly connect that many LEDs to an arduino that could all be turned on at once (if that was needed) without damaging the arduino.

if all you need is on/off level of control then you could look at shift registers or if you have pre built arrays of LEDS in a grid type layout you could look at the MAX7219/MAX7221

if you also wanted to be able to control the brightness individually then you could look at the TLC5940

if we look at the pros and cons of each approach:

# 74HC595

pros:

* cheap to buy
* simple to use

cons:

* each LED needs its own resistor
* cannot vary brightness
* if not using the hardware SPI pins can be slow for large numbers of outputs

# MAX7219/MAX7221

pros:

* lower current draw than 74HC595
* only needs one resistor per IC which can drive 64 LEDs

cons:

* actually flashes LED's really fast to look like they are always on
* costs more than 74HC595

# TLC5940

pros:

* can vary brightness with a high number of steps (4096 steps from fully off to fully on)

cons:

* uses more output pins than either of the above methods
* requires resistor per LED
* costs more for the IC than 74HC595

so to sum up, each method has its merits. if you are driving individual LEDs the the 74HC595 is probably the best/simplest route, if you are driving an array then the MAX7219/MAX7221 is best, and if you need variable brightness then the TLC5940 is probably best.

---
Tags: led
---


title: Arduino PC to RS232 not reading data

text:
# Question
Title: Arduino PC to RS232 not reading data
I am trying to read data from RS232 Shield with an Arduino Mega.

This is the schematic pin, TX is 3 and RX is 2.

Wiring: PC \> USB-RS232 cable \> Arduino RS232 Shield. Software to send/receive data: Hercules Setup Utility

From Arduino, I can transmit data to RS232, the TX led blink and I got the value at PC. From PC, I send the data, the RX led blink but nothing is showed in Arduino Monitor.

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

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

  Serial.println("Goodnight moon!");

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

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

```

I also tried to move RX and TX to Pin 15 and 14 but worked as the same as before.

# Answer
Found the problem, cant use PIN 2 as RX.

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

---
Tags: arduino-mega, softwareserial, rs232
---


# Question
Title: l293d is not able to drive two 300 rpm motors simultaneously
I am using l293d in a line follower but recently I am facing a problem. my l293d motor driver is not able to power 2 300 rpm motors simultaneously while with one of the motors at a time it works perfectly fine. Earlier it used to drive both the motors at optimal desired speed but recently its posing the above mentioned problems. I have tried replacing the Motor driver and Arduino itself but nothing worked and I am still facing the problem.

# Answer
> 1 votes
1. Check if both channels are working in either direction individually.
2. Check the current draw under the load per motor using an Digital Multimeter as an Ammeter function.

**The L293 is designed to provide bidirectional drive currents of up to 1A at voltages from 4.5V to 36V. 600mA per channel for L293D**

3. As long as your motors at drawing more than 600mA per motor, it should work fine.

# Answer
> 1 votes
Check your power supply with a multimeter. Look out for voltage drops under load, or similar problems.

Also, make some tests with another power supply in order to find out if the one you're currently using is faulty or not. You say you've tried replacing the motor driver and the arduino, but not the power supply.

---
Tags: arduino-uno, motor
---


title: Two sensors on one input

text:
# Question
Title: Two sensors on one input
I got this question from my teacher the other day and I can't figure it out:

> If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

In short, the project includes an Arduino Uno with two ultrasonic sensors.

# Answer
There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.

The active solution requires a device called a *multiplexer*. This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors. It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor. It does mean, though, that both sensors can be active at once and you just select one to read the output from.

The passive solution is called *open drain* or *open collector* (if you are using TTL not CMOS terminology). This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground. When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin). When one sensor's output activates it turns on the transistor which then pulls the input pin low. This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.
> 3 votes

# Answer
This solution only actually uses one pin, but only works with simple things like push buttons (which are either open, or closed).

Connect a (different) resistor in series (end-to-end) with each switch. Connect the loose end of each resistor together to +5V. Connect the loose end of those two switches together, then via another resistor to ground. Where the two switches meet, connect them to an analog pin on your Arduino.

For example, you might use a 20k resistor with button A, and a 10k resistor with button B, and a 10k resistor connected to ground. They should be pretty close to the same value, and at least 1k each.

Use the ReadAnalogVoltage sketch to measure the voltage with different combinations of button presses (no button pressed, A, B, A+B), then, in your final sketch, you can compare the value read with the values in this table - pick the closest one, because actual readings may vary slightly. For the resistors above, you should get about: (no button = 0v; A=1.7v, B=2.5v, both 3v). Sort these numerically (which in this case they already are), and work out the values exactly between each pair (up to 0.85 is closest to 0=\> no button; else up to 2.1=\> button A; else up to 2.75 is closest to B; otherwise, both are pressed.

The circuit described looks like this:

The wire leading off to the right goes to the analog pin on the Arduino. Switch A is on the left.

The results can be used either in a table, with a loop, or in an if/else if statement (I used this technique on a 12-key keypad, so the list was a lot longer).

Read up about voltage dividers https://learn.sparkfun.com/tutorials/voltage-dividers and, for both buttons being pressed at the same time, resistors in parallel https://learn.sparkfun.com/tutorials/series-and-parallel-circuits
> 1 votes

# Answer
> If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

If you want your teacher lose his mind answer his question with this:

What I need? :)

* A wire

The solution is to use one trig for both ultrasonic sensor and two echos.

or one echo and two triggers.

ultrasonic sensor sends the pulse \> pulse back \> now echo pin is connected to second sensors trig \> the Second Ultrasonic sensor sends the pulse then starts listening. When the second ultrasonic echo back, it sends to other Arduino pin, reverse it if you want it on one input pin :)

```
#define trigPin 6
#define echoPin 4
#define echoPin2 7

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
   pinMode(echoPin2, INPUT);
}

void loop() {
  long duration, distance, distance2;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(20);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  duration = duration + pulseIn(echoPin2, HIGH);
  distance2 = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println("cm");
       Serial.print(distance2);
    Serial.println(" cm");
        Serial.println("HHH");
  }
  delay(500);
}

```

that's it.
> 1 votes

# Answer
I ran into the same question, except I wanted to put 8 of the HC-SR04 sensors on pro-mini.

I used an I2C pin expander for the triggers, and an octal OR/NOR chip to multiplex the return.

Library, examples and pictures

https://github.com/arielnh56/SonarI2C http://redhunter.com/blog/2016/04/28/sonari2c-multiple-hc-sr04-sensors-on-arduino-i2c/
> 1 votes

# Answer
The OP does not specify whether the focus is on hardware or software.

So I will presume that what the professor might looking for is a solution using minimal circuitry; as close to the diagram as possible. Thus, the solution would be implemented in software.

Given all that, I'd propose that the trigger signal be sent out on sensor 1, and the reflection measured at the receiving pin.

It is time-gated (the time for the sensor to react to an object at maximum range). If detected, then set a variable saving the distance measured on sensor 1.

Then the same could be sent from the second sensor's trigger pin. And if there is a reflection within the time-gate then that can be recorded in another variable.

It would require creating two instances of the ultrasonic sensor, and they would just happen to share the same receive pulse pin.
> 1 votes

# Answer
Try the above logic use a 555 timer with C1: 10uF, R2: 300k and R1: 30k for 1.1 sec switching time,now for approx every one second data from USS1 goes to SIN(Arduino IN) when the timer OUT is high and similarly when timer OUT is LOW signal from USS2 goes to SIN(Arduino),,,

But you will not be able to know from which sensor is the output coming.

If you would like to know from which sensor the output is coming you can just add one INVERTER to one of the branch so so both the sensors will give different states i.e one will return HIGH and other will return LOW

hope this helps

Edited:Please note 555 timer design part is not complete ,,i am just giving an idea :)
> 0 votes

# Answer
A SPDT switch would fit nicely in your diagram where the question mark is.
> 0 votes

# Answer
The question is two Ultrasonic data get input on one. Its simple. You just need two IDs. Creat a IDs of each sensors. You can use I2C bus too. You need to hub who keep the two input in raw. And than digitally write with address and than do codding for read the data. Howz my idea guys?
> 0 votes

---
Tags: arduino-uno, sensors
---


# Question
Title: How to power an Arduino using automated mains/rechargeable battery switching?
I'd like to power my Arduino circuit like a smartphone. That is:

* When the device is unplugged, power by rechargeable battery
* When the device is plugged in, power by mains and charge battery at the same time

I'd like to not go the expensive shield route and instead purchase some inexpensive breakout boards from Aliexpress or eBay if possible. I'm willing to put in the time to learn if someone will point the way.

Can someone please provide some guidance?

# Answer
Yes, charging a battery and supplying an Arduino at the same time is possible as long as we manage the caveats (see below) of in-circuit charging.

---

## This is what I use:

---

## This is how it works:

* charger is fed via solar panel and/or USB supply,
* battery is continuously supervised and charged on demand
* Arduino is connected to the output side of the charger

This works because the load that the Arduino presents is relatively small compared to what the charger can feed (and what the battery can take). During recharging the charge current will predominantly flow through the battery. And since the current through the battery drops once it gets full, the charger can still recognise this drop and finish the charge cycle – even though the Arduino is connected all the time.

---

## Example setup:

I took some quick snapshots, please excuse the image quality. Charger is in the center, Arduino to the upper left, battery in a holder to the lower left, solar panel to the upper right.

The Arduino has a voltage regulator, but I don't use it in this setup. An explanation why and when to use the regulator is beyond the scope of this question and a matter for another answer.

In the first photo the charger input is only connected to the solar panel, but the panel voltage is low. So the charger is actually *off* and the Arduino is running off the battery.

---

In the second photo the charger is now connected to a USB power supply. The charger is on and in CC/CV charge mode (as indicated by the red LED of this charger model).

---

In the third photo the charge cycle is completed, the battery is full (as indicated by the blue LED of this charger model). Note that the charger could determine the charge completion even though the Arduino is connected and running (no power saving tricks involved here).

---

## Background info:

The charger switches between CC and CV mode, depending on the level of discharge the battery is in. Particularly, my charger uses CC mode in case the voltage on the battery side is below 4V and CV mode in case the voltage on the battery side is above 4V. The current limit can be configured and the voltage limit is hard coded to around 4.2V, which makes the circuit save for a device like Arduino.

Image source: Nanjing Top Power

Other chargers may have other thresholds, but that doesn't matter as long as it fits your battery type and uses constant current/voltage only. I have no particular recommendation for a charger, but so far have a good impression of the one I used in this answer.

---

## Caveats:

There are a couple of cases to consider, though:

### Deep discharge

Should the battery voltage ever go below around 2.9V (e.g. deeply discharged battery), the charger will switch into trickle charge mode where only very small amounts of current are passed to the battery – too little current (i.e. too low a voltage) for the Arduino to run. Arduino will go into brown-out and try to restart until the battery has recovered. So this can become a state in which your Arduino won't respond for an unknown amount of time.

### High load

If the load connected to the battery draws a current that isn't small anymore – compared to the battery charge current – then the charger cannot recognise a full battery anymore, since the current as seen by the charger will never fall off at the end of any charge cycle. So watch out how many gadgets you connect to this kind of in-circuit charger.

### Wrong charger type

There are a multitude of ways to charge a battery. Things like trickle charge, pulse charge, timer based charging, and so on. None of these would likely work, as the voltage those charger types generate could upset the Arduino and the load the Arduino presents could upset the charger.

Please also note that some chargers don't supervise the battery. With Li-Ion or Li-Poly (and other) batteries this would be a very bad idea. Always choose a charger appropriate for your battery.

---

## Alternatives

The charger I use employs a linear regulator. That's not very efficient, other topologies are possible. But they might require supply filtering for the Arduino.

---

## Shameless plug

I wrote a library for the purpose of supervising an Arduino's supply voltage (and chip temperature). This technique allows to check the battery level without any additional components. That library is called CoreSensors.

---

## Further links:
> 6 votes

# Answer
There are many ways you can do this, as you mention there are ready made shields that do this.

You need to take a few thing into consideration:

1. Power - how much power will your cirquit be drawing, as many of these boards will only be able to deliver 3-600mah is this enough, at the same time you will find out how long your cirquit will be able to stay on battery power.
2. Complexity - a ready made controller/charger is already made to work togheter, if you go for a separate charger and booster module you might end up with unwanted power loss, or you need ekstra buttons/sliders to control power.

You could in theory use 1 lipo cell directly to power your MCU, as the voltage spans from 3,6 to 4,7 Volts pr.cell and charge the lipo when NOT in use (you cannot charge a lipo directly while in use, thats why you need a controller). This would be the cheapest way.
> 3 votes

# Answer
> Can someone please provide some guidance?

power your arduino from a power bank and then power the power bank via ac adapter.

simplest and likely most inexpensive solution.
> 0 votes

---
Tags: power, battery
---


# Question
Title: What is the relationship of an Arduino .ino file to main.cpp?
Is the `.ino` file an alternative from a `main.cpp` file?

If yes, then could someone mind explaining the structure of the `.ino` file in `main.cpp` and its relationship?

# Answer
> 11 votes
The Arduino uses the gcc compiler. That compiler wants a normal `main` function of course. Arduino has put a layer on top of that with `setup` and `loop`.

The hidden `main` function for basic Arduino boards is in main.cpp (click on it to see it).
You see that `init` is called, and `setup` and `loop` and a few other things.

To learn how to use `setup` and `loop`, you can try a few examples. They are in the menu of the Arduino IDE and they are also online.

The .ino files are all combined together and presented to the compiler as a single .cpp file to compile. The Arduino libraries are compiled from source as well, and everything is linked into a binary.

When you know how to use `setup` and `loop`, try the Blink Without Delay example. It can be used to run different software timers and do all kind of tasks and keep everything running smooth.

---
Tags: arduino-ide, c++
---


# Question
Title: Communicate between NodeMCU ESP8266 gateway and multiple sensor nodes
What is the best **wired** way to communicate between multiple **NodeMCU ESP8266** boards for home automation.

Every room should get at least a light, temp, PIR and xx relay modules to switch things on and off.

To connect all these sensors the GPIOs from one NodeMCU are sometimes not enough.

To reach this goal I planned to install in every room one NodeMCU as gateway and multiple NodeMCU as nodes for my sensors. The gateway will receive and forward information from/to my **openHAB** center via **MQTT** messaging.

I thought to use an **RS-485** 2-Wire connection between my sensor nodes and the room gateway. The gateway from my room will be connected via wifi or wired cable to my network.

I2C seems more to be for communication directly on PCBs or only short wiring.

Do you have any suggestions for me, is my plan possible? Any better ideas?

# Answer
> 1 votes
If you really wanted wired communication then yes, RS-485 is the way to go.

In any installation where you will be running cables in the vicinity of mains wiring you will have noise. I2C is very bad with noise and not a good choice for any off-board wiring. RS-485, however, owing to the balanced line nature of the signalling, is designed to reject common mode noise such as is induced by mains wiring.

I would ask, though, *why use ESP8266 as remote wired nodes?* It seems a real waste to use a WiFi module for wired communication - a smaller, simpler, lower powered board (Arduino Micro / Mini maybe \[3.3V, 8MHz version for simplicity of interfacing\]) would be far more suitable for such a role.

---
Tags: arduino-uno, esp8266, nodemcu, rs485
---


# Question
Title: Is it possible to make normal pins act like ground pins?
So what exactly I am trying to do is control a motor and be able to turn it both ways without any extra parts.

So if the hmp was on (the plus pole) and the hmm (the minus pole) acted like ground the motor should start turning right.

But if the hmp acted in this case as ground and the hmm like the plus pole it should start turning the other way.

I know that it's probably not going to work. I'm just experimenting.

```
int Hmp=12; // the plus pole
int Hmm=11; // the minus pole

while (HR=0 || Sr > Sl+300) {
  pinMode(Hmp, OUTPUT);
  digitalWrite(Hmp, HIGH);
  pinMode(Hmm, INPUT);
}

while (HR=1 || Sl > Sr+300) {
  pinMode(Hmp, INPUT);
  pinMode(Hmm, OUTPUT);
  digitalWrite(Hmm, HIGH);
}

```

# Answer
You have to put both pin in OUTPUT mode. You digitalWrite() the "positive" pin HIGH and the "negative" pin LOW.

But, it's not a good idea in this case:

1. Motor's power requirement exceeds digital output pin current of 40 mA.
2. Back EMF. Every time you stop the motor, there is a brief current pulse back to your pins. Bad.

The proper ways to control a motor is this:

This will control only one direction. For changing directions, you need a H-Bridge. An H bridge is an electronic circuit that can drive the motor in both directions.
> 3 votes

# Answer
No, it's not going to work - even worse, you risk frying your Arduino -, for the following reasons:

1. The Arduino data pins can't source (neither sink) enough current for that to work.
2. The inductive kickback of the motor could fry Arduino pins.

The right way to do what you want to do is **using an H-bridge controlled by your Arduino data pins**. There are lots of Motor Driver PCB modules for Arduino (most of them based on the inefficient L298 driver IC, which you should ignore and look instead on those based on the TB6612FNG driver IC or similar, because it would be a far better solution) that implement this function.
> 10 votes

# Answer
I don't think that's going to work.

You'll be better off using a cheap module like the Pololu Pololu DRV8838 which implements a MOSFET H-bridge.

(Note: I'm not related in any way with Pololu.)
> 3 votes

# Answer
I just tried what you suggest, and it works fine, with only one (big) caveat: you can only power this way very low power motors. I did this to drive the linear motor that moves an HDD head assembly. This motor works perfectly fine with less than 18 mA.

Note that I switch the Arduino pins between the `HIGH` and `LOW` states, not going through `INPUT`. Setting the pin to `INPUT` would send the motor's inductive kickback through the pin's protection diodes. On the other hand, the inductance of this motor is presumably tiny...

For anything that can draw more than 40 mA, I would use an H-bridge. For something between 20 and 40 mA, I may take the risk of driving it directly *if* it's for an experiment where I am not too much concerned about the risk of loosing my Arduino.
> 2 votes

# Answer
> is it possible to make normal pins act like ground pins?

the answer is yes: i'm looking right now at a blinking led that straddles between two GPIOs with one of them permanently (via code) grounded so i can blink it via the other GPIO pin.

Obviously the usual limitations that apply to a GPIO pin apply here.
> 0 votes

---
Tags: serial, motor, pins, arduino-duemilanove, digitalwrite
---


# Question
Title: Encode & decode boolean values into a single integer?
I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

```
Pin 1: TRUE
Pin 2: FALSE
Pin 3: FALSE
Pin 4: TRUE

Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
1 + 0 + 0 + 8
Result: 9

```

This is pretty efficient. But how do I decode the pin states from this best? Or do you recommend a better way to do this?

# Answer
use the AND operator.

for example:

pin 2's state would be (result & 0x02)?TRUE:FLASE
> 0 votes

# Answer
You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the *bit number* in there. The `<<` is *left shift*.

```
#define PIN0 (1 << 0)
#define PIN1 (1 << 1)
#define PIN2 (1 << 2)
#define PIN3 (1 << 4)

```

Now you can combine:

```
uint8_t val = PIN0 | PIN3; // 9

```

And you can check if one is set:

```
if (val & PIN3) {
    // ....
}

```

To loop through the pins you can use the `<<` again:

```
for (uint8_t pin = 0; pin < 8; pin++) {
    if (val & (1 << pin)) {
        // ....
    }
}

```

etc.
> 5 votes

---
Tags: bit
---


# Question
Title: Send AT commands programatically to ESP8266 without Arduino
Let me explain my question in more details. I want to use ESP8266-01 as standalone micro-controller for my project. I don't want to use Arduino or any other board with that. Using Arduino i can use two of the pins as software serial and can send different AT commands to ESP module to ESP's Tx and Rx pins, but now what I want is to eliminate the need to Arduino.

What I want to do is to to program ESP itself to toggle mode from AP mode to Host mode on press of a push button. for that I has to send AT commands to ESP from the code while i will write to the ESP itself. Is there any way to achieve the same.

I tried searching a lot but what I found everywhere is how to send AT commands from Arduino.

Thanks in advance.

# Answer
You don't use AT commands. You install the esp8266 boards package and program the esp8266 as if it were an Arduino. That means learning the esp8266 WiFi API which has plenty of examples included.
> 1 votes

---
Tags: serial, esp8266
---


# Question
Title: Detect where pressure is being applied by using force resistors
I have 3 force resistors in a row, on top of which I have placed a board. I read values from the resistors through analogue ports. My goal is to be able to detect whether someone is pressing on the top, middle, or bottom of the board.

So far I can easily detect the left and right, like this: I first calibrate the 3 sensors for 2 seconds. Then I detect if pressure is applied on any of the calibrated sensors. If yes, I sum for all of them the values that they return on each round of the loop, until force has stopped being applied. I finally compare the 3 values against each other and I find which received higher pressure in total. This works perfectly fine for the left and right. However, when the board is pressed in the middle, pressure is applied on all 3, since the board is flat. Sorting the values does not help, because very often the left and right sensors have recorded a higher value than the middle.

I noticed that when the board is pressed on the left, the right sensor records very few values, and the same for the other way around. So, I get a high success rate in detecting middle presses like this:

```
int threshold = 80;
if (left_sum > threshold && middle_sum > 80 && right_sum >80)
    return middle_pressed;

```

However, when someone presses hard enough on the left or right, the if statement is satisfied.

Is there a more accurate way to detect where force is being applied?

*(Following is a quick schematic I made - I am not at all an expert so please excuse me for my mistakes, I just hope it illustrates more or less what it is supposed to)*

simulate this circuit – Schematic created using CircuitLab

Please ignore the double arrows right on top of the resistors.

# Answer
> 1 votes
Let's assume that you have only two FSR sensors. With those you can make three virtual buttons (above the left sensor, above the right sensor and in the middle).

To measure someone's weight, it is allowed to have a scale under each foot and add both weights. We can use that to calculate the total force pressing to the board, by just adding the two forces.

The FSR sensors have a curve to calculate the force in newtons. It is very inaccurate, but works more or less. That can be added later. For now let's assume that it is linear to the ADC value of the Arduino.

Are the FSR sensors connected to an analog input and GND ? Do you have a resistor between the analog input and 5V ? I assume you do. You need the resistors so that a nice pressing force to the board results somewhere in the middle of the ADC range.

Pseudo code:

```
setup()

  Measure both ADC values (or a number of values and use the average)
  Store them as offsets in a global variable.

loop()

  Measure both ADC values, substract the offset.

  Translate the ADC values into force.
  The more force the higher the number should get.
  Any range is okay for now.
  They can be translated into Newton later.

  The total force is by adding the two forces.

  The position in percentage is the force of the right sensor
  divided by total force times 100.
  Then the position will be 0 for left sensor, 50 for middle
  and 100 for right sensor.

  If the total force is above threshold, then check the position.

  for example position -50 to 20 for left virtual button.
  for example position 30 to 70 for middle virtual button.
  for example positition 80 to 150 for right virtual button.

```

You can start by printing the forces to the serial monitor. Press the board and check if the numbers increase when pressing more.

Don't get confused when you print the position. It will be very noisy when no force to the board is applied. It should be valid when the total force is above the threshold.

For the position I allow a large error of 50 percent left of the left sensor and right of the right sensor. It depends on the mechanical construction and the rest of the code if that makes sense.

Print the results to the serial monitor.
If that is working well, then you have to detect a single press.

Let's assume that as soon as the threshold is reached, a press to a virtual button is accepted. Let's not wait until the peak of the force is reached.
The State Change Detection example can be used to create a single event for pressing the virtual button.

Any jitter or noise (for example a single press to the board results into two events for the virtual button) can be solved by averaging or filtering in software. I think that it will be needed.

I'm not sure if all of this is okay. I hope that someone else will look into it as well.

# Answer
> 0 votes
> Is there a more accurate way to detect where force is being applied?

normalize your measurements vs. the static values of those strain gauge readings obtained during calibration.

---
Tags: arduino-uno, algorithm
---


# Question
Title: Problem with reading series of bytes over serial port
I'm writing a program to read bytes from serial channel, copy those into an array and then do some verification on those copied numbers.

I'm able to read and copy bytes into an array of bytes. However, I'm facing an issue with the verification of those bytes.

Here's the code I've written:

```
#include <SoftwareSerial.h>

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

void loop()
{
    char charRead = 0x00u;
    byte byteArray[10];
    int i=0 , j=0;

    //Clear the array contents
    for(j = 0; j < 10u; j++)
    {
       byteArray[j] = 0x00u;
    }

    //Wait for data on serial channel
    while(Serial.available() > 0)
    {
       //Copy bytes received into array
       charRead      = Serial.read();
       byteArray[i] = (byte)charRead;
       i++;
    }

    //Just for the sake, print the array contents
    for(j = 0; j < i; j++)
    {
       Serial.print(byteArray[j],HEX);
    }

    //Check for first two bytes
    if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )
    {
        Serial.println("Verified.");
    }
}

```

To test this program, I entered "12345" (without quotes) on the serial monitor which gave me an output as "3132333435" since I'm printing the contents of the array in HEX format.

What I'm not being able to understand is even if this output shows that the first two bytes in the array are 0x31 & 0x32 respectively, why not the verification logic of those two bytes is getting executed? If it would, then the string 'Verified' would get printed on the output.

Am I doing something wrong here with Serial.read() or some typecasting?

I'm running this on an Arduino Uno

# Answer
> 0 votes
So, as result of Edgar Bonet's good remark, change

```
int i=0 , j=0;

```

to

```
int j = 0;

```

and define

```
int i = 0;

```

Outside the loop (as a global variable).

Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.

---
Tags: serial
---


# Question
Title: How to use Atmega1284AU with Arduino IDE
Is there any support to this chip in Arduino IDE, like bootloaders and boards definitions.. i want to use this chip with 3.3V and 8Mhz crystal speed..

I have seen Nick Gammon bootloaders supports this chip for bootloaders, but not with 8Mhz.? and how to add this chip to Arduino IDE.

anybody help..

thanks you

# Answer
> 1 votes
Please check out MightyCore library by MCUdude.

https://github.com/MCUdude/MightyCore

I have used it and can verify it works pretty well with ATmega1284.

---
Tags: arduino-uno, arduino-ide, bootloader
---


# Question
Title: Send signal to vibrate a Restaurant buzzer via web based app to a PC
I'm new to Arduino, I want to create a restaurant buzzer using Arduino and it should turn on/off via web based interface. It will be locally connected only.

Is it possible to send a signal with the mac address of the master transmitter pc to vibrate the buzzer?

What are the materials should I need? Suggestions or any tips is greatly appreciated.

# Answer
> 1 votes
You need a webserver, a defined interface for the client to connect to and a buzzer you can make some noise with.

Because you want to do it over WIFI, an Arduino is probably not the best choice. As 'Look Alterno' says you might be better with an ESP8266 based device, because that has inbuilt WIFI. I would suggest a Wemos D1, its an ESP8266 12 with a power supply and 2.54 pitch connectors, which means its easy to use with things.

Now you can program an ESP8266 using LUA, but I really wouldn't try that. Also if you do that you won't get any help on this forum. Use the Arduino IDE and program it in the same language as an Arduino (You will need to download support for the ESP via the Board Manager in the IDE). There is an example called "Advanced Web Server", done by Majenko on here, that will suit your needs. You just need to change the root handler to activate the buzzer for n seconds and then return HTTP code 200.

Then your client just needs to connect to the root page of the webserver and the buzzer will sound. You don't say how many clients will use this, but this will allow 5 simultaneous clients, if you need more that can be achieved easily.

You can then expand this to identify which client sounded the buzzer.

As to keeping it local, use the firewall on your router.

---
Tags: programming, wifi
---


# Question
Title: DigitalWrite Cannot Power HC-06 Bluetooth
To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V \<=\> pin 11, HC-06 gnd \<=\> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered. What have I done wrong?

# Answer
A digital IO pin is only capable of powering an LED or an incredibly low powered device. It is **not** suitable for powering meaty RF modules.

Instead you need to control the power to your module using a P-channel MOSFET as a High-Side switch.

For instance, assuming a 5V module with built in 3.3V LDO:

simulate this circuit – Schematic created using CircuitLab

Note that `/RFEN` is active low - set the pin OUTPUT and LOW to turn the module on. M1 should have a threshold of no lower than -4V, better -2V or higher.

Also be sure to set RX and TX to be INPUT when you power down the module or back-powering through the TX/RX pins may occur.

R2/R3 is a simple logic level shifter for the 3.3V logic signal the RX pin expects.
> 1 votes

# Answer
> it should have enough power.

Probably not. Debugging is about challenging all assumptions, especially implicit ones.

Put a high side switch there and it should be ok.
> -1 votes

---
Tags: arduino-nano, bluetooth, pins, hc-06, digitalwrite
---


# Question
Title: If (serial.available()) conditional statement
I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()\>0)

Thanks in advance!

# Answer
In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.
> 1 votes

# Answer
> Scenario A, it appears to me that there is no conditional statement, h

The first is a test on if available() returns a non zero value.
> -1 votes

---
Tags: arduino-uno
---


title: Serial Monitor "button" implementation

text:
# Question
Title: Serial Monitor "button" implementation
I have a small project and I have some problems while working on that. The idea of the project is as below: I have an LED which is operated by two "buttons". The buttons takes two values (1 or0) which I have to send from serial monitor. One button is for LDR sensor, which lights up the LED when its value is below 300 (in my code). The other button turns it off (Value 0). The buttons are working together, so I have to consider both of them in my statements. The problem is that I cannot play with the serial monitor it's just looping continuously and I cant type anything as input.

Can anyone help me with this to find a solution to be able to input values for both buttons?

Here is the code:

```
const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

char Buton1; //LDR button
char Buton2; //Blutooth button

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

void loop()
{
  while (Serial.available())
  {
    Serial.println("Button1 value: ");
    Buton1 = Serial.read();
    if (Buton1 == '1')
    {
      Buton2 = Serial.read();
      Serial.println("Button2 value: ");
      if (Buton1 == '1' and Buton2 == '0')
      {
        sensorValue = analogRead(analogInPin);
        outputValue = map(sensorValue, 0, 1023, 0, 255);
        Serial.print ("Sensor: ");
        Serial.println(sensorValue);
        if (sensorValue < 300);
        {
          digitalWrite(digitalOutPin, 255);
        }
      }
      else if (Buton1 == '1' and Buton2 == '1')
      {
        digitalWrite(digitalOutPin, 255);
        Serial.print("Both buttons are ON ! !");
      }
    }
    else if (Buton1 == '0')
    {
      Serial.println("Button2 value: ");
      Buton2 = Serial.read();
    }
    if (Buton1 == '0' and Buton2 == '1')
    {
      digitalWrite(digitalOutPin, 255);
    }
    else if (Buton1 == '0' and Buton2 == '0')
    {
      Serial.println("Both buttons are inactive ! Please reset");
      break;
    }
  }
}

```

# Answer
> 1 votes
A simple approach would be to use bit 0 of serial data to control "button 1", and bit 1 of serial data to control "button 2". As follows:

```
char sd = Serial.read();
byte button1 = sd & 1;
byte button2 = sd & 2; // Or (sd & 2)>>1 if you prefer

```

With the above code, button 1 is true for odd-digit inputs, and button 2 is true when `(sd & 2)>>1` is odd. For example, input 0 to turn off both buttons, 1 to turn on only button 1, 2 for only button 2, and 3 to turn on both.

You might also wish to button1 or button2 only when the input character represents a digit. For this, you can say:

```
char sd = Serial.read();
byte button1, button2;
... ;
if ('0' <= sd && sd <= '9') {
    button1 = sd & 1;
    button2 = (sd & 2)>>1;
}

```

# Answer
> 1 votes
The first problem is that your code does not wait for anything to be typed, so it loops very rapidly. Serial.read() returns -1 when there is nothing in the buffer, so I imagine your codes is printing something like:

```
Button1 value:
Button1 value:
Button1 value:
Button1 value:

```

Try inserting

```
while( !Serial.available() )
   ;

```

before your serial.read() calls. This will force it to wait until you type something before it continues.

# Answer
> 0 votes
Each button has a 1 state and a 0 state. The combination will always be something like this:

```
if (button1 == '1' and button2 == '1')
do something
if (button1 == '1' and button2 == '0')
do something
if (button1 == '0' and button2 == '1')
do something
if (button1 == '0' and button2 == '0')
do something

```

# Answer
> 0 votes
as it has been pointed before you the read function returns a -1 when there are no information to access, what you can do is

```
while( !Serial.available() )
{
  //do nothing
}
Buton1=Serial.read();
Serial.clear();   //for having the buffer clear for the next button

```

# Answer
> 0 votes
See if this helps:

```
const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

byte Buton1; //LDR button
byte Buton2; //Blutooth button

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

void loop() {
  while (Serial.available() > 0) {
    char inChar = Serial.read();
    if (inChar == 'l' || inChar == 'L')
    {
      Buton1 = Serial.parseInt();
      Buton1 = constrain(Buton1,0,1);
    }
    else if (inChar == 'b' || inChar == 'B')
    {
      Buton2 = Serial.parseInt();
      Buton2 = constrain(Buton2,0,1);
    }
    else
    {
      Serial.println("invalid input");
      while (Serial.available() > 0)
        Serial.read();
    }
    Serial.print("Buton1 = ");
    Serial.println(Buton1);
    Serial.print("Buton2 = ");
    Serial.println(Buton2);
    Serial.println();
  }
}

```

---
Tags: serial, code-review
---