title: Generated frequency is not as expected

text:
# Question
Title: Generated frequency is not as expected
This code sets a pin HIGH for 1 microsecond and then LOW for 1 microsecond. The expected frequency should be about 500 kHz. When measuring the output the frequency is about 96.4khz. Why ?

```
int del = 1;

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

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

digitalWrite(3, HIGH);
delayMicroseconds(del);
digitalWrite(3, LOW);
delayMicroseconds(del);

}

```

# Answer
`digitalWrite()` takes a few microseconds to execute as well. There is also some overhead around the `delayMicroseconds()` function.

If you need exactly 500 kHz, you would want to consider using a timer. You can read up on how to set one up in the microcontrollers datasheet.

Unfortunately, I don't have access to an Arduino Leonardo, but here is an example code for the ATmega328P. The register names will be different, but you should be able to adapt the code to fit your Arduino.

```
// 500 kHz frequency

void setup() {
  cli();                 //Disable interrupt during setup
  TCCR2A = 0;
  TCCR2B = 0;

  TCCR2B |= (1 << CS20); //Enable timer without prescaler
  OCR2A = 15;            //Do interrupt TIMER2_COMPA after reaching this counter value
  TIMSK2 |= (1 << 1);    //Enable TIMER2_COMPA interrupt

  DDRD |= (1 << PORTD3); //Set Digital Pin 3 as Output Pin
  sei();                 //Enable interrupts again
}

ISR(TIMER2_COMPA_vect) { //If the counter has reached the point where the output needs to be low
  TCNT2 = 0;
  PIND |= (1 << PORTD3); //Toggle Digital Pin 3
}

void loop() {
  //your looping code here
}

```

Explanation: `TIMER2` is an 8-bit timer, which means it will always count from 0 to 255, regardless of what the CPU is doing.

Normally, it counts up at the Arduino's clock frequency, like 16 MHz.

When the counter hits 15, a special code is immediately executed, called an "Interrupt Service Routine". In this code, we reset the timer and change the state of your output pin, resulting in a 500 kHz square wave on that pin.

We count to 15 since there are 16 steps in between "0" where the counter begins and 15, where we reset it.

16'000'000 Hz / 1 (no prescaler) / 16 (counter) / 2 = 500 kHz

The divisor of 2 comes from the fact that we need to change the pin state twice for every full square of the output signal.
> 5 votes

# Answer
delayMicroseconds() has a minimum lower value of 3-4 us per the IDE documentation. It won't do 1.

loop() also adds some delay mechanisms doing it's background stuff.

You will see better results with a while() :

```
loop(){
  while (1){
  digitalWrite(3, HIGH);
  delayMicroseconds(del);
  digitalWrite(3, LOW);
  delayMicroseconds(del);
  }
}

```

with direct port manipulation in place of the digital writes.

There will also be jitter from the millis() background time keeping, if you want a smoother signal it will be best to turn off interrupts as well.
> 0 votes

---
Tags: arduino-leonardo, frequency
---


# Question
Title: I can send on software serial, but not read?
I've been cracking my head over this for a long while.

Like many before me, I'm trying to send and receive data from a HM-10 bluetooth module, arduino mega adk and the app called BLE Scanner. I've figured out receiving alright. Whatever I write into the serial monitor, shows up on the app. Whatever I write into the software serial, shows up. However, I haven't figured out how to read from the software serial. The available function never gets triggered, and always printing out the software serial read is always -1

The app supports sending data over bluetooth as well. However, using:

```
    #include <SoftwareSerial.h>
SoftwareSerial blueSerial(14, 15); //RX, TX
  blueSerial.begin(9600);
  Serial.begin(9600);
while (1)
  {
    blueSerial.listen();
    if (Serial.available()) {
      Serial.println("Writing");
      blueSerial.write(Serial.read());
      Serial.println(Serial.read());
      Serial.println(blueSerial.available());
    }
    if (blueSerial.available()) {
      Serial.println("Blueserial writing");
      Serial.write(blueSerial.read());
    }
}

```

The listen function is used out of pure desperation.

How do I fix this? This should be working right? Since I want to be sending AT commands to the bluetooth modules at some time and read their output, getting this to work is really important.

# Answer
Possibly the built-in UART (Hardware Serial) assigned to the same pins is interfering with SoftwareSerial? If you really want to us SoftwareSerial, try it on a pair of pins that has no hardware UART attached.

