title: Force Sensitive Resistor OverLoad

text:
# Question
Title: Force Sensitive Resistor OverLoad
I've got just a simple question. What happens when I overload Force Sensitive Resistor (FSR). Example Here.

Let's say that it's got force sensitive range between 100g and 10 000g. What would happen if I'd create pressure about 100kg? I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance? If so, can this FSR survive this overload? Has somebody test that?

Thank you for any answer.

# Answer
> I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance?

The harder the force, the lower the resistance. Sparkfun has a datasheet attached that shows the following graph:
Notice how both axis of the graph are logrithmic. This means that the resistance will never reach 0 ohms. However it will get close. At 10 Kg (22 lb) the resistance is about 250 ohms.

> What would happen if I'd create pressure about 100kg?

The datasheet has the following to say for weight above the 10 Kg mark:

> At the high force end of the dynamic range, the response deviates from the power-law behavior, and eventually saturates to a point where increases in force yield little or no decrease in resistance. Under these conditions of Figure 2 \[ie. the graph above\], this saturation force is beyond 10 kg. The saturation point is more a function of pressure than force. The saturation pressure of a typical FSR is on the order of 100 to 200 psi. For the data shown in Figures 2, 3 and 4, the actual measured pressure range is 0 to 175 psi (0 to 22 lbs applied over 0.125 in^2). Forces higher than the saturation force can be measured by spreading the force over a greater area; the overall pressure is then kept below the saturation point, and dynamic response is maintained. However, the converse of this effect is also true, smaller actuators will saturate FSRs earlier in the dynamic range, since the saturation point is reached at a lower force.

In summary, the weight applied can go over 10 Kg providing that weight is spread over the sensing area. The larger FSRs (such as this one) are better suited for this purpose as they have a larger area for which to spread the pressure.

Note: It is quite possible that with 100 Kg you could irreversibly damage the FSR, particularly if the weight isn't spread over the sensor area.

Measuring an analog voltage from the sensor is possible so that it can be fed into one of the analog pins of the Arduino. This Adafruit page has a nice table at the bottom showing the analog voltage that you get when you put the sensor in a voltage divider network (ie. in series) with a 10K ohm resistor.
> 2 votes

---
Tags: sensors, pressure
---


title: Issues graduating to AVR-C

text:
# Question
Title: Issues graduating to AVR-C
I'm trying to make the transition from coding in the Arduino language to AVR-C, but I'm having some issues with my microcontrollers.

I don't have an ISP, so I'm using one of my Arduino UNOs with the ArduinoISP sketch. The problem is that when I try to run avrdude it gives me this error:

```
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
  Double check connections and try again, or use -F to override
  this check.

```

However, when I try to run the command with the sugested -F it uploads the code to the Arduino UNO I'm using as an ISP instead of the ATmega328p on my breadboard.

Does anyone have any idea about whats going on here, or how to fix it?

# Answer
> 0 votes
"invalid device signature" is due to bad connection or inability to reset the device (RST pin fuse setting for example).

---
Tags: c, atmega328, avr, avrdude, arduinoisp
---


title: Arduino-based mains frequency monitor

text:
# Question
Title: Arduino-based mains frequency monitor
I'm looking to put together a simple mains frequency monitor based on the Arduino platform. The mains here are 250 V @ 50 Hz, but obviously these fluctuate slightly, which is the whole point of the exercise. (I am not interested in capturing voltage fluctuations, only frequency fluctuations).

I have never used any Arduino products before, but I am familiar with PIC-based MCUs. I understand Arduino should be somewhat simpler. Also, I am not an electronics engineer.

Presumably, the Arduino will sample the mains frequency for a second or two, and then report the result somehow. I guess the easiest way is for a computer connected to the Arduino by USB to receive the result and act accordingly. Otherwise, other options include adding an Ethernet module to the Arduino and having it HTTP POST the result to a web server.

(I assume doing this naive method is preferable to recording a time series and then performing a Fourier transform?)

Size isn't a huge concern, but a compact device is preferable over a larger one as I'll be 3D-printing a custom enclosure for it. Therefore I would like to use the Arduino Nano if it's suitable.

Here is what I have so far:

1. The 250V mains will be half-rectified with an IN4004 (?) transistor (together with a 1K resistor and 0.22 uF cap), and that will go into a 4N35 optocoupler.
2. A digital (?) GPIO pin from the Arduino goes into the base of the 4N35 and emitter goes to GND.
3. The Arduino samples for a short time the number of pulses on that pin, does a simple calculation, and reports the result.

Here are my uncertainties so far:

1. Based on my research, I believe the Arduino can reliably be powered by USB. If this is correct, this would be ideal as it would avoid me having to build a low voltage DC power supply for it.
2. How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?
3. I presume I'll need to debounce the result from the optocoupler? Will there be some noise as the transistor transitions between states? Are there built-in debouncing functions or will I need to write my own? How is this likely to affect available clock cycles and therefore the accuracy of the measurement?
4. I've seen PIC projects where it interacts with the computer by emulating a keyboard. While simple, this wouldn't be ideal as the computer it's connected to must also remain usable. The software processing the result should run in the background while a user can continue using the computer. How simple is it to write some software (in C#) that will recognise the Arduino connected via USB, and communicate with that device in particular?

I also welcome any other comments and suggestions. Thank you.

**Edit:** Following these helpful comments and suggestions, I've made some revisions and asked a follow-up question.

# Answer
> I understand Arduino should be somewhat simpler \[than PIC\].

The whole Arduino platform (boards, core library and IDE) makes it super easy to get started and do *simple* things. However, if you want to “push the limits” and use the full potential of the MCU, you may have to dig into low-level programming, and this has a steep learning curve.

> The 250V mains will be half-rectified with an IN4004 (?) transistor (together with a 1K resistor and 0.22uF cap), and that will go into a 4N35 optocoupler.

1 kΩ seems way too low to me: your resistor will dissipate on average 31 W, and it will burn unless it is a heavy-duty power resistor. You should choose a resistor that limits the current to a value low enough to avoid overheating, but still high enough to reliably turn on the optocoupler. If these two constraints end up being incompatible, you will need a step-down transformer in addition to (not instead of) the optocoupler.

> A digital (?) GPIO pin from the Arudino goes into the base of the 4N35 and emitter goes to GND.

The base of the optocoupler is typically left floating. You connect the Arduino input to the collector, using either the internal or an external pullup resistor, and you ground the emitter.

> 1. I believe the Arduino can reliably be powered by USB.

Yes, powering through USB is fine. The Arduino itself draws very little power. Only when *it* is powering something else you may worry about power limits. Here it would seem your Arduino will only be sourcing a very small amount of current into the output transistor of your optocoupler, so you will be fine.

> 2. How stable is the clock on the Arduino?

Terrible. Most Arduinos are clocked off a ceramic resonator. These are typically specified with 0.5% frequency tolerance, but their frequency is constantly fluctuating, and is also strongly dependent on ambient temperature. This makes those Arduinos grossly unsuited for any job requiring precise timings. I would recommend you get an Arduino sporting a real quartz crystal, like the Leonardo or the Micro. A quartz crystal can be quite inaccurate, but at least its frequency is stable. It's *orders of magnitude more stable than a ceramic resonator*. C.f. for example this article about the Arduino clock frequency accuracy.

> 3. I presume I'll need to debounce the result from the optocoupler?

If the capacitor after your half-wave rectifier is well dimensioned, your signal should be clean and not need debouncing. The Arduino digital inputs all have Schmitt triggers which clean up the input noise as long as it is not excessive. If you really need debouncing (check with a scope if you can), well... there are no provisions for doing so in the Arduino core library, but there is a Debounce tutorial among the examples shipped with the Arduino IDE, and there are a few third party debounce libraries floating around the Web.

> 4. How simple is it to write some software (in C#) that will recognise the Arduino connected via USB, and communicate with that device in particular?

As stated in other answers, your Arduino will be seen by your computer as a virtual serial port. I don't know C#, but any decent programming language should allow you to easily read data from a serial port.

**Measuring method:**

You will time one or several periods of the input signal. There are several ways of doing so. In roughly increasing order of complexity and accuracy:

1. You continuously monitor the digital input, in a loop, and whenever you see a transition from LOW to HIGH you record the current time using `micros()`.
2. You use an interrupt pin as the input and you have the interrupt handler record the time with `micros()`.
3. You use the *input capture* facility of your 16-bit timer running at the full CPU speed.

The methods using `micros()` have a resolution of 4 µs. Both will give you some software-induced jitter because they depend on the timing of your program execution. The advice given by GuitarPicker: “Keep your code predictable, using as few conditional branches as possible that might alter how long your code takes to run each cycle” is relevant only to the first method. The interrupt method is immune to your main loop timing, but it is still affected by the CPU processing other interrupts.

The *input capture* method will give you single-cycle resolution and accuracy, with zero software-induced jitter. That would be my first choice, but it requires digging into the MCU datasheet and doing some low-level programming.

---

**Addendum**: Here are some tentative answers to a comment posted by Ozzah to his own question:

> I probably want 4 decimal places if possible.

If you want 10−4 *absolute* accuracy, you may need to calibrate your clock, even if it is a crystal. If you only require 10−4 *stability* (variations of the frequency), then even a ceramic resonator may be (barely) up to the task, if you don't mind recalibrating it every few weeks, and assuming your indoor temperature doesn't vary by more than ≈ 10°C.

> I want the highest resolution and best tolerance possible.

Then a quartz crystal is definitely a plus. It's roughly 100 times more stable than the ceramic resonator.

But if you really want the “best”, you may as well follow Milliways' advice and get a GPS reference. Some options, in increasing order of price and accuracy:

1. A simple GPS module for the Arduino. Make sure you get one with a 1PPS output (a “one pulse per second” reference signal). You may want an external antenna for better reception.
2. A GPSDO (GPS disciplined oscillator). This is typically a lab-grade frequency standard consisting of an OCXO (oven-controlled crystal oscillator) disciplined by a feedback loop into tracking GPS time. It gives the same long-term stability as the simple GPS module but has far better short-term stability.
3. A rubidium-based GPSDO. This is similar to the above but has also a rubidium atomic frequency reference. Still better short-term stability. Now we are talking about stabilities in the 10−11 to 10−12 range. Provably overkill for your use case.

From the software point of view, I would recommend you start with the interrupt method, just to get a prototype working easily, and then go to the input capture method, as it will give you the best accuracy. It should be possible to be cycle-accurate with the interrupt method, but that would require some non-trivial tweaks.

Note also that the Arduinos based on the ATmega32U4 (Leonardo and Micro at least) have *two* 16-bit timers with input capture capability. You can then time both the mains signal and a 1PPS reference in parallel. If your Arduino has only one 16-bit timer (like the Nano), you would have to time one of the signals with the interrupt method.

> I'm trying to find a way to determine which Arduino boards use crystals for the MCU clock and which use ceramic resonators. From what I can see, they all have a crystal, but presumably that's for the USB interface?

Yes, the USB/serial interface is clocked off a crystal more often than the main MCU. The Arduinos that do *not* have a separate USB/serial bridge (like those based on the ATmega32U4) seem to have the main MCU clocked off a crystal.

> How can I get a list of Arduinos that use crystals?

It's often stated in the product page. E.g., the page of the Arduino Micro states (emphasis mine): “It has 20 digital input/output pins (of which 7 can be used as PWM outputs and 12 as analog inputs), **a 16 MHz crystal oscillator**, a micro USB connection, an ICSP header, and a reset button.”

Arguably, the info is not very prominent, and a compiled list would be useful. I think this could be a very good question to ask in this site.
> 3 votes

# Answer
It sounds like you're well on your way to creating a solid project. I will attempt to answer some questions and offer some suggestions on approaching this.

Rather than counting the number of AC pulses per time period, you might get better results seeing how many Arduino clock ticks you get between a sampling of say, 50 (debounced) pulses. This will give you bigger numbers to work with. Doing the opposite (seeing how many pulses per time period) will not give the same precision. If you only got 49 pulses in a second, did you just barely miss the 50th, or was it a whole 2% off? Since the Arduino clock can count much faster, it would be better to count those ticks instead.

1. Arduinos can be reliably powered by USB, as long as you don't draw too much current. Your application sounds like it shouldn't draw much at all.
2. The clock on the Arduino isn't going to compare with using a separate real-time clock circuit, but it should be good enough to measure trends and differences. Keep your code predictable, using as few conditional branches as possible that might alter how long your code takes to run each cycle.
3. Debouncing is probably a very good idea in this situation. There are several debouncing libraries available for the Arduino, or you can roll your own. Once again, the library should written as to not introduce inconsistent delays into the code. For this reason, it might be better to write your own specifically suited for this application. You might need to borrow an oscilloscope and see how long the pulses are from your optocoupler circuit. The closer you can get them to being a 0V/5V square wave, the better.
4. Arduinos come in many flavors. Some can emulate keyboards, but most act natively as serial ports. If you can read data from a serial port, then you can read the output from the Arduino. This should be trivial in C#, or just use a terminal emulator or the Arduino IDE's serial console to view the results. Once again, if you are outputting data while still measuring, then you should use use fixed width output so that the program takes the same amount of time to run each cycle. It would be far more accurate instead to take your measurements silently, and output the results afterward later so that you don't have to account for serial port buffer delays. Take another "flush" delay before starting measurement cycle again.
> 2 votes

# Answer
I would use a step-down transformer with that 1N4004 rectifier diode to limit the *peak rectified voltages* to less than the Arduino's safe input voltage. I would also be inclined to add a zener diode to ground at the Arduino's input to "clamp" or limit that input voltage to whatever your Arduino's safe upper limit is.

At some point you might also find it beneficial to double the 50hz using a full-wave rectifier to give you more pulses to count for finer resolution.

A low current fuse in there somewhere wouldn't be a bad idea either.
> 2 votes

# Answer
It's a safety issue at the very least. A catastrophic failure of the opto & everything is gone. At least with a "wall bug" style transformer, you've given yourself & your device a large safety margin.

I assume your opto will be triggered at line voltage & frequency to subsequently switch a 3.3 or 5v bus to an Arduino input pin at the 50hz line rate.

The opto you've chosen turns ON at ~1 volt & it needs a current limit of ~10ma thru it. You'll need to calculate a dropping resistor value to bring the *rectified peak voltage* down so that the opto isn't overloaded in either category. You'll need to also compensate for the eventual surge/peak voltages well above the typical line voltages.

There could conceivably be enough constant "noise" riding in on the line that prevents the opto from regularly seeing the "zero crossing" moment that your pulse counter relies on.

Transforming that line voltage to a much lower level decreases ambient line noise by the same transformer ratio, increases safety & makes it easier for the opto to detect the zero crossing in the presence of line noise etc. bc
> 2 votes

# Answer
> Based on my research, I believe the Arduino can reliably be powered by USB.

it can also be powered by the mains directly. ST wrote such an application note for its STM8 but the basic principle is the same. The beauty of this approach is that your zero cross detection can be done without the use of an optocoupler, directly through a gpio pin.

> How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?

depending on your board. crystals are usually specified to 20ppm but typically within 10ppm at room temperature. resonators, which some arduino uses, are 0.1 - 1%.

if you are n't too picky, even the internal oscillators will do -\> you can average the measurement over a long period of time to minimize jitter.

> I presume I'll need to debounce the result from the optocoupler?

generally no.

when you measure frequencies, you typically count the input signal. for low frequencies like the mains, you do the other way around: count the internal clock and use the input signal to gate its counting.

This allows frequency calculation down to quite a few decimal points: you should average approximately 8M counts per half cycle.

that's a lot of effective digits.
> 0 votes

---
Tags: arduino-nano, usb, digital, frequency
---


# Question
Title: Stability issue with webserver and smartmeter logging
In the past few months I have successfully logged the data from the power and gas meter in my house to a remote web server.

Now I try to add the ability to enable and disable my doorbell over the internet.

Although it seems to work, I experience 2 problems.

**Problems**

* Arduino freezes after a few hours
* When the meter reading is transmitted, the doorbell can not be switched.

**Questions**

> *Is there a way to give priority to control the doorbell?*

and ..

> *is there a way to find out why the Arduino freezes after a while?*

**Setup:**

* Arduino Mega 2560 board
* Ethernet shield
* LCD display
* Relay
* light sensor(for backlight control)
* serial connection to smart power/gas meter

```
//V1.1: Cleaned up messy code
#include <LiquidCrystal_I2C.h>
#include <Wire.h>  // Comes with Arduino IDE
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#include <AltSoftSerial.h>
#include <SPI.h>
#include <Ethernet.h>

//setup ethernet server
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //assign arduino mac address
byte ip[] = { 192, 168,  178, 95}; // ip in lan assigned to arduino
byte gateway[] = { 192,  168, 178,  1}; // internet access via router
byte subnet[] = {  255,  255,  255,  0}; //subnet mask
EthernetServer server(84); //server port arduino server will use
char thingSpeakAddress[] = "";
IPAddress myDns(8, 8, 8, 8);
EthernetClient client;
String writeAPIKey = "XXXMX2WYYR0EVZZZ";
String tsData = "hello"; //dummy data
String readString; //used by server to capture POST request
const int updateThingSpeakInterval = 20 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
unsigned long int updateCounter = 0; //set refresh counter to 0
//////////////////////
//slimme meter////////
/////////////////////
char c;
AltSoftSerial altSerial;
const int requestPin = 48; //data pin connected to smartmeter
char input; // incoming serial data (byte)
bool readnextLine = false;
#define BUFSIZE 75
char buffer[BUFSIZE]; //Buffer for serial data to find \n .
int bufpos = 0;
long mEVLT = 0; //Meter reading Electrics - consumption low tariff
long mEVHT = 0; //Meter reading Electrics - consumption low tariff
long mEAV = 0; //Meter reading Electrics - Actual consumption
long mG = 0; //Meter reading Gas
//unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

//const unsigned long postingInterval = 10 L * 1000 L; // delay between updates, in milliseconds, the "L" is needed to use long type numbers
/////////////////////////////////////////
//photcel////////controls lcd backlight//
////////////////////////////////////////
int photocellPin = 5; // the cell and 10K pulldown are connected to a0
int photocellReading; // the analog reading from the analog resistor divider
//boolean doorbell = true;

int creset = 43; //Telling arduino that you are connecting pin 43 with reset

//////////
//setup///
//////////
void setup() {
  Wire.begin();
  digitalWrite(22, LOW);
  digitalWrite(creset, HIGH);
  pinMode(creset, OUTPUT);
  pinMode(22, OUTPUT); //pin selected to control
  pinMode(6, OUTPUT); //pin selected to control
  pinMode(7, OUTPUT); //pin selected to control
  pinMode(8, OUTPUT); //pin selected to control
  //pinMode(5, OUTPUT); //pin 5 selected to control
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  server.begin();
  Serial.begin(9600);
  altSerial.begin(9600);
  Serial.println(F("Smarthome controller")); // keep track of what is loaded
  Serial.println(F("Send a g in serial monitor to test client")); // what to do to test client
  lcd.begin(20, 4); // initialize the lcd for 16 chars 2 lines, turn on backlight
  // sensorValue = analogRead(sensorPin);
  lcd.backlight(); // finish with backlight on
  //-------- Write characters on the display ------------------
  // NOTE: Cursor Position: Lines and Characters start at 0
  lcd.setCursor(0, 0); //Start at character 4 on line 0
  lcd.print("Smarthome controller");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("powerd by arduino");
  delay(1000);
  lcd.print("                  ");
  lcd.setCursor(0, 2);
  lcd.print("");
  lcd.setCursor(0, 3);
  delay(1000);
  lcd.print("Slimmemeter:     ");
  //lcd.backlight(); // turn on backlight.
  lcd.setCursor(0, 2);
  lcd.print("Doorbell: onn      ");
}
void loop() {
  if (updateCounter > 400) {
    digitalWrite(creset, LOW);  // Reset arduino
  }
  // Update ThingSpeak
  if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
    decodeTelegram();
  }
  // Check if Arduino Ethernet needs to be restarted
  if (failedCounter > 3) {
    startEthernet();
  }
  lastConnected = client.connected();
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char cl = client.read();
        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += cl;
          //Serial.print(c);
        }
        //if HTTP request has ended
        if (cl == '\n') {
          ///////////////
          Serial.print(readString); //print to serial monitor for debuging
          //now output HTML data header
          if (readString.indexOf('?') >= 0) { //don't send new page
            client.println("HTTP/1.1 204 Zoomkat");
            client.println();
            client.println();
          } else {
            client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
            client.println(F("Content-Type: text/html"));
            client.println();
            client.println(F("<HTML>"));
            client.println(F("<HEAD>"));
            client.println(F("<TITLE>Smarthome</TITLE>"));
            client.println(F("</HEAD>"));
            client.println(F("<BODY>"));
            client.println(F("<H1>Smarthome control page</H1>"));
            // DIY buttons
            client.println(F("Deurbel"));
            client.println(F("<a href=/?on2 target=inlineframe>ON</a>"));
            client.println(F("<a href=/?off3 target=inlineframe>OFF</a><br><br>"));

            client.println(F("Pins"));
            client.println(F(" <a href=/?off2468 target=inlineframe>ALL ON</a>"));
            client.println(F(" <a href=/?off3579 target=inlineframe>ALL OFF</a>"));
            client.println(F("<IFRAME name=inlineframe style='display:none'>"));
            client.println(F("</IFRAME>"));
            client.println(F("</BODY>"));
            client.println(F("</HTML>"));
          }
          delay(1);
          //stopping client
          client.stop();
          if (readString.indexOf("**secretcode**") > 0) //checks for secretkey
          {
            ///////////////////// control arduino pin
            if (readString.indexOf("on2") > 0) //checks for 2
            {
              digitalWrite(22, LOW); // set pin 5 high
              //Serial.println(F("Led 5 On"));
              //Serial.println();
              lcd.setCursor(0, 2);
              lcd.print("Doorbell: on      ");
              //doorbell = true;
            }
            if (readString.indexOf("off3") > 0) //checks for 3
            {
              digitalWrite(22, HIGH); // set pin 5 low
              //Serial.println(F("Led 5 Off"));
              //Serial.println();
              lcd.setCursor(0, 2);
              lcd.print("Doorbell: off      ");
              //doorbell = false;
            }

            //clearing string for next read
            readString = "";
          }
        }
      }
    }
  }

  //lcd.setCursor(0, 0); //Start at character 4 on line 0
  //lcd.print("SMARTHOME CONTROLLER;.");
  //String analogValue = String(analogRead(A5), DEC);
  photocellReading = analogRead(photocellPin);

  //lcd.setCursor(0, 1);
  //lcd.print(photocellReading);
  if (photocellReading < 800) {
    lcd.backlight(); // turn on backlight.
  } else {
    lcd.noBacklight(); // turn on backlight.
  }

}

////////////////////////////////////////////////////////////////////////////
//////////////////////////FUNCTIONS/////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void updateThingSpeak(String tsData)
//void sendGET() //client function to send and receive GET data from external server.
{
  //lcd.setCursor(0, 2);
  // lcd.print("                   ");
  lcd.setCursor(13, 3);
  lcd.print("verstur");
  // delay(1000);
  if (client.connect(thingSpeakAddress, 80)) {
    client.print("GET /smarthome/log.php?stroomLaag=");
    client.print(mEVLT);
    client.print("&stroomHoog=");
    client.print(mEVHT);
    client.print("&stroomVerbruik=");
    client.print(mEAV);
    client.print("&gasStand=");
    client.print(mG);
    client.println(" HTTP/1.1");
    client.println("Host: .nl");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    lastConnectionTime = millis();
    updateCounter++;
    Serial.print("Connecting to log server...");
    Serial.println(updateCounter);
    //x=x+1; //page upload counter
    // lcd.setCursor(0,3);
    // lcd.print("Data send           ");
    //delay(1000);
    lcd.setCursor(13, 3);
    //lcd.print("                    ");
    lcd.print("ok        ");
    lcd.setCursor(16, 3);
    lcd.print(updateCounter);
    if (client.connected()) {
      Serial.println("Connecting to suscesfull...");
      //Serial.println();
      failedCounter = 0;
    } else {
      failedCounter++;
      Serial.println("Connection to failed (" + String(failedCounter, DEC) + ")");
      Serial.println("connection failed");
      Serial.println();
      lcd.setCursor(13, 3);
      lcd.print("fout");
      lcd.setCursor(16, 3);
      lcd.print(String(failedCounter, DEC));
    }
  } else {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
    Serial.println();
    lastConnectionTime = millis();
  }
  while (client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char cl = client.read(); //gets byte from ethernet buffer
    //readString += c; //places captured byte in readString
    //Serial.print(c); //print raw data
  }
  client.stop(); //stop client
  readString = ""; //clear readString variable
}

////////////////////////////////////////////////////

void startEthernet() {
  client.stop();
  Serial.println("Connecting Arduino to network...");
  Serial.println();
  delay(1000);
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  } else {
    Ethernet.begin(mac, ip, gateway, gateway, subnet);
    server.begin();
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
  }
  delay(1000);
}

////////////////////////////////////////////////////

void decodeTelegram() {
  long tl = 0;
  long tld = 0;
  if (altSerial.available()) {
    //input = altSerial.read();
    c = altSerial.read();
    // --- 7 bits instelling ---
    c &= ~(1 << 7);
    char inChar = (char) c;
    //Serial.print(c);
    input = c;
    //Serial.println(input);
    //char inChar = (char)input;
    // Fill buffer up to and including a new line (\n)
    buffer[bufpos] = input & 127;
    bufpos++;
    if (input == '\n') { // We received a new line (data up to \n)
      if (sscanf(buffer, "1-0:1.8.1(%ld.%ld", & tl, & tld) == 2) {
        tl *= 1000;
        tl += tld;
        mEVLT = tl;
      }
      // 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
      if (sscanf(buffer, "1-0:1.8.2(%ld.%ld", & tl, & tld) == 2) {
        tl *= 1000;
        tl += tld;
        mEVHT = tl;
      }
      // 1-0:1.7.0 = Electricity consumption actual usage (DSMR v4.0)
      if (sscanf(buffer, "1-0:1.7.0(%ld.%ld", & tl, & tld) == 2) {
        mEAV = tl + tld;
      }
      // 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
      //if (strncmp(buffer, "0-1:24.2.0", strlen("0-1:24.2.1")) == 0) {
      if (sscanf(strrchr(buffer, '(') + 1, "%d.%d", & tl, & tld) == 2) {
        mG = (tl * 1000) + tld;
      }
      //}
      // Empty buffer again (whole array)
      for (int i = 0; i < 75; i++) {
        buffer[i] = 0;
      }
      bufpos = 0;
    }
    if (input == '!') { //uitroepteken geeft einde van telegram aan, dus we gaan data versturen
      // if (millis() - lastConnectionTime > postingInterval) {
      // httpRequest();
      updateThingSpeak("field1=0");
      // httpRequest();
      mEVLT = 0;
      mEVHT = 0;
      mEAV = 0;
      mG = 0;
      client.stop();
      //}
    } //Einde vraagteken detectie
    //Serial.print(c);
  } //Einde 'if AltSerial.available'
} //Einde 'decodeTelegram()' functie

```

# Answer
> 1 votes
Please see some comments that can help you.

Why do you use a software serial port?
This ATmega has 4 real serial ports!

`delay()` is dangerous in the main loop runtime. Try to use it only in setup.

Every time you call a task, be sure you will not stay there forever.
Get out of the task, if something seems to be too long time. Use `millis()` stamp time differences to measure time spent.
Print it if necessary on debug compiler option.
Printing on failure case do not spend MCU time if there are no errors.

# Answer
> 1 votes
```
buffer[bufpos] = input & 127;
bufpos++;

```

Never use a buffer without a length protection.
Flag if max buffer is reached, force to never write after last position.

Like this:

```
if ( bufpos > MaxBuff )
{
    Serial.print("errornumber");
    bufpos = MaxBuff;
    //And force \n to finish errored message
}

```

---
Tags: relay, web-server, logging
---


# Question
Title: What is causing this 'narrowing conversion' warning?
Because I'm still figuring out 'Arduino C' I leave all warnings on.

Recently I got this one:

`narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte...` etc.

...referring to this line:

```
const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

```

...pointing to the `or` symbol.

The code in question (much simplified to recreate this):

```
const int latch[2] = {2, 4};

const byte bx_0 = 1 << latch[0];
const byte bx_1 = 1 << latch[1];

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

```

(This happens whether I use `byte`, `uint8_t`, or `unsigned char` everywhere.)

Without the `or` operator, no warning. If `bx_0` and `bx_1` are simple bytes, not shifted into existence, no warning. If I do this:

```
const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

```

...again, no warning.

However, I get no complaints about this:

```
const byte notMask = !(bx_1 | bx_0);

```

...so a further condition is that the problem `or` has to be in an initializer list. Yikes.

I don't get it. There's no way an `or` of two bytes can force widening, so where did the `(int)` cast come from? It apparently has something to do with the `1 << latch[0]` code, but the result of that is still a byte, by definition.

I have a solution -- the `(byte)` cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.

# Answer
That warning message arises when a compiler complies with C/C++ specifications.

According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),