And/or try SoftwareSerial (again, on a non-UART pair of pins) to connect to your PC (after uploading; you can't upload with it), and use Serial1 to connect to your device. This isn't the recommended or easiest way but it might help debug the problems you're seeing.
> 1 votes

# Answer
On Mega you don't need to use SoftwareSerial. Mega has 4 Serials. Connect the module to RX3/TX3 like on the Fritzing in your question and use Serial3 in sketch.

```
void setup() {
  Serial.begin(9600);
  Serial3.begin(8600);
}

void loop() {

  while (Serial.available()) {
    Serial3.write(Serial.read());
  }
  while (Serial3.available()) {
    Serial.write(Serial3.read());
  }
}

```
> 1 votes

# Answer
If SoftwareSerial is not working then simply do not use it.

You shouldn't be using it anyway.

You have a Mega with 4 UARTs. You are using a pair of the UART pins, and yet you are using SoftwareSerial.

Don't.

instead use the `SerialX` object (where X is the number by the TX and RX for the pins) to communicate.

SoftwareSerial is only for those times when you *don't* have enough hardware UARTs, and you have plenty.
> 0 votes

---
Tags: arduino-mega, bluetooth, softwareserial
---


# Question
Title: Combining two code of two sensor in one program
I'm using two sensors, which is Galvanic Skin Response sensor and Heartrate sensor. The problem is that when I combined both of the codes, the only output that is showing up is from Heartrate only which is at A0. If I run them separately both codes works perfectly fine. My background in coding is basic and both codes came from the internet.

These are the codes:

```
    #define BLYNK_PRINT Serial
    #include <ESP8266_Lib.h>
    #include <BlynkSimpleShieldEsp8266.h>
    #include <SoftwareSerial.h>
    SoftwareSerial EspSerial(2, 3); // RX, TX

    #define samp_siz 4
    #define rise_threshold 4

    // Your ESP8266 baud rate:
    #define ESP8266_BAUD 9600

    char auth[] = "ba4e5bd1bd9549669a02ac378db9faf6";
    char ssid[] = "vivo";
    char pass[] = "takoyaki";

    /*char auth[] = "b3f01a592b78471f9f720b09d2ff8047";
    char ssid[] = "vivo";
    char pass[] = "takoyaki";
    */
    ESP8266 wifi(&EspSerial);

    BLYNK_CONNECTED()
    {
      Blynk.syncAll();
    }

    BlynkTimer timer;

    // Pulse Monitor Test Script

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

      // Set ESP8266 baud rate
      EspSerial.begin(ESP8266_BAUD);
      delay(10);

      Blynk.begin(auth, wifi, ssid, pass);

      pinMode(A0, INPUT);
      pinMode(A1, INPUT);

      //timer.setInterval(1000L, myTimerEvent);     //send the arduino's                         uptime
      timer.setInterval(350L, sensor);            //send gsr data every         0.35s
    }

    /*void myTimerEvent()
    {
      // You can send any value at any time.
      // Please don't send more that 10 values per second.
      Blynk.virtualWrite(V4, millis() / 1000);
    }
    */
    void sensor(){

      const int GSR=A1;
      int inputvalue=0;
      int gsr_average=0;
      long total=0;
      for(int j=0;j<10;j++)                       //Average the 10                 measurements to remove the glitch
          {
          inputvalue=analogRead(GSR);
          total += inputvalue;
          delay(5);
          }
       gsr_average = total/10;
       Serial.println(gsr_average);
       Blynk.virtualWrite(V6, gsr_average);
    }

    void heartrate ()
    {
        int sensorPin =A0;
        float reads[samp_siz], sum;
        long int now, ptr;
        float last, reader, start;
        float first, second, third, before, print_value;
        bool rising;
        int rise_count;
        int heartrate;
        int n;
        long int last_beat;

        for (int i = 0; i < samp_siz; i++)
          reads[i] = 0;
        sum = 0;
        ptr = 0;

        while(1)
        {
          // calculate an average of the sensor
          // during a 20 ms period (this will eliminate
          // the 50 Hz noise caused by electric light
          n = 0;
          start = millis();
          reader = 0.;
          do
                  {
            reader += analogRead (sensorPin);
            n++;
            now = millis();
          }
          while (now < start + 20);
          reader /= n;  // we got an average

          // Add the newest measurement to an array
          // and subtract the oldest measurement from the array
          // to maintain a sum of last measurements
          sum -= reads[ptr];
          sum += reader;
          reads[ptr] = reader;
          last = sum / samp_siz;
          // now last holds the average of the values in the array

          // check for a rising curve (= a heart beat)
          if (last > before)
          {
            rise_count++;
            if (!rising && rise_count > rise_threshold)
            {
              // Ok, we have detected a rising curve, which implies a         heartbeat.
              // Record the time since last beat, keep track of the two previous
      // times (first, second, third) to get a weighed average.
      // The rising flag prevents us from detecting the same rise more than once.
              rising = true;
              first = millis() - last_beat;
              last_beat = millis();

              // Calculate the weighed average of heartbeat rate
              // according to the three last beats
              print_value = 60000. / (0.4 * first + 0.3 * second + 0.3 *         third);

              heartrate = print_value;

              //Serial.print(print_value);
              Serial.print(heartrate);
              Serial.print('\n');
              Blynk.virtualWrite(V7, heartrate);

              third = second;
              second = first;

            }
          }
          else
          {
            // Ok, the curve is falling
            rising = false;
            rise_count = 0;
          }
          before = last;

          ptr++;
          ptr %= samp_siz;

        }
    }

    void loop()
    {
      Blynk.run();
      //timer.run();
      sensor();
      heartrate();
    }

```

# Answer
I have not tested the following code, so it will be up to you to do this and handle small errors. This is more about the coarse way to change the program. And you will have to understand, what the code really does, to be able to change it the way you need it.

First you will have to make some of the variables in the `heartrate()` function to global variables (by writing them near the top of the sketch outside of any function), so that they keep their values between the different executions of the function. I also changed some variable types, which match the type of the assigned values.

```
float reads[samp_siz], sum;
unsigned long now, start, ptr;
float last, before, reader;
unsigned long first, second, third;
bool rising;
int rise_count;
float print_value, heartrate;
unsigned long last_beat;

```

The sensor pin should be `#define`d at the top of the program (by convention). Then you should put this code:

```
for (int i = 0; i < samp_siz; i++)
    reads[i] = 0;
sum = 0;
ptr = 0;

```

into the `setup()` function.

Now we can look at the `while(1)` loop. On Arduino a value of `0` is treated as the boolean `false` and every other value as `true`. So this is the same as writing `while(true)`. The `while()` structure loops as long, as the expression inside the brackets evaluates to `true`. Since this is always the case here, it will loop forever. At this point you can just erase this line (and the corresponding closing bracket `}`).

After these changes the function will only take 1 reading (averaged over 20ms), then check, if a heartbeat was detected, and finally exiting to the `loop()` function. Since not every reading is a heartbeat, you will get more output from the `sensor()` function (which outputs on every execution) than from the `heartbeat()` function. And now, due to your functions being non-blocking, you will get very fast output. You might want to slow that down, by using a `delay()` or (better) the `millis()` function (like in the `BlinkWithoutDelay` example of the Arduino IDE).

Note, that this code exhibits some bad coding styles. You can get much of good code on the web, but also much of bad code. I see wrong types for variables, the usage of totally unnecessary variables and usage of the `millis()` function, which doesn't handle the rollover. This doesn't mean, that the code does not work. But you can get weird and difficult to debug errors through them.
> 0 votes

---
Tags: arduino-uno, programming, sensors, blynk
---


# Question
Title: Can't make ultrasonic sensor work with motor controller
I just started using Arduino Uno, I can't get the ultrasonic to work ,with motor controller board, the output value is always zero.

Just to make sure I'm talking about the correct stuff: I used this guide to try to make it work (look at the picture how did I connect the parts).

And this is my code:

```
#define trigPin A4//Attach Trig to port 8
#define echoPin A5//Attach Echo to port 7
#include <AFMotor.h>
//SMARS Demo 2 with Line sensor

AF_DCMotor R_motor(2); // defines Right motor pin
AF_DCMotor L_motor(1); // defines Left motor pin

int lmotorpin1 = 3;
int lmotorpin2 = 5;
int rmotorpin1 = 6;
int rmotorpin2 = 9;
int distancecm = 0;
//const int trigPin = 18;
//const int echoPin = 19;

// defines variables
long duration;
int distance;
void setup() {

  Serial.begin(9600); // sets up Serial library at 9600 bps

  //changes the following values to make the robot drive as straight as possible
  L_motor.setSpeed(200); // sets L motor speed
  R_motor.setSpeed(140); // sets R motor speed

  R_motor.run(RELEASE); //turns L motor on
  L_motor.run(RELEASE); //turns R motor on

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
      Serial.println(trigPin);
    Serial.println(echoPin);
  distancecm = mdistance();
  if (distance < 5) {
    L_motor.run(BACKWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
//    L_motor.run(FORWARD); //moves motor L Forward
//    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
  }
  else {
    L_motor.run(FORWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
  }
}

int mdistance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  Serial.print("Duration: ");
  Serial.println(duration);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

```

As you can see I tried different pin numbers but it always 0 ....

what do you think can be wrong?

The motors work. Motor Controller: KEYES L293D Motor Control Shield Sensor: Ultrasonic Ranger V2.0

# Answer
Pin numbers 0 and 1 are reserved for the Serial monitor which you're using on the board. The function `int mdistance()` should return an integer. You also didn't seem to set the motor pins as OUTPUT.
> -1 votes

---
Tags: arduino-uno, sensors, arduino-motor-shield
---


# Question
Title: Problem with Arduuino to breadboard Mega8
I am trying to make an arduino using mega8 mcu. After so much struggling with sync/response/signature problems and reading the previous questions, finally managed to do it (almost). However I still have some weird problems.

I uploaded the arduinoISP sketch to an Uno for programming the chips: AtMega8A-PU and AtMega8L-8PI (I had a couple of L version from years ago).

For bootloader selected the Mega8 from NG board in IDE 1.8.5 then uploaded to Mega8A-PU for the L version cloned the ng part in boards.txt and reduced the F\_CPU to 8MHz, (same bootloader code) and uploaded to 8l

Now, I'm able to upload sketches to both using a usb-serial breakout board/ avrisp mkII.

my first problem is when I disconnect the converter board neither of the MCUs can start unless I pull up or pull down the RxD pin (#2) which i find accidentally. it seems they both stuck in bootloader part. even if i leave the reset pin floating (using internal pullup) and tie the rxd pin they work fine up on applying power (with like an annoying 15~16s delay). the resistor value I tried 1K and 10K but no difference in operation and delay time. it wont start with rxd open. I couldn't find why?

another question is running the code on mega 8L as reliable as on 8A? (need it for lower V)

More clarification: they both run with Xtals and 22pf caps on breadboard. the 8l also works fine with 16MHz Xtal at 5v.

sketch (I know it's not much of help):

```
void setup() {
  Serial.begin(19200);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  tone(10,3520);
}

volatile unsigned int i, var = 1;

void loop() {
  digitalWrite(9, HIGH);
  for(i = 0; i < 1500; i++)
                 var += ((var * 3) / 2);
                 // do something (if compiler not wipe it for optimizing :D )
  digitalWrite(9, LOW);
  Serial.println(millis());
}

```

sample of 8A and (similarly) uno output:

```
7 11 15 19 23 27 31 35 39 44 48 52 56 60 64 68 72 76 80 84 89 93 97 101 106 110

```

8L output @ 3.3v @8MHz:

```
16 24 32 40 51 59 67 75 86 94 102 110

```

tone() output is the same for all

Appreciate your help

# Answer
> 0 votes
I found here: https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader

that NG / mega8 bootloader doesn't enable the rx pin internal pullup nor it gets out of the bootloader even if receiving junk data on rx (which was my case due to leaving it open thus floating). It also has a delay of 6 to 8 seconds intentionally.

Probably I'll use another bootloader since the link to source code on the page was broken or just program the L version without any bootloader and better fuse options.

---
Tags: bootloader
---


title: GPRS Based OTA to the NODEMCU

text:
# Question
Title: GPRS Based OTA to the NODEMCU
I need the OTA firmware update. I have the only option in my hand GSM(GPRS SIM800), with the help of this is it possible OTA, plz help me for this how I Do OTA via GPRS, FYI, I completed OTA Via WIFI.

# Answer
> 1 votes
Download the bin file over GPRS and then use the Update singleton object. It is declared in Update.h. Example is ArduinoOTAClass::\_runUpdate() in ArduinoOTA.cpp or ESP8266HTTPUpdate::runUpdate() in ESP8266httpUpdate.cpp

---
Tags: arduino-uno, nodemcu, firmware, software
---


# Question
Title: What do the charactors " '/2' " mean in the variable declaration?
I'm working on an RS485 project, In the CPP file there are `const` variables declared in the following manner:

```
#include <RS485_protocol.h>
const byte STX = '\2';
const byte ETX = '\3';

```

What does the '\2' and '\3' mean?

# Answer
The '\2' and '\3' are characters with octal code 2 and 3. Which is nothing more then 2 and 3 in octal and in decimal. The author could simply write `const byte STX = 2; const byte ETX = 3;`.

Characters with ASCII code 2 and 3 are control characters STX (start of text) and ETX (end of text). Control characters are invisible characters used to control the terminal or as mark characters in communication.
> 1 votes

---
Tags: variables
---


# Question
Title: ESP01 connected to Arduino can't read from UART while connected from external power source
I have an Arduino Uno connected to a NodeMCU ESP01 module, communicating via serial pins. The NodeMCU is powered from the Arduino's 3.3V pin. My idea is that the ESP01 receives MQTT messages, sends them to the Arduino via serial and wait for the Arduino to reply and then publish MQTT messages back.

If I power the Arduino from my computer's USB, everything works fine.

If I use an external power supply 12V/1A, the ESP01 can publish and receive "standard" MQTT messages (meaning, it does not send messages to the Arduino and does not expect a reply). It just receives and directly replies (no Arduino involved).

The problem occurs if the ESP needs to query the Arduino for a result.

The Arduino is able to read and write (I see the correct text in the console) to the serial port, but the NodeMCU ESP01 has problems publishing MQTT messages. Sometimes it does not publish anything (the ESP probably is unable to read what Arduino sends over serial), sometimes it publishes destroyed characters (random text).

It looks like the current needed by the ESP module is not high enough, but it does not make sense for me, since the external power supply should be able to provide more current than USB. Any ideas?

This is my schematic:

**Code:**

In my ESP01 I have the following MQTT `onMessage` listener, If the topic is a query for the Arduino (topic is validated by the `handleQuery` function), then the topic is sent by UART to the Arduino, which listens for specific strings in the `loop` function. When the Arduino receives a string, it does some logic and writes a reply back to the ESP via UART (`Serial.print()`).

After the ESP sends a message to the Arduino, it sets listeners for strings, that end with character %. If the reply from the Arduino is received, then it publishes an MQTT message with the result.

```
function onMessage(client, topic, message)
    if handleQuery(topic.."+"..message) then
        uart.write(0,topic.."+"..message)

        uart.on("data","%", function(data)
            if data=="quit%" then
                uart.on("data") -- unregister event
            end

            if data ~= "quit%" then
                client:publish(topic.."/response","REPLY:"..data,0,0)
            end
        end,0)
    else
        client:publish(topic.."/response","REPLY: Invalid query",0,0)
    end
end

```

The reply from the Arduino has the following message format:

```
 REPLY:<value>%
 quit%

```

This solution works if the Arduino is connected to my desktop computer's USB. It does not work if it is powered from an external power supply. It seems like the ESP is not able to read what the Arduino wrote to UART with `Serial.println()` if powered from an external power source.

I have no idea why, because power supply should be able to deliver more current.

**Edit:**

I use the following Arduino clone: eBay link

I tried to connect the ESP01 to the Arduino's 5V output with a voltage regulator (5V should deliver more current), and again, if the USB is connected, the ESP reads UART messages with no problem. If the Arduino is powered from an external power source, the ESP reads damaged characters. The only difference is that those damaged characters seems to be always the same. So perhaps some coding problems(?) or something like that.

So far it looks like a low current value is not a problem.

**Edit 2**

I removed from my code `print()` statement from the ESP/LUA code that I used for "debbuging". It printed to serial some messages for me. It seems that it cleaned traffic on Serial line a little bit.

Now I get most of the time correct characters, but the first character is missing, so instead of:

LOW% I get OW%
HIGH% I get IGH%
29.53% I get 9.53%

And from time to time I get String =\]�quit%.

Perhaps some input buffer has a problem(?).

# Answer
> 1 votes
Can I just check when you plug your 3.3V ESP into a 12V power supply it stops working? Is there a burning smell when you do this? Are you using anything to drop the voltage to 3.3V?

You also say you are connecting the ESP to the Arduino's 5V supply. Normally that's not a good idea either.

Also have you tied the ground of the Arduino to the ESP/12V PSU? If the two devices don't share a common ground then they won't agree what 0V and so won't be able to talk to each other over serial. Just run a wire from the Gnd on the Arduino to the Gnd on the ESP and they will jump into life.

# Answer
> 1 votes
Use a proper level shifter on the RX and TX lines. You probably are marginal as far as signal level.

The problem is not the voltage into the ESP8266. It is the level out of the TX of the ESP8266 not being high enough for the Uno CPU. This marginal voltage can cause messed up characters. Often we can get away with it at this level but it is really a marginal situation. It is not a reliable thing to do.

Specification for Vin high is 0.7xVcc. 0.7 x 5.0v = 3.5 volts !!!!

Using a 3.3 volt level signal will often work into 5 volt logic but not always. I had learned this the hard way. I designed a medium run product that used a 3.3v derived TX signal into the 5 volt logic RX input. Worked fine in 30 prototypes. But about 20% failures when running a production order. Different batch of chips resulted in different high trip point.

Just because the practice of using 3.3volt logic into 5 volt CPUs is common it is NOT guaranteed to work. Read the spec sheet! Do the math.

---
Tags: arduino-uno, esp8266, lua
---


# Question
Title: Arduino pin 13 as PWM output, not possible?
I have noted on more than one occasion the comments in sketches "reserving pin 13 for future PWM backlight dimming of the LCD" while using Uno and Nano boards. Am I missing something ? I always considered it NOT possible as PWM output is only available on pins 3,5,6,9,10 and 11 on most boards.

# Answer
> 3 votes
Arduino pin 13 is SCK/BP5 on the ATmega8 MPU, there's no hardware PWM capability on that pin, so any PWM would be software driven.

---
Tags: pwm
---


# Question
Title: Measure movement distance - not sure what sensor?
I want to measure the length of a step / stride -not sure what sensor to use.

I am trying to get several people to march a pattern for a band. I am thinking a Arduino to beep when step is too short or too small. Thinking the Arduino will be tied to their shoe laces. IR or Ultrasonic do not seem to be the correct sensor to use.

Ideas?

# Answer
> 0 votes
The sensor to use is an accelerometer. The principle is easy: measure the acceleration, perform a double integration and you have the distance (after the first integration you have the velocity).

The problem is that, because of the double integration, small errors in the acceleration signal lead to big errors in the calculated distance. For example: an error e in the acceleration leads to an error e.t2 in the distance (where t stands for time). For this reason al sorts of filters are used often in combination with gyroscopes and/or gravity sensors. The signals from the gyroscopes and/or gravity sensors are used for the low frequency signals (long term) and te signals from the accelerometer(s) for the high frequency signals (short variations). That's why you find these sensors often combined in one package (for example the BNO055 form Robot Electronics https://robot-electronics.co.uk/bno055.html).

It is a complicated and highly mathematical area of science. In fact you want to do the same thing as fitness trackers do (and I think you are striving to a higher accuracy than they) - and there are not many that do really well.

P.S. Robot Electronics also sell a tilt compensated compass board with this BNO055 chip: the CMPS12 (https://robot-electronics.co.uk/cmps12-tilt-compensated-magnetic-compass.html). With this board you can read out absolute and relative positions straight away without any calculations.

---
Tags: arduino-uno
---


# Question
Title: How do I make a toggleable Infrared motion detection module
I just got an Arduino and an Infrared motion detection module. What I tried making is, that if the module detected movement, a led would turn on, and if it detected movement again, it would turn off. So I wrote this code and tried looking online for solutions, but couldn't find it. I really don't know what to change about my code to make it work. Does anyone have solutions for this?

(Sensor value can be 0 or 1, 0 means nothing detected, 1 means something detected. After detection the value automatically goes back to 0 in a few seconds)

```
int Sensor = 4;
int led = 13;
bool bool1 = false;

void setup() {
pinMode(Sensor, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}

void loop() {
int SensorValue = digitalRead(Sensor);

if(SensorValue == 1){
  bool1 = !bool1;
  }

if(bool1 == true){
  digitalWrite(led, HIGH);
  }
if(bool1 == false){
  digitalWrite(led, LOW);
  }
}

```

# Answer
Consider using a state machine with 4 states. Currently you only have 2 states. One where "bool1" is TRUE and another when "bool1" is FALSE. The 4 states needed are:

1. When the LED is OFF & the PIR is NOT-ACTIVE.
2. When the LED is OFF & the PIR is ACTIVE.
3. When the LED is ON and the PIR is ACTIVE.
4. When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3. And you will only want to turn the LED OFF when traveling between states 4 & 1.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Are hardware interrupts used while controlling an LCD screen using the LiquidCrystal library?
I'm working on a tone generator project that uses Mozzi to make sound (sine waves mainly). As I understand, Mozzi can glitch if used along with hardware interrupts.

The plan is to use the classic 2x16 LCD screen, but I don't know the guts of the library or interface. Are hardware interrupts used while interfacing with an LCD screen, or by the LiquidCrystal library?

# Answer
The LiquidCrystal code shows that delays are used. That can cause audio glitches in the sound. The LiquidCrystal library does not use interrupts.

You could try to change the LiquidCrystal code according to the instruction on the Mozzi page.
> 1 votes

---
Tags: lcd, interrupt, audio
---


# Question
Title: Button state changes despite not being connected?
I have written some code to test buttons that I want to use

```
const int buttonPin1 = 1;
const int buttonPin2 = 2;
const int buttonPin3 = 3;
const int buttonPin4 = 4;
const int buttonPin5 = 5;
const int buttonPin6 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int buttonState6 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  pinMode(buttonPin5, INPUT_PULLUP);
  pinMode(buttonPin6, INPUT_PULLUP);
}

void loop() {
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);

  if (buttonState1 == HIGH) {
    Serial.println("button1 press");
  }
  if (buttonState2 == HIGH){
    Serial.println("button2 press");
  }
  else if (buttonState3 == HIGH){
    Serial.println("button3 press");
  }
  else if (buttonState4 == HIGH){
    Serial.println("button4 press");
  }
  else if (buttonState5 == HIGH){
    Serial.println("button5 press");
  }
  else if (buttonState6 == HIGH){
    Serial.println("button6 press");
  }
  else{

  }
}

```

I have tried with the buttonPins being A0-A5 as well, and whenever I try to run the code, it always spams out that button 5 and button 2 are being pressed, despite me not pressing them, as well as when I remove the buttons entirely, and pull out all the wires from it, it still prints it out. Even when I re-run the code. How can I fix this?

# Answer
You are setting button pins with INPUT\_PULLUP mode, which activates internal resistor connected to supply voltage. In this way, your input pins are in state HIGH if disconnected or if button is not pressed.

To fix this, you need to compare your button state with LOW. Also, make sure that one side of your buttons is connected to ground. Then, pressing the button will connect the button to ground and will bring your button pin to LOW.
> 3 votes

# Answer
The answer is in the way you configured the buttons. Because you used `INPUT_PULLUP`, the Arduino will read the pin as `HIGH` when it is connected to ground.

To utilize this in your setup, the buttons must be connected to ground, not 5V. This way, when the button is pressed, the input pin gets connected to ground, causing it to read `HIGH`.

Another way to fix the problem is to leave the buttons connected to 5V and just set the button pins to normal input: `pinMode(buttonPin, INPUT);`

---

In summary, there are two fixes: either connect your buttons between the input pins and ground, not 5V **OR** use `pinMode(buttonPin, INPUT);`.
> 0 votes

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


# Question
Title: Ultrasonic sensor and ledstrip color problem
So I've made a parking sensor with the Ultrasonic sensor and a ledstrip. But the ledstrip doesn't turn yellow or green. I think it has to do with the Thresholds. Can anyone help me to set this up? I also want a longer distance greater than 1 meter. This is my code:

```
#include "FastLED.h"
 #include <math.h>

    #define NUM_LEDS 32
    #define BRIGHTNESS 10
    #define DATA_PIN 4

    // Define the array of leds
    CRGB leds[NUM_LEDS];

    // Module Pins
    #define trigPin 11
    #define echoPin 12

    // Thresholds (in CM)
    long SECTION_SIZE = 80;
    long STOP_DISTANCE = 60;
    long WARNING_THRESHOLD = 50;
    long MAX_THRESHOLD = 375;

    long RED_THRESHOLD = STOP_DISTANCE;
    long YELLOW_THRESHOLD = RED_THRESHOLD + SECTION_SIZE;
    long GREEN_THRESHOLD = YELLOW_THRESHOLD + SECTION_SIZE;

    const int numReadings = 5;

    int readings[numReadings];      // the readings from the analog input
    int readIndex = 0;              // the index of the current reading
    int total = 0;                  // the running total
    int average = 0;                // the average

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

      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      FastLED.setBrightness(10);

      // HC-SR04 Setup
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // initialize all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
    }

    void loop() {
      long distance, lastRun;
      bool red, yellow, green;
      total = total - readings[readIndex];
      readings[readIndex] = calculateDistance();
      total = total + readings[readIndex];

      readIndex++;
      if (readIndex >= numReadings) readIndex = 0;

      distance = abs(total / numReadings);

      yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
      red = distance <= RED_THRESHOLD;
      green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

      if (red) {
        setRed();
      } else if (yellow) {
        setYellow(distance);
      } else if (green) {
        setGreen(distance);
      } else {
        setGreenStandby();
      }

      Serial.print(distance);
      Serial.println(" cm");
      FastLED.show();
      delay(1);
    }

    void lightItUp(const CRGB& pColor, const CRGB& sColor, uint16_t travel) {
      uint16_t travelFix = travel * (NUM_LEDS/SECTION_SIZE);
      uint16_t leftStop = travelFix/2;
      uint16_t rightStop = NUM_LEDS - leftStop;
      for (int i = 0; i < NUM_LEDS; i++) {
        if (i < leftStop || i > rightStop) {
          leds[i] = pColor;
        } else {
          leds[i] = sColor;
        }
      }

      FastLED.show();
    }

    long calculateDistance() {
      long duration;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      return (duration/2) / 29.1;
    }

    void setGreenStandby() {
      return fill_solid(leds, NUM_LEDS, CRGB::Black);
    }

    void setRed() {
      return fill_solid(leds, NUM_LEDS, CRGB::Red);
    }

    void setGreen(long distance) {
      long travel = GREEN_THRESHOLD - distance;
      return lightItUp(CRGB::Yellow, CRGB::Green, travel);
    }

    void setYellow(long distance) {
      long travel = YELLOW_THRESHOLD - distance;
      return lightItUp(CRGB::Red, CRGB::Yellow, travel);
    }

```

# Answer
> 2 votes
I believe your mistake is in this part of your code:

```
  yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
  red = distance <= RED_THRESHOLD;
  green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

  if (red) {
    setRed();
  } else if (yellow) {
    setYellow(distance);
  } else if (green) {
    setGreen(distance);
  } else {
    setGreenStandby();
  }

```

In particular, you are defining three boolean variables independently and then switching based on their values.

Assuming you are seeing the right values output on serial monitor (like `90 cm`, `60 cm`, etc...), which is something I'm unsure of as I'm not getting how you are determining the distance, then the following should be easier to follow/understand:

```
if (distance > GREEN_THRESHOLD) {
  setGreenStandby();
} else if (distance > YELLOW_THRESHOLD) {
  setGreen(distance);
} else if (distance > RED_THRESHOLD) {
  setYellow(distance);
} else {
  setRed();
}

```

You have only one variable determining the led strip configuration, no need to go to 3 and then try to reduce again ;-)

Please note that your `YELLOW_THRESHOLD` is defined as `140`, if you don't ever see a message in the serial monitor greater than that value you don't have a chance of seeing any colour other than red.... I'm asking because you mentioned *I also want a longer distance greater than 1 meter* that might imply your sensor is unable to go farther than 1 meter...

With the code above I'm checking the distance in a *greater to smaller* order: the first matching is the only one activated and it's impossible for the `distance` variable to match more than one condition. Generally speaking, simpler is better.

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


# Question
Title: How can I connect multiple different sensors that uses the same pins?
I'm doing a project on Arduino Uno and it requires me to connect 3 different sensors together: Waveshare 2.9 E-paper, MFRC522 RFID Reader and a ESP8266 wifi module. problem is, The e-paper and RFID uses the same multiple digital pins. How can I connect all of them together in a beardboard?

Edit: The E-Paper uses:

```
e-paper 3V3 -> Arduino 3V3
e-paper GND -> Arduino GND
e-paper DIN -> Arduino D11
e-paper CLK -> Arduino D13
e-paper CS -> Arduino D10
e-paper DC -> Arduino D9
e-paper RST -> Arduino D8
e-paper BUSY -> Arduino D7

```

The rfid uses:

```
SDA --> Digital 10
SCK --> Digital 13
MOSI --> Digital 11
MISO --> Digital 12
IRQ --> unconnected
GND --> GND
RST --> Digital 9
3.3V -->3.3V

```

The wifi uses:

```
GND --> GND
VIN --> 3.3v
Enable --> 3.3V
TX --> RX
RX --> TX

```

I'm very new to electronics so i'm sorry if something does not make sense

I'm using library, code and instructions from this 3 websites:

E-paper ( Waveshare 2.9 E-paper): https://www.instructables.com/id/Getting-Started-With-E-Paper-Display-Modules/

RFID (MFRC522 RFID Reader): https://randomnerdtutorials.com/security-access-using-mfrc522-rfid-reader-with-arduino/

Wi-Fi (ESP8266 wifi module): https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e

Thanks!

# Answer
You are lucky, the two devices creating the conflict both use the same pins because they both use the same interface, SPI to be precise, which allows to have multiple devices connected using different `Chip Select` pins, abbreviated as `CS`.

Of the two libraries, one allows to define the `CS` pin (RFID module), the other has it hardcoded (ePaper). So, when declaring your RFID library, you should use the constructor that allows to define the chip select pin:

```
void PCD_Init(byte chipSelectPin, byte resetPowerDownPin);

```

This means in your code you should use:

```
PCD_Init(6,8) rfid;

```

The above also implies one of your RFID connections must be changed: what was previously `SDA --> Digital 10` is now going to be `SDA --> Digital 6`. Please note I picked pin 6 randomly among the pins that seem unused by your code, but any other unused pin will be a good choice, including analog pins.

BTW, the web page about the RFID module uses a pin naming which causes a lot of confusion because it mixes up `SDA` with `MISO` and `MOSI`: those names are used in two different types of interface, the former is called I2C or TWI, the latter SPI. On Arduino the two interfaces share a couple of pins, but they are very different in many different ways.

In your case both modules use `SPI`, which is good for you.
> 2 votes

---
Tags: arduino-uno, esp8266, breadboard
---


title: Arduino UNO socket

text:
# Question
Title: Arduino UNO socket
***As I learnt so far is that Arduino UNO board has a socket for power input. The available power input range is between 7V - 20V, but the optimal usage range is 7V-12V.***

Here I am wondering:
---\> if there is a USB port for power supply, why do we need a power input socket? ---\> Or there is a battery on-board to charge?

# Answer
> 2 votes
The Arduino Uno has no on-board battery. The dc barrel jack is provided to give you more options to power the Uno, which is handy for stand-alone applications (without USB-connection to a computer) and/or battery powered applications. It can also supply more current than the USB-connection, which can be necessary when using shields.

The current taken from the usb port is limited to 500 mA by by an auto resettable fuse on the Uno (the voltage is not regulated by the Uno). This is the same amount of current as the USB 2.0 standard specifies that a standard down stream port (computer USB port) should be capable to deliver (for USB 3.0 this is 900 mA).

The power taken from the barrel jack is regulated to 5 V by a voltage regulator, the NCP1117ST50T3G. To work properly, this regulator needs a voltage difference (dV) between input and output of 1.2 V (depending on output current and ambient temperature). This means that the minimum voltage on the barrel jack is 6.2 V.

The regulator has an internal thermal limiting circuit that limits the junction temperature to ca. 175°C. This determines the maximum power dissipation (= output current times dV) the regulator can handle at a given ambient temperature. The maximum allowable power dissipation also depends on the size of the copper pad under the cooling tab of the regulator. As I don't know this size it is difficult to calculate de maximum power dissipation precisely, but my guess is that at 25°C and 6.2 V a power dissipation of 1 Watt should be possible. This gives a maximum output current of 1/(6.2-5.0)=0.833A=833 mA. Of course, at higher input voltages the maximum output current is lower. For example at 12 V: 1/(12.0-5.0)=0.143A=143mA.

# Answer
> 0 votes
Many projects (robots, drones, 3D printers, light control, art) made with Arduino have actuators (relays, motors), lights and displays which require a 9 or 12 V power supply. To use this power supply for the Arduino too, you need a voltage regulator which converts the voltage level and filters the noise and fluctuations created for example by that actuators.

---
Tags: arduino-uno, power, electronics, current, voltage
---


# Question
Title: Multiple sensors connected to Arduino MEGA 2560 Serial ports
I am using Arduino MEGA 2560 to read values from two sensors. Sensor 1 is providing us two values separated by a comma and a space followed by a newline character. e.g.:

```
2.277, 7.942
2.269, 7.897
2.263, 8.040

```

Sensor 2 is providing us a single value followed by a newline character. e.g.

```
1.213
1.333
1.17

```

Sensor 1 gives twice as many readings as Sensor 2 in the same amount of time. Sensor 1 is connected via `Serial1` and Sensor 2 is connected to `Serial2` on MEGA board. I am using the following code to read the values:

```
void setup() {
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    {
      Serial.print(Serial1.readStringUntil('\n'));
      Serial1.flush();
    }
  }

  Serial.print("\t\t\t");
  if (Serial2.available()) {
    while(Serial2.available())
    {
      Serial.write(Serial2.read());
      Serial2.flush();
    }
  }
  Serial.println();
  delay(1000);
}

```

I am expecting an output similar to this:

```
2.409, 8.150            2.134
2.490, 7.851            2.133
2.603, 8.759            2.122
2.634, 8.305            3.12
2.727, 8.408            1.32
3.018, 7.982            2.543
3.030, 7.982            1.345
3.020, 8.587            2.435
2.844, 8.034            2.763
2.690, 8.690            5.433
2.721, 8.011            2.348
2.705, 8.242            7.654
2.670, 8.713            2.123
2.756, 8.563            2.098
2.899, 8.413            2.765
3.464, 8.196            2.654
3.705, 8.437            2.343
3.435, 8.558            1.245
3.446, 8.592            2.345
3.421, 8.075            1.234

```

Instead I am getting something like this:

```
2.770, 8.332.635, 8.281         2.345
2.690, 8.690            2.674
2.721, 8.011            2.356
2.705, 8.242            2.345
2.670, 8.713            3.002
2.756, 8.563            2.094
2.899, 8.413.102, 8.523         2.984
3.464, 8.196            2.398
3.705, 8.437            2.745
3.435, 8.558            2.789
3.446, 8.592            2.543
3.421, 8.075            2.984
3.504, 8.153.772, 8.770         2.183
3.705, 8.552            2.784
3.653, 8.443            2.567
3.908, 7.971            2.098
5.020, 8.581            2.20
3.913, 8.247            2.342
3.762, 8.023.575, 8.345         2.123

```

The sensor readings after every few lines are distorted. I understand this might has something to do with the serial buffers. How could I rectify this and obtain the desired output?

# Answer
> 1 votes
Your serial buffers and moving in and out of phase, which is distorting your display.

Try something like:

```
void setup() {
  String sensor1;
  String sensor2;
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    sensor1 = Serial1.readStringUntil('\n'));
  }

  if (Serial2.available()) {
    sensor2 = Serial2.readStringUntil('\n'));
  }

  Serial.print(sensor1);
  Serial.print(sensor2);
  Serial.println();
  delay(1000);
}

```

I would also recommend the method suggested by @Majenko in his comment below your question.

---
Tags: serial, sensors, uart
---


# Question
Title: Maximum signal frequency obtained at the gpios of arduino mega 2560
Is it possible to obtain the rectangular pulse signals of freuency 10 MHz simultaneously at the GPIOs of arduino mega 2560?

# Answer
> 1 votes
The maximum fundamental frequency you can generate is *fcpu/2* \- or 8MHz with the default 16MHz resonator / crystal.

What shape the actual signal is, though, is very much dependant on the load on the IO pin. The IO pin has a specific *drive strength* which will provide limited current into a load. Any capacitance or inductance within that load causes a change in the *slew rate* (also known as the *rise time* or *fall time*) of the IO pin, which affects the shape of the signal by limiting the highest harmonic frequencies you observe. At the worst case scenario, you get an almost sine wave (only the fundamental frequency gets through). In general though you get more of a rounded-off square wave:

You can improve that slew rate by adding a buffer with a higher drive strength to the output (assuming your buffer has a high enough bandwidth). However, the IO pin itself will always have a certain amount of curvature to the signal due to its own internal capacitances.

For generating higher frequencies you are better off using a chip that is designed to operate at higher frequencies.

---
Tags: arduino-mega
---


# Question
Title: Send data to a pc localhost with ESP-01 wifi module
i use a linux machine with a localhost php server installed. Wifi machine is connected to the ESP-01 module (access point mode) and i can send several datas to the Arduino via the ESP-01 set as:

```
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

```

The php server can send data by GET method and Arduino receives pin=11:

```
 http://192.168.4.1:80/?pin=11

```

But, now, i would like to send to the php server datas from the Arduino. I tried this configuration but in my sketch but, it returns, error.

```
sendData("AT+CIPSTART=0,'TCP','http://localhost',80\r\n",1000,DEBUG);

```

Serial monitor:

```
   ERROR
   AT+CIPSTART=0,'TCP','http://localhost/test_php',80

   Link type ERROR

```

So please, how can i send and receive data with my ESP-01 module?

# Answer
> 2 votes
"localhost" is a name associated with the loopback interface of your computer. That is, 127.0.0.1.

It is *not* the address of your computer on the network. The only computer that can talk to "localhost" is the computer itself.

Instead of "localhost" you *must* use the IP address of your computer (or a FQDN that resolves to the IP address of your computer).

And you cannot open a TCP connection to a URL. You open a TCP connection to an IP or FQDN.

You really should learn the basics of IP networks before trying to write software for them.

---

Since your PC can communicate with the ESP8266 on 192.168.4.1 I assume that you are running the ESP8266 in SOFTAP mode and you have a WiFi interface connected to that access point. If so that WiFi interface will have a 192.168.4.x address assigned to it. That is the address you must open with a TCP connection on port 80 to connect to your apache server.

For example:

```
sendData("AT+CIPSTART=0,'TCP','192.168.4.3',80\r\n",1000,DEBUG);

```

Then you can craft a suitable HTTP request to send the data.

# Answer
> 0 votes
Open command prompt and type `ipconfig` Under `IPv4 Address` you can see IP or your PC. That IP address is address of localhost(because your PC is a "server" within your local/home network).

Don't forget to config XAMP/WAMP to listen special addresses. And of course if you want use localhost, your PC must be on.

> Yes, pc can send, but how can arduino do the same to the pc

Yes, it can. PC(localhost) is server and Arduino is client, like Stackexchange is host and your PC is a client (to Stackexchange). I hope you get it

```
 The ESP is not linked to my house network and i don't want it as

```

You can use public server, but you need to Know IP address of the server.

---
Tags: esp8266, wifi
---


# Question
Title: Button press with Arduino repeated many times
I have 5V -\> button -\> 10K resistor -\> PIN2 setup with Arduino UNO.

My code is very simple:

```
int count = 0;

void setup() {
  pinMode(2, INPUT);
  Serial.begin(9600);
}

void loop() {
  int state = digitalRead(2);
  Serial.println(state);
  if (state == HIGH) {
    count++;
    Serial.print("Hi");
    Serial.println(count);
  }
  delay(1000);
}

```

If the button is pressed print "HiX", but what I get is very strange. When I press the button only once I get this:

```
0
0
0
0
0
1
Hi1
1
Hi2
1
Hi3
1
Hi4
1
Hi5
1
Hi6
1
Hi7
1
Hi8
1
Hi9
1
Hi10
0

```

The button press is registered 10 times.

What am I doing wrong ?

# Answer
> 6 votes
I can't comment that's why I'm writing this as an answer but,

Are you doing exactly this this to wire the button?

I'd like to see your schematic but from what you describe there's a pull-down connection missing

# Answer
> 1 votes
there could be some stray capacitance that's holding the charge.

generally for cases like that, put the buttons active low + pull-up to avoid cases like yours.

# Answer
> 1 votes
I think it's not a problem of debouncing... There is a delay(1000) in the loop so after 1 second, the switch is not bouncing anymore. But switching to VCC is the problem. Connect the switch to GND and use the internal pullup resistors (pinMode(2, PULLUP). The switch then pulls it down to ground. Now it is floating and probably still HIGH after opening the switch....

# Answer
> 0 votes
Try out this code and schematic. It may solve your problem of debouncing.

```
const int buttonPin = 2; // Push Button at Pin 2

int buttonState = 0;
int lastButtonState = 0;

int counter = 0;

void setup()
{
  pinMode(buttonPin, INPUT_PULLUP); // Push Button with pull-up
  Serial.begin(9600);
}

void loop()
{
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState)
  {
    if (buttonState == HIGH)
    {
      counter++;
      Serial.println("Hi !");
      Serial.print("Number of button pushes:  ");
      Serial.println(counter);
    }
    else
    {
      Serial.println("Button off");
    }
    delay(50); // Delay a little bit to avoid bouncing
  }
  lastButtonState = buttonState;
}

```

---
Tags: button
---


title: LED brightness and Arduino ports

text:
# Question
Title: LED brightness and Arduino ports
Hi I am learning Arduino. Pin 13 lights the LED's very brightly. With subsequent LED's on other ports the LED's are much less bright than the one on 13.

Anyone know what is going on?

regards

# Answer
> 1 votes
You probably have cheap crappy inefficient leds on the other pins. Or you have the wrong value resistor in series with them. If they are not from the same batch, with the same resistor, you can't really complain. Maybe they are for a higher voltage. (because of the resistor value)

Are you sure you set the port pins for output?

```
pinMode(Output_PIN, OUTPUT);

```

---
Tags: arduino-uno
---


# Question
Title: esp8266 WiFi Cannot Connect to a PHP Server
I am using a magnetic float switch sensor to monitor water level in a tank. I am using a ESP8266 board.

I am trying to send the data collected by it to a php page in a host called "weris.link". I've checked the WiFi ssid and password for a myriad of times, yet somehow the connection to server still failed.

Did i commit a mistake ?

Here's my code :

```
#include <ESP8266WiFi.h>
#define FLOAT_SENSOR  D2     // the number of the pushbutton pin
#define LED           D8      // the number of the LED pin

const char* server = "weris.link"; // alamat server
const char* ssid = "aBee"; // SSID router wifi
const char* password = "xxxxx"; // password wifi
const char* SensorID = "Water_Level_Kelompok_1.Unsrat"; // ID sensor

const char* count1= "Water Tank Full";
const char* count2= "Water Level Low";
const char* recommend1= "Turn Off Flow";
const char* recommend2= "Turn on Flow";

WiFiClient client;

void setup()
{
  Serial.begin(115200);
  // initialize the LED pin as an output:
  pinMode(LED, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(FLOAT_SENSOR, INPUT_PULLUP);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
  }

void loop()
{
  if(digitalRead(FLOAT_SENSOR) == LOW)
  {
    // turn LED on:
    digitalWrite(LED, HIGH);
    Serial.println(count1);
  }
  else
  {
    // turn LED off:
    digitalWrite(LED, LOW);
    Serial.println(count2);
  }
  // mulai Kirim data sensor
   if (client.connect(server,80 && LED == HIGH)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Tank Full: " + String(count1) + ", Tank Level Below Normal: " + String(count2));

// dengan GET /path file php penangkap data
client.println("GET /iot/terima.php?data1=" + String(count1) + "&data2=" + String(recommend1) + "&sid=" +SensorID+ " HTTP/1.1");
client.println("HOST: weris.link");
client.println("Connection: close");
client.println();
client.stop();
Serial.println();
digitalWrite(BUILTIN_LED, HIGH);
}

else if(client.connect(server,80 && LED == LOW)) {
  client.println("GET /iot/terima.php?data1=" + String(count2) + "&data2=" + String(recommend2) + "&sid=" +SensorID+ " HTTP/1.1");
  client.println("HOST: weris.link");
  client.println("Connection: close");
  client.println();
  client.stop();
  Serial.println();
  digitalWrite(BUILTIN_LED, HIGH);
 }
  else {
Serial.println("Koneksi ke server gagal");
 }
  delay(5000);
}

```

Below is the screen capture from the serial monitor

# Answer
> 3 votes
This line:

```
if (client.connect(server,80 && LED == HIGH)) {

```

is definitely not going to do anything useful. Nor is this line:

```
else if(client.connect(server,80 && LED == LOW)) {

```

In both lines you're take the logical AND of the number 80 and the result of testing the LED.

Put the closing parenthesis in correct place:

```
if (client.connect(server,80) && LED == HIGH) {

```

and

```
else if(client.connect(server,80) && LED == LOW) {

```

Written this way you're still connecting twice if the LED is LOW. The code would be better written:

```
if (client.connect(server,80)) {
    if(LED == HIGH) {
      do stuff
    } else {
      do other stuff
    }
}

```

Even better would be to have the *do stuff* and *do other stuff* sections just set some variables and then write the code to talk to the web server once, using those variables. Having a single instance of the code will help avoid bugs in the future if you ever need to change it - the DRY (Don't Repeat Yourself) principle of programming.

Also, I hope you didn't just publish your wifi password here. If you did, you should change it.

---
Tags: esp8266, wifi, web-server, code-review, web
---


# Question
Title: Actuating a Hobbywing Skywalker 50A-UBEC ESC with Arduino CNC Shield
I need to control a brushless motor that came connected to this ESC using the Arduino CNC Shield V3.00 and Grbl 0.9j.

I connected the ESC's black wire to a GND from the shield and the ESC's white wire to the shield's Z+ limit (end stop).

I then tested by connecting everything but leaving the ESC unpowered, sending several `M3 S*`commands, where `0 <= * <= 1000`, then powering the ESC, but nothing happened.

# Answer
After a lot of research, I found out that the variable spindle speed output is a PWM signal, while the ESC needs a PPM signal to be controlled. Although that, it's a specific PPM signal that actually looks like PWM, so it can be used.

The problem is that, instead of being controlled by the duty cycle, what actually controls it is the amount of time that each pulse stays on high, which depends on the period, which is the inverse of the frequency. Long story short, the frequency is too high.

I managed to change the frequency used by grbl and found one that works. I don't know if this frequency allows the whole throttle range to be controlled but, for my application that doesn't require a very strict RPM, it was enough. Here are the steps (some steps are already explained elsewhere):

1. Import grbl's library in Arduino IDE.
2. Find out where the library got installed and edit `grbl/spindle_control.c`, lines 89 and 94.
3. Change `0x02` to `0x05`. Save and close the file.
4. Compile and download the library to Arduino Uno.
5. Connect everything but leave the ESC unpowered.
6. Send `M3 S0` (that's a zero).
7. Power the ESC.
8. You should hear a 123 tone (three beeps of different frequencies). It will then continue to beep once from time to time — I have no idea why... It should have stopped after a few.
9. Send `S600`. It should start spinning. If it doesn't, first send lower values from 0 to 600.
10. Send `S500` to stop.
> 2 votes

---
Tags: arduino-uno, pwm
---


title: Serial.write is synchronous

text:
# Question
Title: Serial.write is synchronous
I have a good experience of the real(/critical)time world, but I'm new with Arduino. I noticed that Serial.write is synchronous. If the buffer size is \>64 (the USART size) it lasts the time of the physical transmission minus 64char. It is obvious with simple tests as : Serial.write (char64) comes back in 1 millisec if the USART buffeur is empty and comes back in 64\*10/baudrate if USART buffer is full. Does anyone has written an asynchronous Serial.write? If not who can help me to write it? That is to say have the docs on the USART, the interrupts and soon? Basically, the point is to fill the buffer, get an interrupt when it is free to fill it again.

Thanks for contacting me.

# Answer
Until the buffer is full, `Serial.write` is asynchronous. You just have to avoid filling the buffer up.

Fortunately, there is the function `Serial.availableForWrite()` which returns the number of bytes available in the buffer. You can use that to see if there's room in the buffer for what you want to send, and if there is then send it (i.e., just placing it in the buffer).

By re-writing the UART handing to call your own interrupt routine to send a byte as and when needed you are basically doing exactly the same as the Arduino's HardwareSerial class is doing - just with your own buffer instead of the one in the HardwareSerial class.

There is no hardware buffer in the Arduino. It only has a single byte shift register for sending UART data. Any buffering has to be done in software, so either you implement that yourself, or use the existing buffering, or only ever generate and send one byte at a time, which is fairly useless.

If you *really* want to re-write it then all the information you need is in the datasheet for the MCU on your chosen development board.

---

<sub>*The terms "synchronous" and "asynchronous" when applied to situations like this are better replaced with "blocking" and "non-blocking", since "synchronous" and "asynchronous" when applied to serial communications imply different styles of data transmission, not software implementation.*</sub>
> 6 votes

# Answer
Thanks to Majenko I have the pieces of a gloabal solution. I just summaries and share : The Serial.availableForWrite() gives the available space left free in the Serial TX buffer. It your string is shorter the Serial.write will be passing, if not blocking (until enought free space). You can adjust the size of this TX buffer (default is 64) in HardwareSerial.h. Take care buffersize larger than 256 (255 available) result in a longer processing time for Serial.write. If you have Serial, Serial1, ... the size will be the same for both and ofcourse the buffers are seperated. I noticed thas Serial.flush is blocking long (80ms). This is to take into account for time critical issues. Enjoy
> 0 votes

---
Tags: serial
---


# Question
Title: SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls
i'm working on project where i'm trying to achieve that arduino parse caller ID so i can use it later to send SMS with sensor reading data.

Somehow i made that code (with much googling) and it works great... But when i include arduino sleep part, it does work at beginning, but after i call SIM800 4-5 times with distinct of 30 seconds, i get unusable data on Serial, so i can't no longer parse correct number.

I tried many things, dropping baud rate to 1200, changing delay, but still i get strange characters after few calls.

Can anyone help me?

P.S. ATMEGA328P ic MCU

Thank you, Matija

```
#include <SoftwareSerial.h>
#include <avr/sleep.h>

SoftwareSerial SIM800(8, 7);

String buffer1;
unsigned int current_millis = 0;
String phone;

void setup() {
     buffer1.reserve(200);
     phone.reserve(20);

     Serial.begin(19200); //
     SIM800.begin(9600);
     delay(1000);
     SIM800.write("AT\r");  // because of SIM800L autobounding mode
     delay(1000);
     SIM800.write("AT+IPR=9600\r");  // set baud at 9600, i tried with 1200
     and  other, and with autobauding but still got same problem
     delay(1000);
     SIM800.write("AT+CMGF=1\r");  // set SMS mode to text
     delay(1000);
     SIM800.write("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     Serial.print(SIM800.readString());
     SIM800.write("AT+CLIP=1\r\n");
     delay(1000);
     SIM800.write("AT+SGPIO=0,7,1,0\r");
     delay(1000);
     SIM800.write("AT+CSCLK=2\r"); //power saving mode of SIM800L
     delay(1000);
     current_millis = millis();
}

void loop() {
   // put your main code here, to run repeatedly:
   if (SIM800.available() > 0) {
      buffer1 = SIM800.readStringUntil('\n'); //Saving string then parsing
           caller number from it
      Serial.println(buffer1);
      parse();
      current_millis = millis();
      }

    if ((millis() - current_millis) > 10000) { //Putting atmega tu sleep
       sleepNow();
       delay(1000);// tried many delays
       current_millis = millis();
     }

 }

void parse() {
    if (buffer1.indexOf("CLIP:") > 0) {
        phone = buffer1.substring(buffer1.indexOf("+CLIP: ") + 8,
        buffer1.indexOf("+CLIP: ") + 21); //parsing caller number
        Serial.println(phone);
        SIM800.write("ATH\r"); //hang out phone call
        delay(500);
        SIM800.write("ATH\r");
        delay(500);
  }

}

void sleepNow() { //PIN CHANGE INTERRUPT ON PIN 7,8 BECAUSE SOFTWARE SERIAL
                   LIBRARY USE IT AND IT WILL WAKE UP ATMEGA
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set herethe
                                          sleep bit in the mcucr register
    sleep_mode();            // here the device is actually put to sleep!!
                         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable
                                sleep...
    }

```

# Answer
> 1 votes
Give AltSoftSerial a try, it's hands down superior.

Reset might work but it does not actually solve your problem, it just swipes it under the mattress. Also, have you considered ditching that String? It is the source of many problems regarding memory. You could relatively easily substitute it for an array of chars instead. Something like this, taken from example#2:

```
void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

```

# Answer
> 1 votes
When you use sleep mode SLEEP\_MODE\_PWR\_DOWN you're turning off all of the microcontroller's timers, Including the timer SoftSerial is using. I expect that turning off and then when wake from sleep turning back on the timers is affecting the timing of your serial communications.

Try using SLEEP\_MODE\_IDLE instead of SLEEP\_MODE\_PWR\_DOWN and see if it corrects the problem.

---
Tags: arduino-uno, serial, gsm, sleep
---


title: RS422 interfacing with the Arduino

text:
# Question
Title: RS422 interfacing with the Arduino
Good day, I have a sensor which supports serial data output using RS422 which has 4 wires (RX+, RX-, TX+, TX-) my question is how can I connect this sensor to the Arduino. I read that i can use 2 max485 chips to do this but uncertain of the exact procedure. Thanks in advance.

# Answer
> 1 votes
There are pre-made and very inexpensive Arduino RS-485 modules available on Ebay or Amazon. Much simpler than building your own circuit.

They look like this:

# Answer
> 0 votes
The MAX490 chip consists of DI (pin 3) and RO (pin 2) pins that connect to the Arduino TX and RX respectively. the rs-422 side of the chip consists of pin 5 (Y / T+), Pin 6 (Z / T-), pin 7 (B / R-) and pin 8 (A / R+)

http://arduinotronics.blogspot.com/2018/09/long-distance-serial-with-rs-422.html

---
Tags: serial, sensors
---


# Question
Title: How to use php file_get_contents with ESP8266
A part of my project need to get datas from an ESP8266 with php script. I tested this script and i don't know why i can get the datas in an iframe element and nothing with file\_get\_content function. In iframe element my browser displayes "Hello my friend!" as wanted:

The ESP8266 server mode at 192.168.4.1 address, part of code:

```
String webpage = "<div id='div1'>Hello</div>";
webpage += "<div id='div2'>my</div>";
webpage += "<div id='div3'>friend!</div>";

String cipSend = "AT+CIPSEND=";
cipSend += 0;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";

sendData(cipSend,1000,DEBUG);
sendData(webpage,1000,DEBUG);
sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);

```

The php script:

```
<html>
    <body>
    <iframe src="http://192.168.4.1/?cmd=SS,0,0,"></iframe>

 <?php

 $url="http://192.168.4.1/?cmd=SS,0,0,";
 $lines_string = file_get_contents($url);
 echo htmlspecialchars($lines_string);

?>
    </body>
</html>

```

If i replace the url by:

```
$url=https://arduino.stackexchange.com

```

It works with php script,so what is the issue with the ESP8266 ?

# Answer
> 1 votes
To process the request by php, you must send valid HTTP response. The browser tolerates too much.

```
String webpage = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
webpage += "<div id='div1'>Hello</div>";

```

---
Tags: esp8266
---


# Question
Title: ESP8266 feather huzzah wiring for MFRC522
I'm trying to wire the mfrc522 and the huzzah but i can't seem to figure out the rst pin.

I found the pin out diagram but it doesn't show or idk how its labeled as.

# Answer
> 2 votes
use Wemos table from your link. here is the mapping to esp8266 io pins

```
RST/Reset   D3 = io 0
SPI SS      D8 = io 15
SPI MOSI    D7 = io 13
SPI MISO    D6 = io 12
SPI SCK     D5 = io 14

```

If you want, you can use any pin for SS and reset. See the examples.

```
#define SS_PIN 4
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);

```

# Answer
> 0 votes
Use GPIO0 (D3 on the Wemos). The reset signal is under program control in the library and isn't the same as the ESP8266 reset input.

---
Tags: esp8266, adafruit
---


# Question
Title: Triggering an SPI transfer with an interrupt in Arduino Due
I have a DDS that is controlled by an Arduino DUE, loop() waits for Serial commands and based on them calls one or another function that sets the DDS's frequency, phase, amplitude etc via SPI. In addition to that I want to be able to use an external interrupt triggered by a TTL signal to reset the DDS's phase accumulator. The phase reset is done by writing an SPI register - resetPhase().

Somehow the resetPhase() is triggered correctly, but as soon as I add a SPI.transfer to it the SPI communication stops working altogether, not just through interrupts, but also the functions triggered via serial commands stop working.

Is there a way to get it to work?

```
SPISettings spiSettings = SPISettings(10000000, MSBFIRST, SPI_MODE0);

void setup()
{
    pinmode(chipSelect, OUTPUT);
    int syncPIN = digitalPinToInterrupt( interruptPin);
    SPI.usingInterrupt(syncPIN);
    attachInterrupt(syncPIN, resetPhase, RISING);
}

void resetPhase():
{
    SPI.beginTransaction(spiSettings);
    digitalWrite(chipSelect, LOW);
    SPI.transfer(controlRegister);
    digitalWrite(chipSelect, HIGH);
    SPI.endTransaction();
}

```

# Answer
> 1 votes
In general, it's best to do as little as possible in your interrupt service routine (ISR).

`resetPhase` is your ISR here, and typically it would set a flag or semaphore to signal lower priority code that certain work needs to be done and, in this case, probably nothing more. Then your `loop` code on noticing the flag is set would clear the flag and do its work.

I imagine the library authors thought `SPI.usingInterrupt` would ease use of SPI, but performing I/O in an ISR seems a bit contrary to best practices. These concerns are echoed here, along with some other caveats regarding interrupts and ISRs. Possibly not the answer you're looking for, but I hope it helps.

---
Tags: interrupt, arduino-due, spi
---


# Question
Title: Is it possible to simultaneously acquire 2 values from the Arduino?
I am currently making a project using a resistive touch screen and an Arduino Uno. The resistive touch screen outputs an X and Y coordinate pair, which I then want to be able to read and output on an X-Y scatter plot in Visual Basic. I am wondering if it's possible to collect these X and Y coordinates at the same time, and read them through the serial port so they can be used in Visual Basic.

# Answer
> 0 votes
Since this is a Arduino forum I will answer the Arduino part of your question. Yes you can get the coordinates and get them into the computer via a serial port.

---
Tags: arduino-uno, serial, visualstudio
---


title: Is arduino a single board computer?

text:
# Question
Title: Is arduino a single board computer?
First excuse me if tags are not reflecting the content,

While watching a video about single board computer (SBC) I got confused that it doesn't mention arduino as SBC. I always considered it as SBC.

After digging around a bit I got more confused. It seems single board computer is where processor, memory, I/O this things are built on single circuit board rather than using expansion card attached on to a circuit board (motherboard). According to that is not arduino a SBC? It's processor, memory,storage are on single ATMega32A (for uno) attached on a single board which provides some I/O port (I/O pin, USB, UART, I2C etc.).

From some digging I learned that arduino code runs on bare metal unlike SBC like Rpi and that's the reason for it not being SBC. This seems weird reason.

(1) Is Arduino a SBC? If (1) is no then next questions are,

(2) Is Being less powerful is the cause? If yes where do you draw the line?

(3) Not having an OS hosted environment for execution is the cause?

If (3) is Yes then,

(4) Arduino has some bootloader code to load the program through USB. Isn't it kinda like OS, I admit it's not giving some nice api for h/w usage but is it all?

This link comment section kind of started a debate but ended without giving clear answer about my question.

# Answer
It may be impossible to draw a sharp line that separates single board computers from microcontroller boards. There are, however, several attributes that can help differentiate them and, in a sense, draw a blurry line. If a specific board has most of the attributes of SBCs it's probably safe to call it an SBC. Same for MCU boards.

Processing power may be one of those attributes. A typical SBC is many orders of magnitude more powerful than your typical Arduino. A Raspberry Pi, for example, has half a million times the RAM of an Arduino Uno. Although you can find microcontrollers that are a thousand times more powerful than the Uno, you are unlikely to find many SBCs that are one hundred times less powerful than a Raspberry Pi.

The operating system may also be a factor. SBCs are typically meant to run mainstream OSes: some flavor of Linux, Windows or Android. Microcontrollers, on the other hand, will most often run some kind of RTOS (real-time OS) specifically designed for the embedded world, if they do run an OS at all.

A factor that has not been mentioned yet is the I/O capabilities. On an SBC, you will typically find the kind of I/O ports that are common on desktop or laptop computers, like HDMI, USB host or Ethernet. A microcontroller, on the other hand, is more likely to have analog inputs or outputs, as these are more useful in the “electronics” world than in the “computer” world. Of course, the lines are blurry: you may find SPI, I2C and GPIOs on both SBCs and MCUs.

Neither of those factors may be enough to tell an SBC apart from a MCU board. But taken together, they can allow you to say that board A is clearly an SBC, board B is clearly an MCU board, and board C is somewhere in between and hard to classify.
> 2 votes

# Answer
The Arduino isn't a computer. It is a programmable microprocessor / microcontroller.

Generally a computer can run multiple applications where most programmed devices like the Arduino are running only one program. This is not an official definition but it is one way to differentiate.

It can be difficult to draw a line where it is one but not the other.

> (4) Arduino has some bootloader code to load the program through USB. Isn't it kinda like OS, I admit it's not giving some nice api for h/w usage but is it all?

No that isn't like an operating system. The Arduino does not have a real operating system when compared to a computer system. And someone being able to load in a new program is just changing the current single program that is runnable.

> An operating system (OS) is system software that manages computer hardware and software resources and provides **common services for** **computer programs**.

I think the **programs** being plural is an important factor, but this is only my opinion.

There is no one definition so you will get a number of different opinions. And most will be reasonable.
> 3 votes

# Answer
It all depends on your definition of "computer". From the point of view that the Arduino is a "Turing complete" architecture, with CPU, memory, storage, IO, etc, then yes, it is a computer. But it's not a "computer" as in what you have on your desk.

Is a mobile phone a "computer"?

We can shift the definition elsewhere if you like:

In general an SBC is taken to be a SoC mounted on a board with the support components. A SoC is a "System on Chip". But now we just move the definition to "What is a SoC?" - a question that has been asked many times before.

There is no one specific thing that divides a SoC from a Microcontroller. For instance:

* "A SoC runs an operating system, but a Microcontroller doesn't" - except that there are microcontrollers that can and do run operating systems, and you don't *have* to run an operating system on a SoC.
* "A SoC relies on external memory, but Microcontrollers have it built in" - except that there are SoCs with built in memory, and Microcontrollers than need external memory to function

The list goes on.

My definition of what constitutes a "computer" as opposed to an "embedded system" has nothing to do with what the device *is*, it's *what you do with it*.

If the board is being used with a keyboard, mouse, screen, etc for *generic* operation then it's a computer. If it's being programmed for *one specific task* then it's an embedded system. The same hardware could be used in both ways, and I would call it a computer if it were running "general" software (operating system, web browser, server software, etc), but I'd call it an "embedded system" if it were running one program only (with or without an OS) gathering data, reporting it back to a central system, etc.

For something to be termed a "Single Board Computer" I would say it has to be *capable* of running *general* software designed to run on a "traditional" computer. Things like Linux with Apache etc, or a desktop environment.

Mind, this is only my opinion, and as such it will differ from other peoples' opinions.
> 1 votes

---
Tags: programming, raspberrypi, documentation
---


# Question
Title: How to connect ESP8266-01 (AT-commands) to its web server using AJAX
I am just new on using AJAX in web server, I got an error on declaring "server" I am confused about this because I just used only a AT commands to used the ESP8266-01 (wifi-module) I hope you can help me, I want to get the data (distance) to print in the web server(page) in real-time(no refresh). So I used the AJAX for it but this code is still error. Advance thanks on anyhelp :)

```
 #include "NewPing.h"
 #include <SoftwareSerial.h>
 #define DEBUG true

 SoftwareSerial esp8266(10,11);
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

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

 server.on("/",WebsiteContent);
 server.on("/xml",XMLcontent);
 server.begin();

 pinMode(TRIGGER_PIN, OUTPUT);
 pinMode(ECHO_PIN, INPUT);

 sendData("AT+RST\r\n",2000,DEBUG);
 sendData("AT+CWMODE=2\r\n",1000,DEBUG);
 sendData("AT+CIFSR\r\n",1000,DEBUG);
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

}

void javascriptContent(){
Javascript ="<SCRIPT>\n";
Javascript+="var xmlHttp=createXmlHttpObject();\n";
Javascript+="function createXmlHttpObject(){\n";
Javascript+="if(window.XMLHttpRequest){\n";
Javascript+="xmlHttp=new XMLHttpRequest();\n";
Javascript+="}else{\n";
Javascript+="xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n";
Javascript+="}\n";
Javascript+="return xmlHttp;\n";
Javascript+="}\n";
Javascript+="\n";
Javascript+="function response(){\n";
Javascript+="xmlResponse=xmlHttp.responseXML;\n";
Javascript+="xmldoc = xmlResponse.getElementsByTagName('data');\n";
Javascript+="message = xmldoc[0].firstChild.nodeValue;\n";
Javascript+="document.getElementById('div1').innerHTML=message;\n";
Javascript+="}\n";

Javascript+="function process(){\n";
Javascript+="xmlHttp.open('PUT','xml',true);\n";
Javascript+="xmlHttp.onreadystatechange=response;\n";
Javascript+="xmlHttp.send(null);\n";
Javascript+="setTimeout('process()',200);\n";
Javascript+="}\n";

Javascript+="</SCRIPT>\n";

}
void WebsiteContent(){
javascriptContent();

 Website="<html>\n";
 Website+="<style>\n";
 Website+="#div1{\n";
 Website+="width:400px;\n";
 Website+="margin:0 auto;\n";
 Website+="margin-top:130px;\n";
 Website+="font-size:900%;\n";
 Website+="color:powderblue;\n";
 Website+="}\n";
 Website+="</style>\n";
 Website+="<body onload='process()'>";
 Website+="<div id='div1'>"+data+"</div></body></html>";
 Website+=Javascript;
 server.send(200,"text/html",Website);
 }
 void XMLcontent(){

 XML ="<?xml version='1.0'?>";
 XML+="<data>";
 XML+=data;
 XML+="</data>";

 server.send(200,"text/xml",XML);

 }
 void loop()
 {

 delay(2000);
 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

 long duration,distance;
 duration= pulseIn(ECHO_PIN,HIGH);

 distance = duration/58.2;

 data=(String)distance;
 delay(500);

 server.handleClient();

 if(esp8266.available())
 {
 if(esp8266.find("+IPD,"))
 {
 delay(1000);
 int connectionId = esp8266.read()-48;

 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);

}
}
}
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
return response;
}

```

# Answer
> 1 votes
You're trying to mix code that is intended to run directly on an ESP8266 using ESP8266-specific libraries on an Arduino. It can't ever work.

Likes like:

```
server.on("/",WebsiteContent);
server.on("/xml",XMLcontent);
server.begin();

```

are for use with the ESP8266's ESP8266WebServer library which doesn't run on an Arduino. To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available.

So, either:

* Do it *all* with AT commands only, or
* Ditch the Arduino and program the ESP8266 directly instead.

---
Tags: esp8266, web-server
---


title: Teensy 2.0 usb xinput device

text:
# Question
Title: Teensy 2.0 usb xinput device
So I came across a library that lets you turn your TeensyLC/3.X into an xinput device. I only have a 2.0 on hand. I spend the past few hours messing around with the LC example to see if I could hack it over to work on a 2.0 board. Admittedly, it will take much more time analyzing everything before I can make a more educated attempt. I saw another project that is able to use the 2.0 as xinput devices but the firmware is only available in its hex form.

So I'm wondering what would be the best way to go here... all of the xinput code is in the `/core/teensy3` directory. It has many spidering dependencies which will take a lot of time to go through and try and port(would that even work?). Is there a super "lite" version of the core that lets you fill out device descriptors/handshake/etc? If there is, the xinput just becomes a task of emulating the xinput packets.

Anyway, as this is my first usb input project, any suggestions would be greatly appreciated. Again, I already have the 2.0 and I know its possible so just getting a LC/3.X I'd like to avoid. I'm more just looking for direction on the best way to get started.

# Answer
> 1 votes
The Teensy 2.0 is a completely different MCU from the 3.0 with very different libraries.

USB on the 32U4 on the 2.0 typically uses the LUFA library for USB.

So to answer your question: I doubt it will be possible to port code written for the 3.0 SAMD based teensy to the AVR based 2.0 teensy without basically rewriting it from scratch.

The Arduino Leonardo also uses a 32U4 so you might want to look for examples code written for the Leonardo.

The examples from the LUFA library may be useful but they are not designed to be used with the Arduino IDE.

**UPDATE** From the comments, there is this project: https://github.com/bootsector/XInputPadMicro that uses LUFA and targets the Leonardo.

---
Tags: usb, teensy
---


title: Arduino Uno Reading Fuses

text:
# Question
Title: Arduino Uno Reading Fuses
I am trying to read the fuse values for the Arduino Uno, but keep getting the following results returned back to me:

```
enter code hereavrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "/usr/local/CrossPack-AVR-20131216/etc/avrdude.conf"
     User configuration file is "/Users/hd334/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

```

I have tried using avrisp as the programmer too, but this reports an invalid device signature. If I override the device signature check with -F I get the same results as above.

I am using an Uno as the ISP to another uno and have connected the two together as detailed in https://www.arduino.cc/en/Tutorial/ArduinoISP

I have boot loaded the Arduino Atmega328P boot loader and from the fuse settings given in the boards.txt file expect to see: lfuse reads 0xff hfuse reads 0xde efuse reads 0x05

Another question is with the low fuse set to 0xff the CKDIV8 is programmed so won't the clock be set to 2MHz?

Please help

# Answer
Concerning your questions about clock division settings: have a look at this pretty tool, it gives you a avrdude query for setting fuses (take care!). The CKDIV8 bit of the low fuse is set by default, so an AT328p will run at 1MHz, clearing this bit will result in 8 MHz.

When flashing you should never override any checks as this may damage/lock your chip.

I see that avrdudes states the supply voltage to be 0.3 volts which is far to low for communication. Any received bits would be low level and therefore any information read will be 0. ISPs usually provide a supply voltage which often can be selected by switches on the programmer. If you are sure your programmer is allright, check your circuit in general.

Btw, which ISP-model do you use? Is your mcu assembled on a custom pcb (setup?)? If yes, do you have an arduino(like) board to verify this behaviour?
> 1 votes

# Answer
I'm using a stk500 (USB \<\> ISP programmer) to read atmega328p fuses. I use this cmd:

```
C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe -CC:"\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cstk500 -PCOM9 -e -Ulfuse:r:-:i -Uhfuse:r:-:i -Uefuse:r:-:i

```

Sometime ago I had some issues with device signatures because I missed the "p" in atmega328p definition.

As a tip, you can check the Arduino verbose to help you with more information:

FILE \>\> PREFERENCES

SHOW VERBOSE OUTPUT DURING: \[x\] COMPILATION \[x\] UPLOAD
> 0 votes

---
Tags: arduino-uno, atmega328, isp, oscillator-clock
---


# Question
Title: Porting the FastNoise c++ library to Due
I'm trying to use the FastNoise library with a Due, however, I get something like the following errors, when I try to complie.

error: 'abs' was not declared in this scope
error: 'mt19937' is not a member of 'std'
error: 'uniform\_int\_distribution' is not a member of 'std'

so I added the following:

```
#include <cstdlib>
#include <cmath>
#include <random>

```

which solved most of the problems, however it still says printf hasn't been declared. So I tried to edit cstdio to comment out the #undef printf, but it just brought back the full list of error messages, so that's not the solution. I googled some solutions but none of these seem to work. Do you have any suggestions I should try?

I'm not trying to use printf, just want to use the library.

Thanks for any help.

# Answer
The FastNoise library compiles as it is for the Arduino MKR and Arduino Zero, but there is a "not cool" issue for the Due: https://github.com/arduino/ArduinoCore-samd/issues/308

A issue with `assert` can easily be solved, but the `#include <algorithm>` and `#include <random>` are somehow linked to a `printf` function.
I thought it was very hard, but then @Juraj wrote in his answer about the simple solution to comment out the `#undef printf` line.

In the file cstdio is a list of about fourty `#undef` lines. Only the `printf` requires to be commented out.

```
// #undef printf

```

The file is located in the hidden "Arduino15" folder in the build environment for the Due: Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio

Then it will also compile for the Arduino Due (even without removing the assert). There are many warnings.

I was able to run it on a SAMD21 processor and it produces random numbers. However, I am not sure that those numbers are correct. I don't know if the many compiler warnings can be ignored.

```
#include <FastNoise.h>

FastNoise myNoise; // Create a FastNoise object

float heightMap[32][32]; // 2D heightmap to create terrain

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("FastNoise");
  delay(1000);

  myNoise.SetNoiseType(FastNoise::SimplexFractal); // Set the desired noise type

  for(int x=0; x<32; x++) {
    for(int y=0; y<32; y++) {
      heightMap[x][y] = myNoise.GetNoise(x,y);
      SerialUSB.println(heightMap[x][y]);
    }
  }
}

void loop() {
}

```

Do you know the XY Problem? You did not explain the reason for trying to make that library run on a Arduino Due. Perhaps there is an other way for what you want to achieve.

The Arduino Due was a major update for the Arduino boards, but nowadays some say to avoid the Arduino Due because it has issues (hardware and software).

---

I have updated my answer with help of the answer from @Juray.
> 0 votes

# Answer
The workaround is in the issue found by Jot. In file

`C:\Users\aaaaaa\AppData\Local\Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio`

comment the line

`#undef printf`

and it will compile
> 1 votes

---
Tags: arduino-due, printf
---


title: Powering Adafruit motor shield

text:
# Question
Title: Powering Adafruit motor shield
Making sure not to blow anything up before testing.

I have an adafruit motor shield and an arduino Uno. The arduino uno has a power input and I was hoping to use it to power the motor shield, a nema-17 motor, and an I2C connection. Currently I'm using the power connection on the motor shield to power the nema-17 motor and a serial connection to power the arduino.

Can I just connect a power supply to the input port on the ardiuno uno and power the motor shield and nema-17 step motor?

# Answer
You should not power the motor shield (and thus the motor itself) through the Arduino. The motor draws a high current (depending on the exact product - there are many versions of the nema-17 - I found current in the range of 1 - 2A) and the voltage regulator (or the diode in the path) are not rated for this much current (for the Uno the absolute maximum is 200mA, including the Uno itself). You will fry these components, if you try to draw more than the rated current.

But you can use the same power supply and provide the power to Arduino and motor shield in parallel. This way the current for the motor does not have to pass through the Arduino.
> 1 votes

---
Tags: arduino-uno, power
---


# Question
Title: Problem sending string with Python to Arduino through serial port
I want to send string 50 to Arduino through serial port, the Arduino UNO seems it communicates with port COM25 but it doesnt receive the string properly:

```
import serial # if you have not already done so

ser = serial.Serial('COM25')
ser.baudrate = 9600
ser.write(b'50')
ser.close()

```

Btw Arduino code is correct I checked it with other serial com programs. How can I fix the above code?

# Answer
The AVR Arduinos (Uno, Nano, Mega) have auto-reset function. At opening of USB connection the circuit around USB resets the MCU. After reset the bootloader waits a second for a new upload. If the upload doesn't happen the bootloader starts the current sketch.

The `serial.Serial()` command in python opens the USB connection. With that the Arduino is reset and waits in bootloader while you send the data. The data doesn't arrive in your sketch. Add a two seconds wait time after Python's `serial.Serial()`.
> 3 votes

---
Tags: python
---


# Question
Title: How to use -F option while Burn bootloader for ATtiny 85 using Arduino IDE
I'm very new to Arduino. I tried programming Attiny 85 module using Arduino as ISP. It worked fine few times. after that i'm getting below error.

```
Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

```

I understand that i can override this step using -F option. But really cannot figure out how to use -F option in Arduino IDE. Please Help!

# Answer
> 1 votes
For what I know there is no easy way to pass custom options to `avrdude` via the Arduino IDE, but Sloeber (to which I'm a contributor) does.

Beware though, the `-F` option of `avrdude` command doesn't **solve** the problem, just forces to skip the device signature verification, but if your Attiny is returning such signature something else is wrong and you'll end up with a failed firmware upload anyway.

If the device was working and suddenly stopped it's more than probably a wiring issue, as already suggested in the comments. The second most probable cause, in my experience, would be a hardware issue: you might have accumulated some static charge and then touched the Attiny or any wire connected to it, destroying one of the ISP pins...

My bet is on the former: my experience with the latter is you get changing signatures in the form of `0xFFFF00`, `0x0000FF` and `0xFFFFFF` but, luckily for me, this didn't occur so often to accumulate a true knowledge.

---
Tags: attiny85, arduinoisp
---