> Each of the operands shall have integer type

Thus, in the evaluation of `bx_0 | bx_1` within the statement `const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};`, the operands `bx_0` and `bx_1` are converted to `int` type before being OR'd together. This produces an `int` result, which then must be narrowed to `byte` before it can be stored in the `byte` array.

Knowing that the `(byte)` cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”. :)
> 1 votes

---
Tags: data-type, compiler, constants
---


# Question
Title: Arduino Uno - Multiple modules for HDMI switch device
I have an Arduino Uno device that uses the following modules:

* 16 PIN LED w/ Backlight
* RFID - RC522 (RFID Reader)
* HR911105A (LAN Module - HanRun)

These three modules use every digital pin available in the Uno (2-13) and it works correctly. The problem is that I want to add a relay to this board. I am new to Arduino so I use tutorials and right now I do not fully understand how this works. So I have connected the `IN` pin of the relay to Uno pin 8 and the `NO` pin of the relay to Uno pin 13.

The problem is that when I don't use other modules the relay works correctly (using this code).

```
int relay_pin = 8;
int led_pin = 13;

void setup() {
  pinMode(relay_pin,OUTPUT);
  pinMode(led_pin,OUTPUT);
  digitalWrite(led_pin,HIGH);
}

void loop() {
  digitalWrite(relay_pin,HIGH);
  delay(5000);
  digitalWrite(relay_pin,LOW);
  delay(5000);
}

```

The remaining ports are 1 and 0, which I assume are TX/RX, and can't be used for relay (am I wrong?).

So obviously I should not be using those pins but I wonder which pins I am allowed to use simultaneously when using two or three modules at the same time.

Does it depend on the modules or are there some instructions?

# Answer
The relay wiring diagram you are following is just plain bizarre and the strangest one I have ever seen.

Ignore it. It is completely incorrect.

You only need one pin to control a relay, so disconnect it from pin 13.

The switched side can connect to anywhere where you would normally use a switch - such as to switch power to an LED *connected between +5V and GND with a suitable current limiting resistor*.

You can use any available pin to control the relay, and that includes pins 0 or 1 *if you aren't using serial communication*. Note that with the relay connected to one of those pins it will most likely activate and buzz while you upload a sketch - best to disconnect it at that point and reconnect it afterwards.

---

Devices like relays and LEDs need their own dedicated pin. They can't be shared with other functions or each other.

The only devices that can share pins are devices which connect to a *bus*, such as SPI or I2C.
> 0 votes

---
Tags: arduino-uno, relay, port-mapping
---


title: Connecting a servo via HC05 and HC06

text:
# Question
Title: Connecting a servo via HC05 and HC06
I want to drive a servo via a HCO6 and HC05 link as a stand alone, using no android or PC. The question is how to send a 1.5 ms signal (generated with a pulse command on a Nano) from one HC to another HC (to which my servo will be connected) ? I do not need to care about passwords in my linking. No text to be sent, just the 1ms to 2 ms signal, at a refresh rate of 50 Hz. I will use the HC with a OOK modulation (on - off on the data pin)? How to achieve this ? Thanks !

# Answer
You cannot. You will need an Arduino at the servo end to generate the PWM signal from serial instructions sent over Bluetooth.

Since PWM is (typically) 8-bit and serial is (typically) 8-bit you could simply have each byte as a 1:1 mapping to a PWM value.

One the transmit end:

```
bluetoothSerial.write(pwmValue);

```

On the receive end:

```
if (bluetoothSerial.available()) {
    analogWrite(9, bluetoothSerial.read());
}

```
> 4 votes

---
Tags: arduino-nano, bluetooth, servo, hc-05, hc-06
---


title: PWM on Pin 4 - arduino Micro

text:
# Question
Title: PWM on Pin 4 - arduino Micro
I am using Arduino Micro. Is there any way to use PWM on pin 4 instead of Pin3 ?

I tried to change pins\_Arduino.h but didnt worked.

```
//#define digitalPinHasPWM(p)         ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

#define digitalPinHasPWM(p)         ((p) == 4 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

```

and

```
const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    ////////////////////////modified///////////////
    //TIMER0B,      /* 3 */
    //NOT_ON_TIMER,
    NOT_ON_TIMER,
    TIMER0B,        /* 4 */
    ////////////////////////////////////////////////////
    TIMER3A,        /* 5 */
    TIMER4D,        /* 6 */
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    TIMER1A,        /* 9 */
    TIMER1B,        /* 10 */
    TIMER0A,        /* 11 */

    NOT_ON_TIMER,
    TIMER4A,        /* 13 */

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
};

```

# Answer
> 1 votes
You cannot. There is no PWM on that pin. PWM is generated by hardware. The hardware simply does not exist.

---
Tags: pins, pwm, timers, arduino-micro
---


# Question
Title: Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor?
I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.

I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.

I'd like to start with a garden automation project, a fairly simple one. Humidity sensors, temperature sensors and a water pump.

Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?

I'm sorry if what I just said makes no sense and I thank you for your time. All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.

# Answer
If the connection is a digital sense pin then you can use a parallel-in serial-out IC to read them all simultaneously and then shift it in. Takes up 3 pins on the arduino a latch a clock and a data pin.

If the connection is SPI then you can connect the clocks and MISO pins together and then need a slave select for each. you can control many of them with a serial in parallel out IC or a decoder.

If the connection is with the I2C protocol and each device has a different address then you can simply connect them all in parallel.

If the sensor has an analog output then you can use an analog to digital converter (ADC) which can have multiple inputs and often have a serial interface.
> 4 votes

# Answer
It all depends on the interface between the Arduino and the sensor.

For example the DS18B20 uses the 1-Wire bus. That requires one digital pin and a number of DS18B20 can be connected to the same 1-Wire bus. Every DS18B20 has an unique identifier that makes that possible.

Humidity sensors like DHT11 or DHT22 require a pin for each sensors. They are not accurate anyway.

Sensors like the BME280 use the I2C bus. The I2C bus allows that many sensors can be connected. Each I2C sensor has an I2C address. Sometimes a sensor can have just one I2C address and therefor only one of such a sensor can be connected to the I2C bus. But sometimes a trick is possible to have more.

This list goes on and on and on. A lot is possible without extra hardware.

Because you are going to use sensors and many sensors are 3.3V, did you buy a 3.3V Arduino board ?
> 2 votes

# Answer
If you do not need them to run simultaneously, you can use a multiplexer such as this one from Sparkfun:

https://www.sparkfun.com/products/9056
> 1 votes

---
Tags: sensors, relay, networking
---


# Question
Title: Cannot create a PWM with 20% duty cycle using micro() timer
I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:

1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.

2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.

So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.

```
//MANUAL MODE TEST WITH MICROS()
//VARIABLES ASSIGNEMENT
unsigned long current=0.0;
unsigned long previous=0.0;

float TimeOn = 0.0;
float TimeOff = 0.0;
float manuelF = 0.0;
float sensor = 0.0;

int pin = 11;

byte state = LOW;

//SETUP AND PIN ASSIGNEMENT
void setup() {
  pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
  pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
  pinMode(A5, INPUT);//POTENTIOMETER MANUAL
  pinMode(A6, INPUT);//POTENTIOMETER MUSIC
  Serial.begin(9600);
}

void loop() {

  sensor = analogRead(A5);
  manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
  TimeOn=1000000.0*(0.2*(1.0/manuelF));
  TimeOff=1000000.0*(0.8*(1.0/manuelF));
  current = micros();

  Serial.println(TimeOn);

  //Serial.print("A5 read:");
  //Serial.println(analogRead(A5),8);
  //Serial.println("-----------");
  //Serial.print("Fréquence: ");
  //Serial.println(manuelF,8);
  //Serial.print("timeon:");
  //Serial.println(TimeOn,8);
  //Serial.print("timeoff:");
  //Serial.println(TimeOff,8);

  if ((state == LOW)&&(current - previous >= TimeOff)){
      state = HIGH;
      digitalWrite(pin,state);
      previous = current;
    }
  else{
    if (current - previous >= TimeOn){
      state = LOW;
      digitalWrite(pin,state);
      previous =current;
    }

  }
 }

```

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.

My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.

What is going on?

EDIT#1: I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

# Answer
> 0 votes
I have found the problem. Part of it was the code, thank you @Edgar Bonet. The other part was the pin I was using to generate the PWM signal. Throughout my reasearch, I found that on the arduino nano, the timer pins are the same than those on the arduino Uno. Thus:

Timer0 :pins 5-6

Timer1 :pins 9-10

Timer2 :pins 3-11

Since I was using the function micros() which uses the timer0, I had to send the signal to the right pin. I cannot describe why it did send a certain PWM to discrete frequencies, but the important is that it now works.

In parallel, because the other part of my program is using timer1, the two data transmission won't interfere with each other!

Time inversted in researches: 4hours

Hope this helps someone! Thanks.

# Answer
> 0 votes
You wrote:

```
if ((state == LOW)&&(current - previous >= TimeOff)){
    state = HIGH;
    digitalWrite(pin,state);
    previous = current;
  }
else{
  if (current - previous >= TimeOn){
    state = LOW;
    digitalWrite(pin,state);
    previous =current;
  }

```

While you probably mean:

```
if (state == LOW && current - previous >= TimeOff) {
    state = HIGH;
    digitalWrite(pin, state);
    previous = current;
}
else if (state == HIGH && current - previous >= TimeOn) {
    state = LOW;
    digitalWrite(pin, state);
    previous =current;
}

```

---
Tags: arduino-nano, timers, code-review
---


# Question
Title: Problem with Arduino Uno and SIM900 shield logical communication (rx & tx)
The logical communication(rx & tx) between the shield and Arduino Uno doesn't work. Arduino (rx & tx) supply is 0 & 5 V but this is 0 & 2.8 V. What am I to do?

# Answer
Use a logic level converter.

A logic level converter is a small device that converts between different logic levels, for example between 5V and 3.3V.

I am not affiliated with Sparkfun, I just think they are the most informative source.
> 0 votes

---
Tags: shields, gsm
---


# Question
Title: Ultrasonic distance module works without connecting to gnd
I have a (HCSR04) ultrasonic distance module connected to arduino , i have connected all the four pins of the module properly and its working fine , then when i pull off the wire which is connected to ground in arduino , the module works totally fine . How the module works without connecting its ground pin to arduino ground ?

# Answer
> 4 votes
It's not uncommon for part to "sort of" work when one of the supply rails is missing and an input signal of the some polarity somewhat substitutes for it, often through built-in ESD protection diodes. In this case, the trigger input when idle is low, and there's probably some capacitance on the board that could hold it through the brief trigger pulse.

It's a bad idea to rely on this though, both as it typically means stressing parts by operating them outside of specified limits, and can also produce not-quite reliable behavior.

For example, I once wired an SPI flash chip on a small carrier stuck underneath an MCU eval board, in order to test some software for a board I was designing. It worked great. Or I should say, it did right up until I tried to write to it, which would always fail. Eventually I discovered that I'd forgotten the ground connection when wiring it up. It was able to return enough current through the I/Os to perform read operations, but not to support a write.

---
Tags: arduino-uno, hc-sr04
---


# Question
Title: I can't upload sketches to my Arduino 101
When connected to USB green Power LED on but doesn't upload sketch(that says press master reset therefore i've pressed several time but timeout). And main thing is device doesn't show in device manager.(I'm working on windows10).

* Have I "bricked" it?
* What steps can I take to work out what is wrong?
* What can I do to fix it?

I've search in many sites but doesn't give me detail about hardware repairing guide for arduino 101.

I've checked working usb cable and another laptop but not work.I think **hardware problem**.Once arduino getting hot near usb.

# Answer
Simply replace it because it has a 1 year warranty outside the US.
> -1 votes

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

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

# Answer
If you checked all of the above as *Michel Keijzers* mentioned then it might be a hardware problem. Actually, your usb cable might not fitting correctly to the usb port.
> 0 votes

---
Tags: arduino-101
---


# Question
Title: Can't upload to Arduino Mini via Arduino USB 2 Serial Converter
I bought an Arduino Mini and also an Arduino USB 2 Serial Converter. While trying to program the Arduino Mini, I get this error:

```
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00

```

After doing some research I tried many things like changing the settings, serial port, made sure I'm using the right Arduino etcetera.

Some points to consider:

* I tried burning the bootloader using my Arduino Uno.
* Uploading sketches to the Arduino Mini using my Arduino Uno works (so problem is not directly with the Mini).
* I *am* pressing the Reset button before uploading. I also tried hooking a capacitor and the Reset wire directly. No change.

The wiring (I also tried connecting TX of Mini to RX of serial converter, and vice versa):

# Answer
The Arduino USB 2 Serial converter was defect (even though brand new). I bought a cheaper (7 Euro) FTDI to USB and I can now upload.
> 1 votes

---
Tags: serial, arduino-pro-mini, uploading, ftdi, arduino-mini
---


# Question
Title: How to use and retrieve data file from AT command in Arduino D1 Mini Wemos (With esp8266)
I stumbled upon an AT command for the ESP8266 that I really need. The following command is "AT+CWLAP", but I have no idea how to use it. I can't seem to find any resource on how to implement it.

I need the SSID, RSSI, and MAC addresses of the AP and pretty much use those data internally. For example (not necessarily doing this but you get the point), depending on the signal strength, choose the best option and print the SSID of the AP.

Is it even possible?

# Answer
> 1 votes
The command is documented in the ESP8266 AT Command Reference, with a non-PDF option at https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP

The response from the `AT+CWLAP` is a series of lines listing available access points, and for each, you are given their encryption method, SSID, RSSI, MAC, and the channel (or frequency offset and a calibration value).

It would be up to the you to parse the resulting strings to obtain the APs, sort by signal strength, and decide what to do with that information.

**EDIT:**

Because you are using the Arduino environment/core to write code for the ESP8266, you won't be able to use the AT command set. The AT Commands are available when the ESP8266 has the EspressIF firmware loaded to it, and thus the ESP8266 module is intended to be a peripheral device to some other controller; contrast with your use, where the ESP8266 is the **only** controller, with the WiFi ability baked in.

In this case, you will need to examine the features of the Arduino ESP8266 core, especially the ESP8266WiFi library, which gives an example sketch for scanning the available WiFi networks.

---
Tags: esp8266
---


title: How to calculate voltage from A0 pin

text:
# Question
Title: How to calculate voltage from A0 pin
I would like to calculate the amount of voltage from my A0 pin. I am using a 9v battery to power my load in my circuit. The formula to calculate voltage from the A0 pin is:

```
    sens = analogRead(A0);
    vol = sens * ( 5.0 / 1023.0);

```

If my power source is 9v, should i replace the 5.0 to 9.0?

# Answer
The analog input pins are 0V-5V strictly. If you need to measure a 9V input, you need to scale the voltage to test so that it is within a 0V-5V range. Often this is done with a voltage divider circuit.

In the example below, the 9V test voltage is divided in half, so the scale is 0V-4.5V, which is within range of the input pin.

Then your algorithm is

```
vol = sens * (2.0) * ( 5.0 / 1024.0);

```

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: arduino-uno, electronics
---


title: Arduino nokia 5110 lcd screen problem

text:
# Question
Title: Arduino nokia 5110 lcd screen problem
Hello I have a nokia 5110 lcd display connected to my Arduino. I have looked at so many tutorials and none of them work for me. I am trying to get a bitmap displayed in the screen but only the lights light up and nothing else happens. I have the lcd connected to the following Arduino pins:

* vcc -- 3.3v
* gnd -- gnd
* sce -- pin 7
* rst -- pin 6
* d/c -- pin 5
* DN -- pin 4
* sclk -- pin 8
* led -- 100ohm resistor --pin 11

here is an image

Nothing will display on the screen could someone please help me here is my code:

```
 #include "U8glib.h"
 #include "dht.h"

 #define dht_apin A1
 #define backlight_pin 11

 dht DHT;

 U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6

 const uint8_t brainy_bitmap[] PROGMEM = {
  0x00, 0x00, 0x03, 0xB0, 0x00, 0x00, 0x00, 0x00,
  0x07, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x46,
  0x00, 0x00, 0x00, 0x00, 0xFC, 0x47, 0xC0, 0x00,
  0x00, 0x01, 0xCE, 0x4C, 0x60, 0x00, 0x00, 0x03,
  0x02, 0x58, 0x30, 0x00, 0x00, 0x03, 0x02, 0x58,
  0x10, 0x00, 0x00, 0x02, 0x02, 0x58, 0x18, 0x00,
  0x00, 0x03, 0x06, 0x4C, 0x18, 0x00, 0x00, 0x07,
  0x04, 0x44, 0x18, 0x00, 0x00, 0x0D, 0x80, 0x40,
  0x3C, 0x00, 0x00, 0x09, 0xC0, 0x40, 0xE6, 0x00,
  0x00, 0x18, 0x78, 0x47, 0xC2, 0x00, 0x00, 0x18,
  0x0C, 0x4E, 0x02, 0x00, 0x00, 0x1F, 0x86, 0x4C,
  0x7E, 0x00, 0x00, 0x0E, 0xC6, 0xE8, 0xEE, 0x00,
  0x00, 0x18, 0x43, 0xF8, 0x82, 0x00, 0x00, 0x10,
  0x06, 0x4C, 0x03, 0x00, 0x00, 0x30, 0x0C, 0x46,
  0x01, 0x00, 0x00, 0x30, 0x18, 0x46, 0x01, 0x00,
  0x00, 0x10, 0x18, 0x43, 0x03, 0x00, 0x00, 0x18,
  0x10, 0x43, 0x03, 0x00, 0x00, 0x1C, 0x70, 0x41,
  0x86, 0x00, 0x00, 0x0F, 0xE0, 0x40, 0xFE, 0x00,
  0x00, 0x09, 0x1E, 0x4F, 0x06, 0x00, 0x00, 0x08,
  0x30, 0x43, 0x86, 0x00, 0x00, 0x0C, 0x20, 0x41,
  0x86, 0x00, 0x00, 0x06, 0x60, 0x40, 0x8C, 0x00,
  0x00, 0x07, 0x60, 0x40, 0xB8, 0x00, 0x00, 0x01,
  0xE0, 0x41, 0xF0, 0x00, 0x00, 0x00, 0x38, 0xE3,
  0x00, 0x00, 0x00, 0x00, 0x0F, 0xBE, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xCF,
  0x82, 0x0C, 0x86, 0x46, 0x1F, 0xEF, 0xC3, 0x0C,
  0xC6, 0xEE, 0x1C, 0xEC, 0xC7, 0x0C, 0xE6, 0x7C,
  0x1C, 0xED, 0x8D, 0x8C, 0xFE, 0x38, 0x1C, 0xED,
  0x8D, 0xCC, 0xDE, 0x38, 0x1D, 0xCD, 0xDF, 0xCC,
  0xCE, 0x38, 0x1F, 0x8C, 0xF8, 0xEC, 0xC6, 0x38,
  0x1F, 0xEC, 0x08, 0x0C, 0xC2, 0x18, 0x1C, 0xEC,
  0x00, 0xC0, 0x00, 0x00, 0x1C, 0xFD, 0xFB, 0xC0,
  0x00, 0x00, 0x1C, 0xFC, 0x63, 0x00, 0x00, 0x00,
  0x1C, 0xEC, 0x63, 0xC0, 0x00, 0x00, 0x1F, 0xEC,
  0x60, 0xC0, 0x00, 0x00, 0x1F, 0xCC, 0x63, 0xC0,
  0x00, 0x00, 0x1F, 0x0C, 0x63, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x28, 0x2B, 0x4F, 0x67,
  0x42, 0x38, 0x7B, 0xEA, 0x86, 0xB2, 0x28, 0xC7,
 };

 void draw(void) {
   u8g.drawBitmapP( 0, 0, 6, 50, brainy_bitmap);  // put bitmap
   u8g.drawStr(10, 10, "% ");

 void loop(void) {

   u8g.firstPage();
   do {
     draw();
   } while( u8g.nextPage() );

     delay(5000);  // Delay of 5sec before accessing DHT11 (min - 2sec)
   }

```

# Answer
> 2 votes
There are several possibilities.

Arduino GPIO pins drive outputs to ground or 5V.

The pins on the Nokia 5110 LCDs boards I have are not 5V tolerant. So you might have damaged them when the Arduino's GPIO connected to 5V.

A simple fix is to put a 10k ohm resistor in each signal path, i.e.

* sce -- pin 7
* rst -- pin 6
* d/c -- pin 5
* DN -- pin 4
* sclk -- pin 8

You could get a level-shift chip, or build a circuit, but resistors are quick, cheap and easy.

I would strongly recommend using a very simple Arduino library to get the display working. Then, once everything is working, continue with your current approach. All you need is a simple test; something which turns pixels on and off to check that it works.

I have had good results with the Arduino Playground Philips PCD8544 (Nokia 3310) driver

I have several Nokia 5110's. A few needed the values loaded at initialisation to be tweaked, to make the display visible.

Specifically in void LcdInitialise(void):

```
  LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
  LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
  LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
  LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
  LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
  LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.

```

I have had to tweak *Set Temp coefficent*, *LCD bias mode 1:48* and *Set LCD Vop (Contrast)* to get make the display clear, without looking washed-out, or all-dark. Using a very simple library like the Philips PCD8544 (Nokia 3310) driver should make it easy to adjust this until things work well.

# Answer
> 0 votes
Assuming you got your code from this site: https://brainy-bits.com/tutorials/how-to-use-the-nokia-5110/, it seems you edited the code from there to display only the bitmap, but you didn't get rid of everything. You have no DHT temperature sensors, so get rid of all DHT references in your code, including the 5 seconds delay at the bottom of `loop()`. If you intend to use the code from that site, then use it this way:

```
void draw(void) {
  u8g.drawBitmapP( 37, 0, 6, 50, brainy_bitmap);  // put bitmap
}

void setup(void) {
  analogWrite(backlight_pin, 50);  /* Set the Backlight intensity */
}

void loop(void) {
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

}

```

Make sure to get rid of the #define, #include and constructor referring to DHT.

# Answer
> 0 votes
Change your pinouts. HW SPI needs 13 and 11, not 8 and 4. Try this short bit of code: #

```
include <U8glib.h>

#define RST 6
#define CE  7
#define DC  5        //  D high is data, C low is command.
#define DIN 11
#define CLK 13
#define Backlight 9  // Don't forget the 330 ohm resistor.

//Declare the display and assign the pins.
  U8GLIB_PCD8544 u8g(13, 11, 7, 5, 6);  // CLK=13, DIN=11, CE=7, DC=5, RST=6

void draw() {
  u8g.setFont(u8g_font_profont11);      // Select font
  u8g.drawStr(0, 15, "Nokia 5110...");  // Put string of display at position X, Y.
  u8g.drawStr(29, 35, "HELLO!!!");
}

void setup() {
    analogWrite(Backlight, 80);  // Set Backlight Intensity, 0 is fully bright, 255 is off.
}

void loop() {                    // Enter the U8Glib Picture Loop
 u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}

```

---
Tags: lcd
---


title: Reduce PWM Frequency Arduino DUE

text:
# Question
Title: Reduce PWM Frequency Arduino DUE
I'm newbie in arduino due. I need to reduce the default PWM frequency of arduino Due. Anyone have any tutorial to do this? (Frequencys like 25hz, 50Hz for example)

I read in some posts, if i change the PWM frequency, i make changes in internal timers of arduino and i loss functions like delay(), millis(), etc.

Exits any form to not lose these functions?

Thanks a lot!

# Answer
> -1 votes
The Palatis Softpwm library can generate PWM on any digital pin with (almost) any frequency. Example for 25Hz:

```
#include <SoftPWM.h>
SOFTPWM_DEFINE_CHANNEL(0, DDRB, PORTB, PORTB2);  //Arduino pin 10
void setup() {
  // begin with 25Hz pwm frequency
  Palatis::SoftPWM.begin(25);
  Palatis::SoftPWM.set(0, value); // value is 0 to 255 just like normal Arduino analogWrite
}

```

---
Tags: arduino-due, pwm, timers
---


# Question
Title: ESP8266 send TCP HEX packet with 4 chars
I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.

My code:

```
#include <ESP8266WiFi.h>

const char* ssid     = "Wifi";
const char* password = "wifikey";

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
}

void setup() {
  Serial.begin(115200);
  WiFi.disconnect(true);
  delay(1000);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(ssid, password);
}

void loop() {
  delay(1000);
  const uint16_t port = 5577;
  const char * host = "192.168.178.150";
  WiFiClient client;
  client.connect(host, port);
  client.print(char(0x71));
  client.print(char(0x24));
  client.print(char(0x0f));
  client.print(char(0xa4));
  client.flush();
  client.stop();
  delay(5000);
}

```

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.

Thanks for your help.

# Answer
After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.

Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi%20LED%20control/):

```
/*
Send Commands to LED Controller via Wifi Network and Wemos D1 Board
*/
#include <ESP8266WiFi.h>

const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
const char* password = "***yourWifiPassword***"; //Change this value for your network
boolean connected = false;
boolean colorToggle = false;

void WiFiEvent(WiFiEvent_t event) {
    //Serial.printf("[WiFi-event] event: %d\n", event);

    switch(event) {
    case 3:
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        connected = true;
        break;
    case 6:
        Serial.println("WiFi lost connection");
        connected = false;
        break;
    }

    // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
    // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
    // 3 : WL_CONNECTED after successful connection is established
    // 4 : WL_CONNECT_FAILED if password is incorrect
    // 6 : WL_DISCONNECTED if module is not configured in station mode

}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    Serial.begin(115200);
    WiFi.disconnect(true);
    delay(1000);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

}

// the loop function runs over and over again forever
void loop() {
    //if we are connected
    if(connected){
      digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
      turnLEDSOn();
    }
    else
    {
      digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
      setup();
    }
}

void turnLEDSOn() {
    const uint16_t port = 5577;
    const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

     WiFiClient client;

     if (client.connect(host, port)) //Try to connect to TCP Server
     {
        Serial.println("Connected to LED Controller... ");
        if (colorToggle)
        { //Green
          char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = false;
          delay(5000);
        }
        else
        { //Blue
          char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = true;
          delay(5000);
        }

        Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
     }
     else
     {
        Serial.println("connection failed ... ");
     }

      if (client.available())
      {
        //Read from LED Controller
        char c = client.read();
        Serial.print(c);
      }

      if (!client.connected())
      {
        Serial.println();
        Serial.println("disconnecting ... ");
        client.stop();
        for(;;);
      }
}

```
> 1 votes

---
Tags: esp8266, wifi, tcpip
---


# Question
Title: Can I use my PC or Android mobile as WiFi Shield/Module for Arduino UNO?
I'm using an Arduino Uno. Currently I am using an ESP8266 WIFI module to connect to the Wifi. But is it possible to use my laptop or Android mobile as a WiFi Shield/Module? I want to connect with cloud server using the connection.

Thanks in advance.

# Answer
This problem can be broken into several components:

### Communications channel between the Arduino Uno and the laptop or Android mobile

There are several options. The most common and probably easiest is to do serial communication over USB. The Uno has a USB-serial chip that creates a virtual COM port (VCP) on a computer when you connect the Uno to it via the USB receptacle on the board. This VCP is commonly used to upload sketches to the Uno and also to communicate with the Arduino IDE's Serial Monitor.

Another option for communications between your Uno and the laptop or Android mobile is Bluetooth. You can buy a Bluetooth module for your Uno that will allow this. This may be preferable if you need wireless communication.

### Application on the Laptop or Android mobile that interprets communication with the Uno

Now you can communicate between the two devices but you need a program running on the Laptop or Android mobile to actually do something with the communication. This application will receive commands from the Uno, and make the desired interactions with the "cloud server", and perhaps respond to the Uno. You will need to have some sort of a command protocol. The details of this will be dependent on which type of communications channel you chose. There are many ways you can accomplish this and the best option will also depend on whether you will be writing this application yourself or trying to find an existing application that suits your needs.

### Arduino Uno firmware

This is a sketch you will write and upload to your Uno that sends commands to the laptop or Android mobile via your chosen communications channel and handles any responses.
> 1 votes

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


title: Reload only one variable in loop()

text:
# Question
Title: Reload only one variable in loop()
I need some information for the TFT screen 2.8 and arduino mega. The screen works very well and displays the data. The small problem I encounter is for the text display, the page is reloading every second and this makes a small black screen every second. I would like to know if it was possible to reload only one part of the screen display?

See in video https://youtu.be/vxSa6xkH0vU

My `loop()`

```
void loop(void) {
   tft.fillScreen(BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setRotation(3);
  dt = clock.getDateTime();
  clock.forceConversion();

  // Go
  tft.println();
  tft.setTextColor(GREEN);
  tft.setTextSize(5);
  tft.println("Info");
  tft.println();
  tft.setTextSize(2);
  tft.println(clock.dateFormat("d-m-Y H:i:s", dt));
  tft.println();
  tft.setTextSize(2);
  tft.println("Temperature: ");
  tft.println(clock.readTemperature());

  delay(1000);
}

```

# Answer
> 1 votes
You can use `tft.rect(x,y,width,height)` to clear only a portion of the screen. Make sure to set `tft.fill` before calling it.

---
Tags: lcd
---


# Question
Title: Reading/Writing Strings with Bluetooth Windows API
I am trying to use my HC05 so my Arduino can communicate with my Windows 10 PC. I have a program written using the Window API for Serial Communication but the problem is it looks like the Arduino/HC05 can only send or the API can only read one character at a time. It is the same with Arduino; I send an entire string with the API and the Arduino has to read/parse it character by character. I was wondering if there was a solution to this problem or if I will need to develop some sort of coding protocol (like space to separate messages) to send messages. (The other issue is that it will take an age to send long messages this way.)

Windows File Reading API https://msdn.microsoft.com/en-us/library/windows/desktop/aa364232(v=vs.85).aspx

Here is the PC side file.

```
do {
    // check for data on port and display it on screen.
    ReadFile(file, buffer, sizeof(buffer), &read, NULL);
    int i;
    sscanf(buffer, "%d", &i);
    std::cout << i << std::endl;

    if (read) {
        //WriteFile(screen, buffer, read, &written, NULL);

        //When space seen, add the string to data
        if (buffer[0] == ' ') {
            int convertedDatum = std::stoi(datum, &sz);
            if (convertedDatum < 12) {
                //WriteFile(file, "S " , 2, &written, NULL);
                //WriteFile(screen, "S", read, &written, NULL);
            }
            else {
                //WriteFile(file, "G ", 2, &written, NULL);
                //WriteFile(screen, "G", read, &written, NULL);
            }
            data.push_back(convertedDatum);
            datum = "";

```

Arduino-side test code

```
void loop() {

while (true) {
    String sendValue = String(100);
    sendValue.toCharArray(buf, sizeof(buf));

    Serial1.write(buf);
    Serial1.write(' ');
    delay(4000);
}

```

What I am seeing on the console on the PC which is represented by the **screen** variable when I debug is when I break at the line

```
std::cout << i << std::endl;

```

1-Continue-0-Continue-0 or on the console

```
1
0
0
0
0
0
...

```

I am pretty sure that I have seen entire strings sent at once with the Android Bluetooth API so I am not sure exactly if the same can be done with Windows or if the Windows VC++ API's are incapable.

# Answer
Serial is only ever a character at a time. That is what serial is. If you want to impose some structure on top of that then it is up to you to define that structure.
> 1 votes

---
Tags: arduino-mega, c++, bluetooth, hc-05
---


# Question
Title: Home devices control system using gsm and arduino mega2560
Hi dears I'm trying to do project to control app base gsm control by arduino mega 2560 gsm module SIM900A

To send SMS to open Led than reply SMS to give as the status I mean send SMS then I received SMS from GSM module by this code same time work but same time not work also same time send SMS1111 received SMS2222 status. I hope it is clear.

```
#include <SoftwareSerial.h>
#include <string.h>
#include "SIM900.h"
#include <TinyGPS.h>
#include "sms.h"
SoftwareSerial GSMSerial(12, 13);
byte buffer[128];
int count = 0;
const int Led4 = 43;
const int Led1 = 44;
const int Led2 = 45;
const int Led3 = 50;
void SIM900power()
{
}
void setup() {
    pinMode(Led1, OUTPUT);
  pinMode(Led2, OUTPUT);
  pinMode(Led3, OUTPUT);
  pinMode(Led4, OUTPUT);
  GSMSerial.begin(19200); // the SIM900 baud rate
  Serial.begin(9600); // the Serial port of Arduino baud rate.
  Sim900_Inti();
}
void loop() {
  GSMSerial.listen();
  if (GSMSerial.available()) // If date is comming from from GSM shield)
  {
    while (GSMSerial.available()) // reading data into char array
    {
      buffer[count++] = GSMSerial.read(); // writing data into array
      if (count == 128)break;
    }
    Serial.write(buffer, count); // if no data transmission ends, write         buffer to hardware serial port
Cmd_Read_Act(); //Read the 'COMMAND' sent to SIM900 through SMS
clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
count = 0; // set counter of while loop to zero
  }
  if (Serial.available()) // if data is available on hardwareserial port ==>     data is comming from PC or notebook
    GSMSerial.println(Serial.read()); // write it to the GPRS shield
}
void clearBufferArray() // function to clear buffer array
{
  delay(1000);
  for (int i = 0; i < count; i++)
  {
    buffer[i] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int n = 0; n < count; n++)
  {
    buffer[n] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int m = 0; m < count; m++)
  {
    buffer[m] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int p = 0; p < count; p++)
  {
    buffer[p] = NULL; // clear all index of array with command NULL
    delay(100);
  }
}
void Sim900_Inti(void)
    {
     GSMSerial.println("AT+CMGF=1"); // Set GSM shield to sms mode
  Serial.println("AT+CMGF=1");
  delay(500);
  GSMSerial.println("AT+CNMI=2,2");
  Serial.println("AT CMGF=1");
  delay(500);
}
void Cmd_Read_Act(void) //Function reads the SMS sent to SIM900 shield.
{
  char buffer_i[128];
  for (int i = 0; i < count; i++)
  {
    buffer_i[i] = char(buffer[i]);
  }
  if (strstr(buffer_i, "1111")) //Comparing password entered with password     stored in program
  {
          digitalWrite(Led1, HIGH);
   SMS_1111();
  }
  char buffer_n[128];
  for (int n = 0; n < count; n++)
  {
    buffer_n[n] = char(buffer[n]);
  }

  if (strstr(buffer_n, "2222")) //Comparing password entered with password     stored in program
  {
          digitalWrite(Led2, HIGH);
   SMS_2222();
  }
      char buffer_m[128];
  for (int m = 0; m < count; m++)
  {
    buffer[m] = char(buffer[m]);
  }
  if (strstr(buffer_m, "3333")) //Comparing password entered with password     stored in program
  {
   digitalWrite(Led3, HIGH);
   SMS_3333();
  }
  char buffer_p[128];
  for (int p = 0; p < count; p++)
  {
    buffer[p] = char(buffer[p]);
  }
  if (strstr(buffer_p, "4444")) //Comparing password entered with password stored in program
      {
    digitalWrite(Led4, HIGH);

   SMS_4444();
  }
}
  void SMS_1111() // complet liter Replay SMS TO Know Led1 Is ON
 {
 }
 void SMS_2222()// complet liter
{
}
void SMS_3333()// complet liter
{
}
void SMS_4444()// complet liter
{
}>

```

# Answer
For the `3333` and `4444` you are doing

```
buffer[m] = char(buffer[m]);

```

and

```
buffer[p] = char(buffer[p]);

```

which does nothing.

You probably meant

```
buffer_m[m] = char(buffer[m]);

```

and

```
buffer_p[p] = char(buffer[p]);

```
> 1 votes

---
Tags: programming, gsm
---


title: How to dynamically allocate arrays

text:
# Question
Title: How to dynamically allocate arrays
Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:

```
int* test = 0;

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

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(" " + answer);
  Serial.print(" " + test[0]);
  Serial.println(" " + test[1]);
  Serial.println("test");
  delay(100000000000);
}

```

All of my attempts result in either some garbage in the serial or in most cases:

```
test

test

```

Does anyone know what I'm doing wrong?

# Answer
> 1 votes
`serial.println` doesn't work that way. Or more precisely `+` with string literal and an `int` does **not** create a concatenated string. Instead it treats the string literal as a `char*` and then does pointer arithmetic on it.

```
  Serial.print(" ");
  Serial.println(answer);
  Serial.print(" ");
  Serial.print(test[0]);
  Serial.print(" ");
  Serial.println(test[1]);
  Serial.println("test");
  delay(100000000000);

```

# Answer
> 2 votes
This works:

```
int* test = 0;

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

void loop() {
  Serial.println("test");
  if(test != 0){ //c++ delete and new attempt
    delete [] test;
  }
  test = new int[2];
  //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
  //test = (int*) malloc(2*sizeof(int));          //malloc attempt
  test[0] = 1;
  test[1] = 2;
  int answer = test[0] + test[1];
  Serial.println(answer);
  Serial.print(test[0]);
  Serial.println(test[1]);
  Serial.println("test");
  delay(100000000000);
}

```

In C/C++, you can't add/concatenate Strings and int.

---
Tags: arduino-nano, array, arduino-pro-micro, memory
---


# Question
Title: Can we use Arduino mini in eagle to create new custom modal
I want to learn pcb design in Eagle/Fritzing. So i was thinking of using existing amazing Arduino mini/nano in eagle and create a custom pcb which has all arduino capability and plus some components like 7 segment/Bluetooth radio etc.

Can we do that? Is is allowed or arduino design is not open to be modified?

# Answer
> 1 votes
From https://www.arduino.cc/en/Main/FAQ#toc8:

> I want to design my own board, what should I do?
>
> The reference designs for the Arduino boards are available from their specific product pages. They're licensed under a Creative Commons Attribution Share-Alike license, so you are free to use and adapt them for your own needs without asking permission or paying a fee.

You can find the board design files on the **Documentation** tab of each product page.

Arduino Mini product page:
https://store.arduino.cc/arduino-mini-05

Arduino Nano product page:
https://store.arduino.cc/arduino-nano

# Answer
> 0 votes
Arduino is open-source hardware. The Arduino website has schematics and board layout files.

---
Tags: arduino-nano, arduino-mini, pcb-design
---


# Question
Title: using UART bridge module to have serial communication through usb port of arduino nano
This can be a silly question but I'm having a trouble with serial communication between arduino nano with other serial device. Please help me to handle it.

I'm currently doing a RF communication project using arduino nano and radio telemetry which is using serial communication. I tried to use SoftwareSerial but unfortunately, every pin is being used on arduino nano to control other extra devices. So I decided to have serial communication via usb port of arduino nano

Firstly, I directly connected rx and tx wire of RF device with D- and D+ of B type mini USB. but it did not work

Secondly, I tried to connect rx and tx wire with arduino nano via UART to USB bridge, cp2102 module. I soldered a female USB - male mini USB wire for this connection. but It did not work. the wiring that I build seems like the picture below.

Did I miss something? It doesn't work theoretically anyway?
Please help
Thank you in advance

# Answer
> 1 votes
This is not possible - USB is not an ambidextrous protocol, rather there are distinct Host and Device roles, and while a few chips can switch-hit between them, the USB interface chips commonly used on Nano-style boards are strictly device only, and therefore cannot communicate with another USB device such as a USB-serial adapter. There may well even be a duplicate here somewhere of a similar question having been asked before.

What you should probably do is just use the ATmega UART that interfaces to the USB chip, to talk to your external device directly (or through level translation and possibly inversion if it requires that). The transmit side is no problem, however you will need to give some though to the receive side, as only one thing (the USB chip, or your external device) can drive that ATmega pin at a time. Many of the official Arduino designs have a resistor there, which lets an external driver dominate over the on-board USB serial chip, but your board may or may not have that - if not, you may need to modify it.

And of course such a scheme requires that you disconnect the external device when uploading a new sketch via bootloader.

Another option would be instead of a traditional USB-serial converter, to use some sort of embedded USB host and have that convert to serial - the Kinetis KL25Z chip does this well, as does its close cousin on the Teensy-LC. But at that point, you might as well just replace the Arduino Nano with a better chip having more pins, or even the ATmega328PB which has a second hardware UART.

---
Tags: serial, arduino-nano, communication, uart
---


# Question
Title: Unsigned long overflow? Or something else?
I have been looking at this for hours and can't figure it out... Take the following code I ran on an Arduino Mega:

```
#define MINUTES 0
#define SECONDS 1
#define MILLIS  2
#define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

unsigned long calculate_ms(int , int , int );

int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("Values of selected_turn_delay:");
  Serial.print("minutes: ");
  Serial.println(selected_turn_delay[MINUTES]);
  Serial.print("seconds: ");
  Serial.println(selected_turn_delay[SECONDS]);
  Serial.print("milliseconds: ");
  Serial.println(selected_turn_delay[MILLIS]);

  unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result2 = calculate_ms(0,45,0);
  unsigned long result3 = calculate_ms(0,30,0);
  unsigned long result4 = calculate_ms(0,31,0);
  unsigned long result5 = calculate_ms(0,32,0);
  unsigned long result6 = calculate_ms(0,33,0);
  unsigned long result7 = calculate_ms(0,34,0);
}

void loop() {
}

unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
  Serial.println("------------");
  Serial.println("In calculate_ms");
  Serial.println("------------");
  unsigned long calculated_total_milliseconds = 0;
  unsigned long minute_to_seconds = 0;
  unsigned long seconds_to_ms = 0;

  Serial.println("Input:");
  Serial.print("minutes: ");
  Serial.println(minutes);
  Serial.print("seconds: ");
  Serial.println(seconds);
  Serial.print("milliseconds: ");
  Serial.println(milliseconds);

  calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

  Serial.print("Calculates ms:");
  Serial.println(calculated_total_milliseconds);
  return(calculated_total_milliseconds);
}

```

It gives me the following results:

```
Values of selected_turn_delay:
minutes: 0
seconds: 45
milliseconds: 0
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:4294946760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:4294946760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:4294946760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 30
milliseconds: 0
Calculates ms:30000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 31
milliseconds: 0
Calculates ms:31000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 32
milliseconds: 0
Calculates ms:32000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 33
milliseconds: 0
Calculates ms:4294934760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 34
milliseconds: 0
Calculates ms:4294935760

```

What am I missing why is the calculation for values above 32s out of wack ?

Tried the same code adapted for gcc:

```
#include <stdio.h>

#define MINUTES 0
#define SECONDS 1
#define MILLIS  2
#define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

unsigned long calculate_ms(int , int , int );

int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

int main(void) {
  printf("Values of selected_turn_delay:\n");
  printf("minutes: ");
  printf("%d\n",selected_turn_delay[MINUTES]);
  printf("seconds: ");
  printf("%d\n",selected_turn_delay[SECONDS]);
  printf("milliseconds: ");
  printf("%d\n",selected_turn_delay[MILLIS]);

  unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result2 = calculate_ms(0,45,0);
  unsigned long result3 = calculate_ms(0,30,0);
  unsigned long result4 = calculate_ms(0,31,0);
  unsigned long result5 = calculate_ms(0,32,0);
  unsigned long result6 = calculate_ms(0,33,0);
  unsigned long result7 = calculate_ms(0,34,0);
}

unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
  printf("------------\n");
  printf("In calculate_ms\n");
  printf("------------\n");
  unsigned long calculated_total_milliseconds = 0;
  unsigned long minute_to_seconds = 0;
  unsigned long seconds_to_ms = 0;

  printf("Input:\n");
  printf("minutes: ");
  printf("%d\n",minutes);
  printf("seconds: ");
  printf("%d\n",seconds);
  printf("milliseconds: ");
  printf("%d\n",milliseconds);

  calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

  printf("Calculates ms:");
  printf("%lu\n",calculated_total_milliseconds);
  return(calculated_total_milliseconds);
}

```

And it works great:

```
Values of selected_turn_delay:
minutes: 0
seconds: 45
milliseconds: 0
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 30
milliseconds: 0
Calculates ms:30000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 31
milliseconds: 0
Calculates ms:31000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 32
milliseconds: 0
Calculates ms:32000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 33
milliseconds: 0
Calculates ms:33000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 34
milliseconds: 0
Calculates ms:34000

```

It has to be something obvious, but I can't find it...

# Answer
Ok well, 'before bed illumination'...

Changing:

```
calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

```

for

```
calculated_total_milliseconds = (milliseconds + (seconds * 1000UL) + ((minutes * 60) * 1000UL));

```

Make it work:

```
Values of selected_turn_delay:
minutes: 0
seconds: 45
milliseconds: 0
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 30
milliseconds: 0
Calculates ms:30000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 31
milliseconds: 0
Calculates ms:31000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 32
milliseconds: 0
Calculates ms:32000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 33
milliseconds: 0
Calculates ms:33000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 34
milliseconds: 0
Calculates ms:34000

```
> 1 votes

---
Tags: calculation
---


# Question
Title: ESP8266 Wemos D1 Retrieving Wrong AP Mac Address
Using `WiFi.BSSID` and `WiFi.BSSIDstr` gives me some weird mac address.

the code is:

```
#include "ESP8266WiFi.h"
#include "ESP8266WiFiScan.h"

void setup() {
Serial.begin(115200);
//WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
Serial.println(WiFi.macAddress());
}

void loop() {
   int n=WiFi.scanNetworks();
   Serial.println(n);
   for (int network = 0; network < n; network++){
      Serial.println(WiFi.SSID(network));
      Serial.println(WiFi.RSSI(network));
      uint8_t* mac=WiFi.BSSID(n);
      char APmac[13];
      APmac[0]=0;
      for (int i=0; i<6;i++) {
        char buffer[3];
        sprintf(buffer, "%02x", mac[i]);
        strncpy((char *)(APmac+(i*2)), buffer, 3);
        Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
      }
      Serial.println(APmac);
      Serial.println(WiFi.BSSIDstr(n));

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

```

The current output is 6D:98:C9:00:00:00 which is completely off. It duplicates this output for other APs too. Is this a hardware problem? I've seen other people using the same codes and it works for them. For reference `WiFi.SSID();` and `WiFi.RSSI();` both spits out correctly.

edit: I was testing both output to see which ever one was correct and unfortunately they're both wrong

# Answer
This seems wrong, you are trying to get String to interpret a byte, but are passing in a pointer to a byte:

```
String digit = String(*mac, HEX);

```

Try changing your example to:

```
uint8_t* mac=WiFi.BSSID();              // Gather the byte array
String APmac;
for (int i=0; i<6;i++) {
   String digit = String(mac[i], HEX);  // String() should see an int, not a pointer to a byte, with the directive to print it in HEX format
   if (digit.length() <2)
     APmac += String("0")+digit;        // Corrected capitalization error
   else
     APmac +=digit;                     // Corrected capitalization error
   //mac++;                             // Not necessary
   Serial.print("["); Serial.print(i); Serial.print("]");
   Serial.println(mac[i], HEX);
}
Serial.println(APmac);                  // Print the constructed String
Serial.println(WiFi.BSSIDstr());        // Print the pre-formatted string

```

Consider not using the String object, which may help condense the code a bit:

```
uint8_t* mac=WiFi.BSSID();
char APmac[13];
APmac[0]=0;
for (int i=0; i<6;i++) {
   char buffer[3];
   sprintf(buffer, "%02x", mac[i]);
   strncpy((char *)(APmac+(i*2)), buffer, 3);
   Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
}
Serial.println(APmac);
Serial.println(WiFi.BSSIDstr());

```
> 0 votes

---
Tags: esp8266, hardware
---


# Question
Title: fatal error: ESP8266WiFi.h: No such file or directory
I used platformio IDE

I did "platformio lib install 1101" (http://platformio.org/lib/show/1101/ESP8266wifi),

I installed this: http://platformio.org/lib/show/549/WebSockets (follow instructions)

I did similar things to other libraries.

When I click the platformio:build button, it still complains:

> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
> ESP8266Webserver.h: No such file or directory

# Answer
Have you overridden `lib_dir` in `platformio.ini`? If yes, please remove it.
> 1 votes

# Answer
While Bhushan Patil's answer should work, it would still make future projects tedious. Instead you can add the header files to the hardware library, and use them at will, with the `#include <library>` syntax every other library uses in C/C++.

The PlatformIO IDE has a config file you can modify that tells the IDE where to look for libraries. You could read this file, and determine where to put your header files, such that PlatformIO could find them, or add a location to look for header files in. See this page from the PlatformIO documentation:
http://docs.platformio.org/en/latest/projectconf.html

Beyond that, you could also use the absolute path for the header file (library) you are trying to use, by doing something like

```
#include "/home/user/path/to/user/library.h"

```
> 1 votes

# Answer
Make sure **ESP8266WiFi.h**, **ESP8266WiFiMulti.h**, **ESP8266Webserver.h** files are located in the same directory where your \*.uno file present.
> 0 votes

# Answer
Note the different capitalization: ESP8266**w**i**f**i vs ESP8266**W**i**F**i. Confusing as it may be, these are actually two completely different libraries.

ekstrand/ESP8266wifi is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.

ESP8266WiFi is a library bundled with the ESP8266 core for Arduino. It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.

The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware.
> -1 votes

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


# Question
Title: Error in sending AT commands in esp8266 connecting to arduino IDE
I am working on esp8266 with Arduino.

I have connected pins like arduino-esp 3.3-vcc gnd-gnd 3.3-CH\_PD RX-TX TX-RX and reset to gnd using 3k resistor.

I couldn't send AT commands in serial monitor in Arduino IDE.

Later I connected a capacitor between Vcc and Gnd. Now I could send AT commands and I am getting same commands back. Whatever I entered, I am getting the same back.

I didn't get reply as OK. And I got some random characters too. Can anyone help me with this?

# Answer
Looks like your connection is somewhere missing.

Connect CH\_PD and reset pin to high--i.e. 3.3v.
> 1 votes

# Answer
I made the following connection with Arduino Mega 2560 and AT commands was working perfectly well.

**Connection:**

ESP8266 - Arduino Mega 2560

Vcc, CH\_PD, RST - 3.3V pin

GND - GND

Rx - Tx(18)

Tx - Rx(19)

**Program:**

```
void setup() {
  Serial.begin(115200);   // USB serial port of Due (PROGRAMMING)
  Serial1.begin(115200);  // ESP8266 on Serial Port 1 of Due (UART 1)
}

char rx_byte = 0;

void loop() {
  // send terminal byte to ESP8266
  if (Serial.available() > 0) {
    rx_byte = Serial.read();
    Serial1.print(rx_byte);
  }
  // send ESP8266 byte to terminal
  if (Serial1.available() > 0) {
    rx_byte = Serial1.read();
    Serial.print(rx_byte);
  }
}

```

Select Tools\>Board\> Arduino/Genuino Mega or Mega 2560. Upload the code. In serial monitor, select 115200 baud rate and Both NL & CR option. Enter the AT command and it works!
> 1 votes

---
Tags: esp8266
---


title: Set board manager as ATmega16

text:
# Question
Title: Set board manager as ATmega16
I tried to download the ATmega16 board in my Arduino. I have set below URL under File-\>Preference-\>Additional board manager URL

`https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json`

I am getting below attach images. How can we resolve this error and install atmega16 board manager?

I am using Arduino version 1.6.9. I don't have any issue in opening MightyCare and Arudino URL from my chrome browser.

# Answer
> 2 votes
Thanks for everyone help here.

I have resolved by few steps.

1) File -\> preference -\> Board manager URL as like below. Basically URL are seperated by commas. `http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json`

2) Deleted the tmp file (package\_index.json.tmp) which is in the path `C:\Users\SIMBU\AppData\Local\Arduino15\`

This helped me to resolve the issue.

---
Tags: arduino-ide
---