body: Simply -1 can't be a byte. A byte is a number from 0-255. -1 is below 0. The Arduino reference defines a byte as "A byte stores an 8-bit unsigned number, from 0 to 255.".


sender: user

message:
How to change the default name of ESP8266-12E module

Is there any way to change the default name (ESP_xxxxx) that the module generates?

sender: assistant

body:
This line of code should hopefully do a difference.

    wifi_station_set_hostname(myHostname);

For more information :

https://www.reddit.com/r/esp8266/comments/3zl3pi/change_esp8266_network_name/


body:
Here you are the code where you can see how you can change `network name` of your ESP8266 working in AP mode:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    IPAddress ip(192,168,1,81);         // choose IP address
    IPAddress subnet(255,255,255,0);

    ESP8266WebServer server(80);

    void handleRoot() {
      String page = "<!DOCTYPE html>\n";

      page += "\n\n
Some heading

Generated by ESP8266\n\n";
      server.send(200, "text/html", page);
    }

    // what to do when accessed through http://ip_address/something_undefined
    void handleNotFound(){
      String message = "File not found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET)?"GET":"POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
    }

    void setup(void){
      Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
      WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

      IPAddress myIP = WiFi.softAPIP();
      Serial.println();
      Serial.print("AP IP address: ");
      Serial.println(myIP);

      server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

      // what to do when accessed through http://ip_address/test
      server.on("/test", [](){
        server.send(200, "text/plain", "This is another page");
      });

      server.onNotFound(handleNotFound);

      server.begin();
      Serial.println("HTTP server started...");
    }

    void loop(void){
      server.handleClient();
    }


body: The function is: `WiFi.hostname("Name");`, make sure you call it before `Wifi.begin()`


body: check the Erase Flash>> Tools >> Arduino IDE before uploading your sketch and select erase previous wifi settings


message:
How to I make the Tx and Rx pins on an ESP-8266-01 into GPIO pins?

When programming an ESP-01 with Arduino IDE, how can I make the Tx and Rx into a generic I/O pins reliably? I think there's a command to swap the Tx and Tx with other pins. I  tried `serial.swap()` but it didn't work. So how to get done with Arduino IDE or is it even possible?. I am using an ESP-01, which means there will be four GPIO pins once this question in answered.

I want to achieve same as in the video, [How to add more GPIOs to ESP8266 (ESP-01)][1], but without soldering wire.

  [1]: https://www.youtube.com/watch?v=9RVyWZCSMtA

body:
Tx = GPIO 1

Rx = GPIO 3

Should work but be careful cause if they burn, you won't be able to program or even talk to the ESP anymore.


body:
Maybe a little late but it might helps someone else.

[ESP-01 GPIO pins (1&3)][1]

  [1]: http://www.forward.com.au/pfod/ESP8266/GPIOpins/ESP8266_01_pin_magic.html


body:
Add this to your code at the beginning of set `void setup()`:

    //********** CHANGE PIN FUNCTION  TO GPIO **********
    //GPIO 1 (TX) swap the pin to a GPIO.
    pinMode(1, FUNCTION_3);
    //GPIO 3 (RX) swap the pin to a GPIO.
    pinMode(3, FUNCTION_3);
    //**************************************************

You will no longer be able to use the Serial Monitor as TX will now be a GPIO pin and not transmit Serial data. You can still Flash your device as when you boot the device in flash mode it converts GPIO1 and GPIO3 back to TX/RX. Once you reboot into regular running mode GPIO1 and GPIO3 will go back to being GPIO pins.

To change GPIO1 and GPIO3 back to being TX/RX for regular Serial Monitor use add this to your code at the beginning of set `void setup()`:

    //********** CHANGE PIN FUNCTION  TO TX/RX **********
    //GPIO 1 (TX) swap the pin to a TX.
    pinMode(1, FUNCTION_0);
    //GPIO 3 (RX) swap the pin to a RX.
    pinMode(3, FUNCTION_0);
    //***************************************************

If I understand the ESP-01 correctly the pins CANNOT be both TX/RX and GPIO pins at the same time.


body:
One thing I noticed is that if you're trying to use the Tx/Rx pins for the main serial comm (1 & 3) as a GPIO then you must not use any Serial commands in your code, such as Serial.begin.

I was having my GPIO digital reads randomly read high (they had their mode set as INPUT_PULLUP) while I had a source pulling them low (I verified that input was indeed pulled low while the ESP8266 digitalRead was reading high)

Removing all Serial commands (begin, print and println) fixed that for me.


body: To work TX RX as GPIO Serial.begin() must be deleted from code.


message:
Multiple I2C BREAKOUTS with pull-up resistors doesn't work [UPDATE]

[UPDATE] Now it works fine but the as soon as I add the GY-521 module (hardware not software), it starts sending me crapy info

Project uses:

Arduino Pro Mini as brain

FTDI as a programmer

GY-521 gyro/accel

MPL3115A2 baro/altimeter

DS3231 real time clock

Micro SD card adapter to datalog

The GY-521, MPL3115A2 and the DS3231 uses I2C and they are breakout boards so they include pull-up resistors on the board. Now the GY-521 and the MPL3115A2 works fine together but as soon as I add the DS3231, it all freezzes. My code is fine and I'm sure of that.

Now my theory is that all of those pull-up resistors caused some kind of problem in the circuit. I know that normal I2C require 4.7k ohm pull-up resistors. Now I BELIEVE that the GY-521 uses 4.7k pull-up resistors, the MPL3115A2 uses 10k pull-up resistors and the DS3231 also uses 10k pull-up resistors.

I don't know if this setup could work and I would like to know if I can add some external resistors to calm the whole I2C constellation a bit. Note that I do not want to sodder anything to the breakouts nor do I want to modify them.

Here is the code:

Tab1: MAIN

      //==================================================

    #include <SPI.h>                        //include the SPI library
    #include <SD.h>                         //include the SD card library
    #include <Wire.h>                       //include I2C library
    #include "I2Cdev.h"                     //include another I2C library
    #include "Wire.h"                       //include another I2C library (yes, again)
    #include "MPU6050_6Axis_MotionApps20.h" //include the MPU6050 library
    #include "SparkFunMPL3115A2.h"          //include the MPL3115A2 library
    #include <DS3231.h>                     //include the DS3231 library

    //==================================================

    #define testtest           //*** COMMENT THIS LINE BEFORE UPLOADING OFFICIAL CODE TO FINAL PROJECT ***

    #define chipSelect 10      //pin for the CS/SS
    #define led 2              //led and/or buzzer

    volatile bool mpuInterrupt = false; //just one of those bools

    bool ledState     = false; //state of the led and/or buzzer
    bool dmpReady     = false; //state of the mpu6050

    int yprInt[3];             //gyro data in a integer because the extra precision of the float is total bullshit
    int altitude;              //altitude above takeoff point in meters
    int altitudeCalibration;   //calibration for the altimeter
    int temperature;           //temperature in degrees Celcius

    float counter = 0;         //time counter, a somewhat internal clock that starts when the module starts dataloging

    uint8_t mpuIntStatus;      //holds actual interrupt status byte from MPU
    uint8_t devStatus;         //return status after each device operation (0 = success, !0 = error)
    uint8_t fifoBuffer[64];    //FIFO storage buffer

    uint16_t packetSize;       //expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;        //count of all bytes currently in FIFO

    String day;                //day of the week
    String ymd;                //date: year,month,day
    String hms;                //time: hour,minute,second

    MPU6050 mpu;               //MPU6050 object declaration as mpu
    Quaternion q;              //quaternion container
    VectorFloat gravity;       //gravity vector

    MPL3115A2 myPressure;      //MPL3115A2 object declaration as myPressure
    DS3231  rtc(SDA, SCL);     //DS3231 object declaration as rtc

    //==================================================

    void setup()
    {
      generalSetup();

      gyroSetup();
      baroSetup();

      dataSetup();
    }

    //==================================================

    void loop()
    {
      gyro();      //read angles
      baro();      //read altitude and temperature
      timeClock(); //read day, date, time

      dataPrint();   //serial print the information

      dataLog();   //write data in sd card

      timer();     //time delay and led flash
    }

Tab2: SETUP

    //==================================================

    void generalSetup()
    {
      Serial.begin(115200); //start serial communication
      Wire.begin();         //start I2C communication
      rtc.begin();          //start DS3231

      pinMode(led, OUTPUT); //led or buzzer; used to easily find a lost device
    }

    //==================================================

    void dmpDataReady() {
      mpuInterrupt = true;
    }

    void gyroSetup()
    {
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      TWBR = 24;
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
    #endif
      //while (!Serial);
      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(220);
      mpu.setYGyroOffset(76);
      mpu.setZGyroOffset(-85);
      mpu.setZAccelOffset(1788);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

      else
      {
        return;
      }
    }

    //==================================================

    void baroSetup()
    {
      myPressure.begin();             //start MPL3115A2 communication
      myPressure.setModeAltimeter();
      myPressure.setOversampleRate(7);
      myPressure.enableEventFlags();
      altitudeCalibration = myPressure.readAltitude(); //read altitude
    }

    //==================================================

    void dataSetup()
    {
      if (SD.begin());
    }

    //==================================================

Tab3: FUNCTIONS

    //==================================================

    void gyro()
    {
      float yprFlo[3]; //gyro data in a float

      mpu.resetFIFO();
      mpuInterrupt = false;
      mpuIntStatus = mpu.getIntStatus();
      fifoCount = mpu.getFIFOCount();

      if (mpuIntStatus & 0x02)
      {
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(yprFlo, &q, &gravity);

        for (int i = 0; i < 3; i++)
        {
          yprFlo[i] = yprFlo[i] * 180 / M_PI; //simplify the variable for serial printing and dataloging
        }

        for (int i = 0; i < 3; i++)
        {
          yprInt[i] = yprFlo[i]; //changing the variable from a float to a int
        }
      }
    }

    //==================================================

    void baro()
    {
      altitude = myPressure.readAltitude() - altitudeCalibration; //read altitude
      temperature = myPressure.readTemp();  //read temperature
    }

    //==================================================

    void dataPrint() //serial print all the data
    {
      Serial.print(day);
      Serial.print(" ");
      Serial.print(ymd);
      Serial.print(" -- ");
      Serial.print(hms);
      Serial.print(", ");
      Serial.print(counter);
      Serial.print(", ");
      Serial.print(yprInt[0]);
      Serial.print(", ");
      Serial.print(yprInt[1]);
      Serial.print(", ");
      Serial.print(yprInt[2]);
      Serial.print(", ");
      Serial.print(altitude);
      Serial.print(" ,");
      Serial.print(temperature);
      Serial.println();
    }

    //==================================================

    void dataLog()//wirte all the data in a note file on the sd card
    {
      if (altitude > 1) //if the device is higher then 1m, then we sstart recording everything
      {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile)
        {
          dataFile.print(day);
          dataFile.print(" ");
          dataFile.print(ymd);
          dataFile.print(" -- ");
          dataFile.print(hms);
          dataFile.print(", ");
          dataFile.print(counter);
          dataFile.print(", ");
          dataFile.print(yprInt[0]);
          dataFile.print(", ");
          dataFile.print(yprInt[1]);
          dataFile.print(", ");
          dataFile.print(yprInt[2]);
          dataFile.print(", ");
          dataFile.print(altitude);
          dataFile.print(" ,");
          dataFile.print(temperature);
          dataFile.println();
          dataFile.close();
        }
      }
    }

    //==================================================

    void timeClock()
    {
      day = rtc.getDOWStr();
      ymd = rtc.getDateStr();
      hms = rtc.getTimeStr();
    }

    //==================================================

    void timer()
    {
      counter = counter + 0.5;

      #ifndef testtest
      ledState = !ledState;
      digitalWrite(led, ledState);
      #endif

      delay(500);
    }

    //==================================================

body:
According to my calculations the total pull-up is:

    1 / (1/10 + 1/10 + 1/4.7) = 2.423 k

As I show on [my page about I2C](http://www.gammon.com.au/i2c) a 2.2 k pull-up resistor gives a reasonably good signal:

[![2.2k pullup][1]][1]

Thus I don't think the resistors are the issue. And I don't see how adding more would "calm the whole I2C constellation a bit".

  [1]: https://i.stack.imgur.com/4gbW0.png


body:
In fact the MPU-6050 on the GY521 and the DS3231 both use I2C address 0x68.  Had you looked at the source of the header files you included for each, this would have been apparent.

By consulting the data sheet for each chip you will likely find a way to either change the I2C address by changing a configuration pin, or else to potentially enable/disable the chip by changing one with a GPIO.  This will, however, likely require surgical modification of the carrier board.

You could also move whichever device you expect to access least to a distinct "soft" I2C bus bit-banged on other GPIO pins. No endorsment is implied, but the the first such library that came up in a web search was:

http://playground.arduino.cc/Main/SoftwareI2CLibrary

you can likely find other options for yourself, or can potentially create your own.

There are also other chips in the family of the MPU-6050 which speak SPI instead of or as well as I2C, however these tend to be more expensive.


body: When additional resistors are added in parallel, which is what is going on when you add new I2C devices to the I2C bus, the overall resistor is lowered. This could cause a problem with devices that cannot provide enough current with a low pull-up resistance. Hence, the device will not function well when the pull-up resistance is lower than a specific value. To fix the problem, I recommend removing all parallel pull-up resistors and just keep one at each line to achieve a good resistor value of approximately 4.7 k-ohms.


message:
How to extend my Sketch for Multiple Inputs and Outputs

I am using  4 Push Buttons and 4 leds in my project. Here the sketch is only for one push button and one Led. I want extend my sketch upto 4 push buttons and 4 leds .Please tell what changes I make in my sketch. Please any body can make changes in my sketch.
here is sketch:

    const int buttonPin =2;    // the number of the pushbutton pin
    const int ledPin = 13;      // the number of the LED pin

    // Variables will change:
    int ledState = HIGH;         // the current state of the output pin
    int buttonState;             // the current reading from the input pin
    int lastButtonState = LOW;   // the previous reading from the input pin
    long lastDebounceTime = 0;  // the last time the output pin was toggled
    long debounceDelay = 50;

    void setup() {
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, ledState);
    }

    void loop() {
      int reading = digitalRead(buttonPin);
      if (reading != lastButtonState) {
        // reset the debouncing timer
        lastDebounceTime = millis();
      }

      if ((millis() - lastDebounceTime) > debounceDelay) {
        // whatever the reading is at, it's been there for longer
        // than the debounce delay, so take it as the actual current state:

        // if the button state has changed:
        if (reading != buttonState) {
          buttonState = reading;

          // only toggle the LED if the new button state is HIGH
          if (buttonState == HIGH) {
            ledState = !ledState;
          }
        }
      }

      // set the LED:
      digitalWrite(ledPin, ledState);
      lastButtonState = reading;
    }

body:
I'll show you the long but simple way. Just follow this logic in your setup and loop and you'll be ok. If you still don't understand and want more, tell me and I'll add more code for you.

Do something like this:

    const int buttonPin1 = 2;    // the pin the button is connected to
    const int buttonPin2 = 3;
    const int buttonPin3 = 4;
    const int buttonPin4 = 5;

    const int ledPin = 6;        // the pin the led is connected to
    const int ledPin = 7;
    const int ledPin = 8;
    const int ledPin = 9;

    int ledState1 = HIGH;         // the current state of the output pin
    int buttonState1;             // the current reading from the input pin
    int lastButtonState1 = LOW;   // the previous reading from the input pin
    long lastDebounceTime1 = 0;  // the last time the output pin was toggled
    long debounceDelay1 = 50;

    int ledState2 = HIGH;         // the current state of the output pin
    int buttonState2;             // the current reading from the input pin
    int lastButtonState2 = LOW;   // the previous reading from the input pin
    long lastDebounceTime2 = 0;  // the last time the output pin was toggled
    long debounceDelay2 = 50;

    int ledState3 = HIGH;         // the current state of the output pin
    int buttonState3;             // the current reading from the input pin
    int lastButtonState3 = LOW;   // the previous reading from the input pin
    long lastDebounceTime3 = 0;  // the last time the output pin was toggled
    long debounceDelay3 = 50;

    int ledState4 = HIGH;         // the current state of the output pin
    int buttonState4;             // the current reading from the input pin
    int lastButtonState4 = LOW;   // the previous reading from the input pin
    long lastDebounceTime4 = 0;  // the last time the output pin was toggled
    long debounceDelay4 = 50;


message:
Arduino Mega 2560 and Android USB OTG serial communication

currently I am building a little project based on the Arduino Mega 2560.
My goal is to send some data gathered by some sensors to an Android phone.
It has to be as basic as possible.
Buying new hardware is no option.

After some research, I found that it is possible to communicate via USB OTG just with Serial commands.
I downloaded the an app which can do this (Serial Monitor), connected the Arduino via the USB cable to the Android.
Unfortunately, it did not work.

I have an Arduino UNO, too.
Connecting the UNO the same way to the phone works like a charm and does exactly what I want.

I did some more research and found nothing about that.
It seems that everybody is using the Arduino Mega ADK to establish a communication between Arduino and Android.
But I would like to be able to achieve this the same way it works with the UNO.

Can somebody explain me why it does not work?

**EDIT**
Here is the code I have to test:

*Arduino*

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

    void loop() {
      Serial.println("Test...");
      delay(2000);
    }

For Android I use the code [from this tutorial](http://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/).

Any further suggestions?

body:
So I figured it out.

It was the VendorID. I found it and noticed, that the VIDs of the UNO and Mega are different.
I adjusted the code and now everything works as I expect.
So, thank you Chris Startton for the correct hints.

Thank you all.


message:
Transmitting Variables over RF

I'm using the 3715 RF arduino modules and a hc-sr04, and i'm trying to send the distance i get from the ultrasonic over to the arduino with the rf recieving module but i get something like this: [![enter image description here][1]][1]

Instead of getting this:[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/K3LII.png
  [2]: https://i.stack.imgur.com/MqjxQ.png
Here are the code snippets for each arduino:

Arduino TX:

    #include <VirtualWire.h>

    const int led_pin = 11;
    const int transmit_pin = 12;
    const int receive_pin = 2;
    const int transmit_en_pin = 3;
    long distance;
    long time1;
    void setup()
    {
       // Initialise the IO and ISR
       Serial.begin(9600);
       pinMode(9, OUTPUT);
       pinMode(8, INPUT);
       vw_set_tx_pin(transmit_pin);
       vw_set_rx_pin(receive_pin);
       vw_set_ptt_pin(transmit_en_pin);
       vw_set_ptt_inverted(true); // Required for DR3100
       vw_setup(2000);   // Bits per sec
    }

    byte count = 1;

    void loop()
    {
       digitalWrite(9,LOW);
       delayMicroseconds(5);
       digitalWrite(9, HIGH);
       delayMicroseconds(10);
       time1=pulseIn(8, HIGH);
       distance= int(0.017*time1);
       Serial.println("Distance ");
       Serial.println(distance);
       Serial.println(" cm");
       delay(1000);
       char msg[1] = {distance};

       msg[0] = count;
       digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
       vw_send((uint8_t *)msg, 3);
       vw_wait_tx(); // Wait until the whole message is gone
       digitalWrite(led_pin, LOW);
       delay(1000);

    }

Arduino RX:

    #include <VirtualWire.h>

    const int led_pin = 6;
    const int transmit_pin = 12;
    const int receive_pin = 11;
    const int transmit_en_pin = 3;

    void setup()
    {
       delay(1000);
       Serial.begin(9600);  // Debugging only
       Serial.println("setup");

       // Initialise the IO and ISR
       vw_set_tx_pin(transmit_pin);
       vw_set_rx_pin(receive_pin);
       vw_set_ptt_pin(transmit_en_pin);
       vw_set_ptt_inverted(true); // Required for DR3100
       vw_setup(2000);  // Bits per sec

       vw_rx_start();       // Start the receiver PLL running
    }

    void loop()
    {
       uint8_t buf[VW_MAX_MESSAGE_LEN];
       uint8_t buflen = VW_MAX_MESSAGE_LEN;

       if (vw_get_message(buf, &buflen)) // Non-blocking
       {
          int i;

          digitalWrite(led_pin, HIGH); // Flash a light to show received good message
          // Message with a good checksum received, print it.
          Serial.print("Got: ");

          for (i = 0; i < buflen; i++)
          {
             Serial.print(buf[i], HEX);
             Serial.print(' ');
          }
          Serial.println();
          digitalWrite(led_pin, LOW);
       }
    }

I'm open for pointers as i'm pretty much a noob at this, thank you very much for your help! :)

body:
It looks like you're sending only one byte, but expecting to receive three.
In the TX sketch, `char msg[1] = {distance};` declares an array of one char, assigns its zero-th element the value of distance. Then `msg[0] = count;` over-writes it with the value of count. `vw_send((uint8_t *)msg, 3);` tries to send three bytes but only the first one has been defined. The second and third bytes transmitted are outside of the 1-length array.

You need something more like:

    vw_send(distance, sizeof(distance));

on the TX side, and:

    long distance;
    uint8_t count;

    vw_get_message(distance, &count));
    Serial.println(distance);

on the RX side. You must receive the count into a variable but can ignore it, on the RX side; you know you'll be receiving a `long`; though good defensive coding would check the value anyway.


body:
If you only need to display the value at the other end rather than do any calculations on it then it's nicer to send it as text rather than a number.

Sending:

       char msg[10]; // bigger than it needs to be to avoid overflow issues

       int length = sprintf(msg,"%ld",distance); // convert value to ascii
       digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
       vw_send((uint8_t *)msg, length + 1); // send value (add 1 to length to include the string terminator)

       vw_wait_tx(); // Wait until the whole message is gone
       digitalWrite(led_pin, LOW);
       delay(1000);

Since the data sent over the radio is now a standard c string complete with null terminator the receiving code becomes:

    if (vw_get_message(buf, &buflen)) { // Non-blocking
      int i;

      digitalWrite(led_pin, HIGH); // Flash a light to show received good message
      // Message with a good checksum received, print it.
      Serial.print("Got: ");
      Serial.print(buf);
      Serial.println();
      digitalWrite(led_pin, LOW);
    }

This is making the assumption that the whole thing is sent in a single radio packet, if the vw_get_message doesn't return the entire message in one go then nasty things will happen. You could always check for this be ensuring that `strlen(buf)` returns one less than `buflen` since buflen should include the null terminator but `strlen()` won't


message:
Using Atmel Studio with Arduino Starter Kit (Uno MCU)

Can someone tell me if it's possible AND safe to use Atmel Studio with Arduino Starter Kit?  I'm a newbie to firmware in general and I don't want to "brick" my Arduino Uno Microcontroller.  I don't quite know if the micro controller has been programmed in read only or special memory to make it Arduino compatible and me messing with Atmel Studio could mess it up.  In other words, I want to know I can get back to programming through the Arduino IDE and continue working on the projects in the starter kit book.  I've done about half of them.

1)  Can someone tell me if it's doable, safe and WHY?
2)  Any hints or gotchas or examples on how to do it?

My motivation is that I'm taking a job as a C# Windows programmer but will be exposed (I believe) to AVR and Atmel Studio and wanted to get familiar with it by just playing a little bit.  Arduino libraries seems to hide a lot of the messy details (such as setting a pin output) which is fine, but it would probably be good to do those messy details myself and be familiar with the actual tools they will use at work.

I have searched for a "tutorial for dummies" that says what settings to pick, etc. to no avail.

Thanks Dave

P.S.  If the answer is NO WAY is it safe or desirable, perhaps a recommendation for an AVR development kit (cheaper is better!).  Actually, this is probably not a bad idea anyhow.
Many Thanks!

body:
There are many tutorials on programming Arduino boards (or any other AVR MCU) with Atmel Studio:

Creating new project:
https://asensar.com/blog/2013/how-to-setup-atmel-studio-for-arduino-development/

Configuring Avrdude for firmware upload:
https://asensar.com/blog/2013/how-to-integrate-avrdude-with-atmel-studio/
http://www.instructables.com/id/How-to-Load-Programs-to-an-Arduino-UNO-From-Atmel-/

Please see this post too:
https://arduino.stackexchange.com/questions/21980/atmel-studio-7-my-own-libraries/21985

Nothing to afraid of, just don't mess with lock fuses (relevant only if you decide to play with ISP programmer and arvdude/avrdudess). Use Arduino USB virtual COM port connection for firmware uploading, just like in Arduino IDE.

With Atmel Studio you don't have rich libraries available like in Arduino platform, instead you will have to program MCU, its peripherals (and other devices connected, if any) by directly accessing MCU registers. This requires some knowledge on MCU hardware (but it is a natural choice if you want to learn that). Eventually you can build your own wrapper libraries similar to one in Arduino.

Check Procyon AVR library too - much better choice than digging Arduino library sources (a bit old but still relevant, I always recommend it as a starting point for AVR library development:)
http://www.procyonengineering.com/embedded/avr/avrlib/


message:
W5100 Ethernet Shield to Custom Board Problem

I've been using an Arduino Ethernet shield and an Arduino Mega in my project, but now I'm trying to migrate all the components onto my own PCB. My board uses a W5100 same as the Arduino, but nothing shows up when I connect Ethernet to my computer. Even if there is no communication with the MCU the W5100 should show up as a network device and starting pinging.

I have spent A LOT of time troubleshooting this issue, and I would like to confirm one thing. Using the factory default register settings, I should be able to just connect the W5100 to my computer, and it will start pinging back and forth and be identified as a network device . . . assuming I have the circuit set up correctly just like the Ethernet shield. I used a combination of the recommendations from Wiznet and the Arduino Ethernet shield schematic to make mine.

Edit:
Here is my schematic for the Ethernet module. The question I'm really trying to get answered first is regarding the default state of the W5100. Do I need to set some registers or something to get the W5100 in the same state it is in on the Arduino shield?
[![Ethernet Schematic][1]][1]

  [1]: https://i.stack.imgur.com/K2uI8.png

body:
You need to connect the SCS pin of W5100 to Arduino mega 2560 PB4 pin (pin number 23 raw IC pin number). Then only the W5100 will be selected in active mode.
for reference: https://www.arduino.cc/en/Reference/Ethernet
"Arduino communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. **On both boards, pin 10 is used as SS.** **On the Mega, the hardware SS pin, 53, is not used to select the W5100,** but it must be kept as an output or the SPI interface won't work."


body:
A bit late to the party but... it may be that you are using pins 1, 2, 3 and 4 instead of 1, 2, 3 and 6 on the RJ45. It is unclear whether you are connecting via a header, in which case you my disregard this, or straight to the RJ45, in which case you need to change your pin:

    1. white/orange
    2. orange
    3. white/green
    6. green


message:
Smooth servo control library

Is anyone aware of an Arduino library for smoothly controlling a servo?

I have an especially fast servo, which is trivial to control using Arduino's built-in Servo library. However, the library doesn't support proportional control. You specify a position, and the servo immediately goes to that position as fast as it can. With my servo, that creates incredibly fast jerky motion.

I've found some algorithms for interpolating a smooth servo motion by generating small incremental changes to the signal over time. I've been able to translate this to some Arduino code, and although the motion is much slower, it's still very jittery.

I've search for pure Arduino implementations, but I've not found anything. Does anyone know of an implementation? I find it hard to believe no one else has faced this type of servo control problem with an Arduino before.

body:
Infortunately, I did not find any library but I found that the method shown below could work quite well for small projects. By adding a small delay, it helps the servo run a little smoother. It is not really ideal but it should work if your goal is to minimize the roughness of the servo.

Also by adding a 100uF capacitor between 5V and GND, the capacitor will help calm the sudden rush you might get when the servo first starts to turn. That rush is caused by the servo asking for more current when the servo is not moving.

    #include <Servo.h>   //servo library
    Servo myservo;       //servo object
    int previousAngle = 0;

    const int potPin = A3; //sensor pin

    void setup() {
      myservo.attach(9);  //data pin of the servo
      pinMode(potPin, INPUT); //sensor pin as an input
    }

    void loop() {
      int val = analogRead(potPin);
      int angle = map(val, 0, 1023, 0, 180);

      if(angle>previousAngle)
      {
        for(int i=previousAngle; i<=angle; i++)
        {
          myservo.write(i); //turn servo by 1 degrees
          delay(10);        //delay for smoothness
        }
      }

      if(angle<previousAngle)
      {
        for(int i=previousAngle; i>=angle; i--)
        {
          myservo.write(i); //turn servo by 1 degrees
          delay(10);        //delay for smoothness
        }
      }

      previousAngle = angle;
    }


body:
After searching via a different angle (using "easing" as a keyword), I found this [excellent library][1]. Apparently this task is more commonly known as "servo easing", not smoothing. I've tested it with a hobby servo, and it does exactly what I was looking for.

  [1]: https://github.com/todbot/ServoEaser


body:
Searching the net for smooth servo movement I found this entry one year ago.

In the end I built a new library for this task called [ServoEasing][1].

  [1]: https://github.com/ArminJo/ServoEasing


message:
lcd has no contrast pin

i just bought [this lcd][1]. I connected all pins as discripted on [this datasheet][2] (Page 8). However i noticed that there is no pin to control the contrast. I also didin't get the display to run yet.

Might that be a problem?

edit: here is the code...

    #define RST 3
    #define CE 2
    #define DC 4
    #define DIN 6
    #define CLK 5

    void LcdWriteCmd(byte cmd)
    {
    digitalWrite(DC, HIGH); //DC pin is low for commands
    digitalWrite(CE, HIGH);
    shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
    digitalWrite(CE, LOW);
    }

    void setup()
    {
    pinMode(RST, OUTPUT);
    pinMode(CE, OUTPUT);
    pinMode(DC, OUTPUT);
    pinMode(DIN, OUTPUT);
    pinMode(CLK, OUTPUT);
    digitalWrite(RST, LOW);
    digitalWrite(RST, HIGH);
    LcdWriteCmd(0xAE); // LCD set display enabled
    LcdWriteCmd(0x21); // LCD set power COntrol
    LcdWriteCmd(0x14); // LCD bias mode 1:40
    LcdWriteCmd(0xA2); // LCD basic commands
    // LcdWriteCmd(0xA9); // LCD all segments on
    }

    void loop()
    {
    }

  [1]: http://www.buydisplay.com/default/blue-2-8-inch-128x64-display-serial-lcd-module-spi-with-touch-panel
  [2]: http://www.buydisplay.com/download/manual/ERC12864-655_Series_Datasheet.pdf

body:
I think your commands are a little wrong. Let's look at them:

    LcdWriteCmd(0xAE); // LCD set display enabled

0xAE is 0b10101110. In the datasheet the matching command is `1010111#` where `#` is display on (1) or off (0), so 0xAE is actually display *disabled*. Changing it to 0xAF instead, so bit 0 is 1, should enable the display.

    LcdWriteCmd(0x21); // LCD set power COntrol

0x21 is 0b00100001. That command is `00100###` where `###` is the VLCD resistor ratio. That is being set to 2/8. ((`#` + 1) / 8).

    LcdWriteCmd(0x14); // LCD bias mode 1:40

0x14 is 0b00010100, which is command `0001####` which sets the column address MSB. Quite why you're doing that I don't know, but that command has nothing to do with bias mode...

    LcdWriteCmd(0xA2); // LCD basic commands

No, 0xA2 / 0xA3 sets the bias ratio set, which selects the bias from one of two groups of biases depending on the current duty. This is the default value.

So not only are you not configuring the screen correctly, but you aren't even then trying to put anything on the screen to see if it's working or not.

I suggest you work from the provided example code:

* http://www.buydisplay.com/download/democode/ERC12864-655_DemoCode.txt

The "Initial" function sets the sequence of operations:

    SET_ADC();
    CLEAR_SHL();
    CLEAR_BIAS();
    Power_Control(0x07);
    Regulor_Resistor_Select(0x06);
    Set_Contrast_Control_Register(Contrast_level);
 Initial_Dispay_Line(0x00);
 DISPLAY_ON();

The main commands are defined at the top of the file:

    #define DISPLAY_ON()           Write_Instruction(0xaf)   //  Display on
    #define DISPLAY_OFF()          Write_Instruction(0xae)   //  Display off
    #define SET_ADC()              Write_Instruction(0xa1)   //  Reverse disrect (SEG131-SEG0)
    #define CLEAR_ADC()            Write_Instruction(0xa0)   //  Normal disrect (SEG0-SEG131)
    #define REVERSE_DISPLAY_ON()   Write_Instruction(0xa7)   //  Reverse display : 0 illuminated
    #define REVERSE_DISPLAY_OFF()  Write_Instruction(0xa6)   //  Normal display : 1 illuminated
    #define ENTIRE_DISPLAY_ON()    Write_Instruction(0xa5)   //  Entire dislay   Force whole LCD point
    #define ENTIRE_DISPLAY_OFF()   Write_Instruction(0xa4)   //  Normal display
    #define SET_BIAS()             Write_Instruction(0xa3)   //  bias 1   1/7 bais
    #define CLEAR_BIAS()           Write_Instruction(0xa2)   //  bias 0   1/9 bais
    #define RESET()                Write_Instruction(0xe2) //   system reset
    #define SET_SHL()              Write_Instruction(0xc8)   // SHL 1,COM63-COM0
    #define CLEAR_SHL()            Write_Instruction(0xc0)   // SHL 0,COM0-COM63

The more complex ones are simple enough - just ORing the provided parameter with the base command. For example `Power_Control()` just does:

    Write_Instruction((0x28|vol));

I am sure you can find (and decipher) the rest of the commands to initialize the screen properly.


message:
Arduino char showing as 2 characters

I'm writing the character `1` from a node.js XBee using the code `sp.write("1");` to my Arduino's XBee. Then on my Arduino's XBee I read it like this (inside a loop):

      if (XBee.available()) {
        do {
          r = XBee.read();
          Serial.print(r);
        }
        while (r != -1);

And the input char `r` shows up as `1�` instead of just `1`. Why is this and how can I remove the added invalid character from the char? Also is this char now 2 chars, how does this work? Thanks.

EDIT:

Arduino code:

    #include <SoftwareSerial.h>

    // Global variables
    int AnalogPin = A2; // has much less jumpy readings than A0 (maybe A0 slightly damage from overuse)
    int ledPin = 13;
    SoftwareSerial XBee(2,3); // RX, TX

    // Setup
    void setup() {
      Serial.begin(9600);
      pinMode(AnalogPin, INPUT);
      XBee.begin(9600);
      for (int i=0; i<100; i++)
        Serial.print("\n");
      // Random ID
      Serial.println("Listening...");
    }

    // MAIN LOOP
    void loop() {
      char r;
      // Allow data reception while waiting for handshake confirmation
      while (1) {
          if (XBee.available()) {
            do {
              r = XBee.read();
              Serial.println(r);
            }
            while (r != -1);
          }
          delay(500);
            if (r == 'Q') {
              Serial.println(r);
              Serial.println();
              Serial.println("Turning LED OFF.");
              digitalWrite(ledPin, LOW);
              Serial.println();
              exit(1);
            }
           else if (r == '1') {
              Serial.println(r);
              Serial.println();
              Serial.println("Turning LED on.");
              digitalWrite(ledPin, HIGH);
              Serial.println();
            }
      }
    } // end main loop

Node code:

    var SerialPort = require('serialport');
    var express = require('express');
    app = express();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var ON_DEATH = require('death');

     /* ------------- Connecting to Serial Port ---------------- */
     var portName = '/dev/cu.usbserial-AD01SSII',
     portConfig = {
      baudRate: 9600,
     };

     var sp;
     sp = new SerialPort(portName, portConfig);
     sp.on("open", function (err) {

      console.log("Sending LED on signal.");
      console.log("Ctrl+C: quit and send LED off signal.");
      sp.write('1');

      // Cleanup when termination signals are sent to process
      ON_DEATH(function(signal, err) {
       var death_msg = 'Q';
       sp.write(death_msg);
       sp.close();
       console.log("\n\nSending reset signal to nodes.\n\n")
       process.exit();
      })
    */
      }); // end open

All I'm really trying to do here is turn an LED on and off when I start or end the node program. Maybe I'm just too exhausted to think straight.

body:
<!-- language: lang-c++ -->

     do {
          r = XBee.read();
          Serial.print(r);
        }
        while (r != -1);

Think about it. Since you tested for `XBee.available()` you will have at least one iteration of this loop. And then you do a *second* read, **and** print it, before finding that the second character is -1.

You need to re-order your loop, or your tests. The second character will be what -1 looks like on your monitor.

---

A better loop would be:

<!-- language: lang-c++ -->

      while (XBee.available()) {
          r = XBee.read();
          Serial.println(r);
      }

This is the standard way of looping and reading. You won't get -1 from the read here, because if something is available, you will get that something.


message:
Write PWM with only 8 bit? (Timer2)

I have a problem with the Servo library.

I need to read a PPM signal and create a PWM signal of each channel. The problem is that PPM has a higher resolution than PWM so I want to use the 16 bit Timer1 for reading PPM. However the Servo library that writes the PWM signal also uses Timer1.

Is it possible to generate a PWM signal with 8 bit / Timer2? And has someone made an example, or an explanation about, how to do that?

body:
Yes, Arduino [Servo library][1] uses Timer1 (and other ones, [depending on Arduino boards][2]) to manage FastPWM via software interrupts. Timer2 is used by tone() function: be careful if you are using that function.

A good **example using Timer2** to generate PWM is the **[Infrared remote library for Arduino][3]**. If IR_USE_TIMER2 is defined it will use Timer2. The key code is at [IRremote.cpp][4] where the ISR is managed.

  [1]: https://www.arduino.cc/en/reference/servo
  [2]: https://github.com/arduino/Arduino/blob/ide-1.5.x/libraries/Servo/src/avr/ServoTimers.h
  [3]: https://github.com/z3t0/Arduino-IRremote
  [4]: https://github.com/z3t0/Arduino-IRremote/blob/master/IRremote.cpp


body:
> Is it possible to generate a PWM signal with 8 bit / Timer2?

yes. I implemented multiple approaches, some on avrs and some on pics but the basic principles are the same: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

that post provided a list of links to other implementations - one of them off a timer 2 on avr.


body:
Here is a simple example from [my page about timers](http://www.gammon.com.au/timers) of using Timer 2 to output a square wave of 50 kHz:

<!-- language-all: lang-C++ -->

    const byte LED = 3;  // Timer 2 "B" output: OC2B

    const long frequency = 50000L;  // Hz

    void setup()
     {
      pinMode (LED, OUTPUT);

      TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2B on compare
      TCCR2B = bit (WGM22) | bit (CS21);         // fast PWM, prescaler of 8
      OCR2A =  ((F_CPU / 8) / frequency) - 1;    // zero relative
      OCR2B = ((OCR2A + 1) / 2) - 1;             // 50% duty cycle
      }  // end of setup

    void loop()
      {
      // do other stuff here
      }


message:
Can I use string and int in Serial.println together?

I just yesterday started programming on Arduino, and I have a little problem.

I want to print `"#S|SKAITYMAS|[1]#"` in one line, except instead of `"1"` I would like to use an int value. However, this one doesn't work:

`Serial.println ("#S|SKAITYMAS|[",LINENR,"]#");`

Any hint or tips would be appreciated.

body:
Do something like this:

Start with your string and integer:

    String string = "PI is equal to ";
    int integer   = 3.1416;

Then put this in your loop:

    Serial.print(string);  //string here
    Serial.print(integer); //int here

    Serial.println();      //change line

Serial.print() doesn't change line. Its Serial.println() which is the print that changes line so everything that is printed without println will be on the same line.


body:
The answer by canadiancyborg is fine. However, it is always better to avoid using String objects if at all possible, because they use dynamic memory allocation, which carries some risk of memory fragmentation. Simple and safe:

    int answer = 42;
    Serial.print("The answer is ");
    Serial.println(answer);

The only drawback is that the constant string ("The answer is ") takes some RAM. This can be avoided by embedding it in the `F()` macro, which means “keep this in Flash memory only”. Then, the most memory-friendly idiom is:

    int answer = 42;
    Serial.print(F("The answer is "));
    Serial.println(answer);


message:
SIM800 gsm Module returns 0 on AT+COPS?

I am using SIM800 Module with Arduino Micro. It reponds well to basic AT commands. But i am unable to send SMS from this module as:

AT+CMGF=1 ERROR

Now while further debugging i saw AT+COPS? Returns 0, means not connected to any operator. That may be causing the CMGF failure. But my AT+COPS=? returns multiple operator. I have an Airtel working sim. Intialyy it was showing AIRTEL too in AT+COPS=? but not now.. anything to do with signal??

AT+COPS?

+COPS: 0

OK AT+COPS=?

+COPS: (2,"405800","405800","405800"),(1," IDEA CELLULAR Ltd","IDEA","40404"),(1,"40505","40505","40505"),,(0-4),(0-2)

What is going wrong here. any inputs?

body:
1- Do you even a proprely working SIM card? Test it with your phone by calling or texting someone with it.

2- Try putting your SIM card into your phone and unlock the SIM card. This function is usualy in the setting area of your smartphone. It will make it easier later on.

3- As always, reboot your PC and try again.


body:
It can take a while for a modem to register on the network - sometimes several minutes.

Turning on CREG URCs can help you monitor what is happening:

    AT+CREG=1

You should now start getting `+CREG` notifications as the network status changes.

Before using `AT+COPS?` you should really select a reporting mode so you know what you are looking at. I prefer numeric, since it's easier to parse:

    AT+COPS=0,2

That will switch to automatic registration and reporting as numbers.

    AT+COPS?
    +COPS: 0
    OK

That is not registered.

    AT+COPS?
    +COPS: 0,2,"40404"
    OK

That is registered on a network with ID 40404.

The +CREG reports tell you what is going on:

    +CREG: 1

That tells you that you have just connected to your home network.

If you are roaming, you would see:

    +CREG: 5

Of course, if your home network is not available (say you have an AT&T SIM and only Verizon is visible at the moment), and your SIM doesn't have roaming enabled, then registration will never work.  You'd expect to see +CREG reports of:

    +CREG: 2
    +CREG: 3
    +CREG: 0

That is "trying to register" (2), "registration denied" (3) and "doing nothing much now" (0).

The best document for learning about these commands is the [3GPP Command Set](http://www.etsi.org/deliver/etsi_ts/127000_127099/127007/10.03.00_60/ts_127007v100300p.pdf) which is the standard that all modern GPRS modems should adhere to.


body:
If you are using [linear voltage regulator][1] such as LM7805 or LM317, then definitely you need to replace with buck converter.  Since the dropout at max current 1.5A is 1.8V.

Pls check the module voltage level using AT+CBC. If the voltage dropped less than 3.3V then module would keep restarts.  Hence recommended voltage level for sim800 series is 3.7 - 4.4v. In that case you need a proper power supply. Try buck converter which has 3A rating and less dropout voltage too.

You can refer my study on my blog..
http://vimtron.blogspot.in/2017/10/gsm-sim800l-and-arduino-mega-2560.html

  [1]: https://www.elprocus.com/adjustable-lm317-voltage-regulator-circuit/


message:
Do ISRs have to be defined in top level Arduino program?

I'm currently attempting to implement some interrupts on an Arduino project. Looking through some of the examples, it appears that all the ISRs are defined in the top level Arduino program. I'm organizing my project by C++ classes and namespaces, so I'm curious, is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++  namespace? This question has been spawned primarily for organizational purposes.

Otherwise, I could always just use a #include to import a file that defines the ISR such that they're imported to the top level.

Thanks!

body:
Why don't you try it and see?

> is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++ namespace?

Yes. Example here:

    const byte LED = 13;
    const byte BUTTON = 2;

    namespace foo
      {
      // Interrupt Service Routine (ISR)
      void switchPressed ()
        {
        if (digitalRead (BUTTON) == HIGH)
          digitalWrite (LED, HIGH);
        else
          digitalWrite (LED, LOW);
        }  // end of switchPressed
      }  // end of namespace foo

    void setup ()
    {
      pinMode (LED, OUTPUT);  // so we can update the LED
      digitalWrite (BUTTON, HIGH);  // internal pull-up resistor
      attachInterrupt (0, foo::switchPressed, CHANGE);  // attach interrupt handler
    }  // end of setup

    void loop ()
    {
      // loop doing nothing
    }

I put the ISR in the namespace "foo" and it compiled OK.


message:
Sensor for detect there is a car or not ?

please I'm aiming to do a project for parking system but first of thing I need a sensor to detect there is a car or not other than ultrasonic sensor ..

please any one know any kind of those sensors ? pressure sensor or normal sensor ?

body:
Ideas and concepts you could use:

1 - Laser tripwire - acts like a laser security system. If the beam is broken, then you car is there. Put a laser on one side of your garage and a photocell and the other and read its value.

2 - photocell under the car - if the area is always lit, you might be able to put a photocell below the parking spot. Then when your car is on the photocell, it return a different value then when there is nothing.

3 - pressure/weight sensor - both will detect the presence of a heavy object on them.

Hope those ideas hepled you!


message:
Questions about the Arduino Micro PCB

I'm planning on integrating an Arduino Micro in the circuit of a small project of mine (USB gamepad). The whole thing will use USB for power and data transfer (between the board and the computer). Before I move on with prototyping, I need to clear up some questions I have about the Arduino Micro schematic (picture included for reference):

* Since I'll be powering off of USB, I won't the 5 and 3.3 V regulators or the 5 V Selector (top-right in picture). Am I correct?
* For the USB Micro header, does the schematic refer to any particular header (doesn't seem so to me), or will any generic one work? And what are the six pins on the right side (SH1/S1, SH2/S2, SH3/S3, SH4/S4, SH5/S5, SH6/S6)? What do they do? What are they used for? I found the pins on the left (VBUS, D-, D+, ID, GND) on generic USB Micro headers, but I did not find the pins on the right.
* Out of curiosity, what do the asterisks in the schematic mean? You can see them all over; for example, look at the top-right of the MCU.
* What do the circle and the smaller circle (with an X through it) towards the bottom-right mean?

![arduino_micro_schematic](https://i.stack.imgur.com/yW7TG.jpg)

body:
The 5V regulator is only used when you are powering from external power (>5V). The 3.3V regulator is only used by things that you power from the 3.3V pin on the Micro.

So if you aren't using external power you don't need the 5V regulator. If you aren't using any 3.3V devices then you don't need the 3.3V regulator.

You can use any micro USB or even mini USB connector you like. If you ignore the "ID" pin you can even use an old-fashioned chunky USB B connector like on the Uno.

The circles are *[fiducial markers](https://en.wikipedia.org/wiki/Fiducial_marker#Printed_Circuit_Board_.28PCB.29)* and are special patterns on the board used for aligning a pick-and-place machine when manufacturing.


body:
Let's keep it simple. If you are using USB to power it all, connect the power supply to 5V. The 5V regulator is used to regulate the VIN voltage. The 3.3V regulator is only used to power the 3.3V pin.

USB micro is a type of header. Any common USB micro that you get from a local supplier of EBAY/AMAZON will work.

The asterix and the circle with and without the X are problably markers used by Arduino in there schematic. Don't worry about them.


body:
>•  “... powering off of USB, I won't [need] the 5 and 3.3 V regulators or the 5 V Selector ...”

True, except that some of those parts maintain circuit continuity.  For example, when USB power is used, its current passes through the T1 P-mosfet.  For explanation of the power selector circuit, see for example *[usage of bidirectional mosfet](https://electronics.stackexchange.com/q/140020)* in electronics.stackexchange, or *[arduino power supply selector](http://www.engineeredentropy.com/2013/01/arduino-power-supply-selector/#more-214)* at engineeredentropy.com.

In brief, you can leave those parts in place on Micros that you purchase, or could leave them out (while connecting VUSB and +5V) if you replicate the rest of the circuit.

>• “For the USB Micro header, does the schematic refer to any particular header (doesn't seem so to me), or will any generic one work? And what are the six pins on the right side (SH1/S1, SH2/S2, SH3/S3, SH4/S4, SH5/S5, SH6/S6)?”

Various generics should work ok, even if they don't have all the SHx shell ground pins shown.

>• “... what do the asterisks in the schematic mean?”

The asterisks next to PB7, PB6, etc., designate pins with timer-driven PWM capability.

>• “What do the circle and the smaller circle (with an X through it) towards the bottom-right mean?”

That's not clear to me.  While they look like fiducial markers, such markers typically are not needed on a schematic diagram.  Fiducial markers may be needed on PCBs or PCB layouts, but serve no obvious purpose on the schematic.  These may be a designer's idiosyncracy or left-overs.


message:
Arduino port not showing serial USB Mac OS El Capitan

I don't see serial USB as an option under ports when my Arduino is connected to my Mac. I have used this Arduino on the same computer before without any issues on Yosemite OS. However, I was trying to run a servo motor and I don't think I was getting enough power so I decided to use an external power supply. 12V 500mA DC and connected it while still keeping the USB connection. Since I already had the servo program loaded, the motor did work. Then I tried uploading the program again, that's when I realized that there was no serial connection. I am not sure if the problem is because of the power supply that I connected.

I tried the following approaches without success:

1. Upgraded the OS to El Capitan (which might have been a bad decision in hindsight).
2. Tried connecting the Arduino to another Mac with new Arduino IDE download, same issue.
3. Tried downloading the FTDI drivers as suggested by other folks.

I searched for a few hours for a solution online, but nothing so far has helped. Please provide suggestions.

body:
1. Change USB ports

2. Check your Tx and Rx pins aren't connected to ANYTHING.

3. Reboot your Mac.

4. If you're really desperate, change OS.


message:
How to use a rotary encoder on NodeMCU with Arduino code?

I have a standard 5 ping rotary encoder (3 pins for encoder, 2 pins for button).
I'm trying to get a working code that manages to read the rotary encoder.

I began with the code I found here: http://bildr.org/2012/08/rotary-encoder-arduino/

My problem is that the interrup method never being called.
I read that all the GPIO pins on NodeMCU support interrupts (except D16).
Here's my code:

    volatile int lastEncoded = 0;
    volatile long encoderValue = 0;

    long lastencoderValue = 0;

    int lastMSB = 0;
    int lastLSB = 0;

    void setup() {
      Serial.begin(115200);
      delay(10);

      pinMode(D0, INPUT);
      pinMode(D3, INPUT);

      digitalWrite(D0, HIGH); //turn pullup resistor on
      digitalWrite(D3, HIGH); //turn pullup resistor on

      attachInterrupt(D0, handleInterrupt, CHANGE);
      attachInterrupt(D3, handleInterrupt, CHANGE);
    }

    void handleInterrupt() {
      int MSB = digitalRead(D0); //MSB = most significant bit
      int LSB = digitalRead(D3); //LSB = least significant bit

      int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
      int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

      if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
      if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

      lastEncoded = encoded; //store this value for next time
    }

    void loop() {
        Serial.print("Encoder: ");
        Serial.println(encoderValue);
        delay(1000);
    }

body:
Different RotaryEncoders work in different ways. Mine connects the two outputs sequentially to the `Gnd` or `+` inputs, depending on the rotation direction. The resultant phase changes need to be detected and decoded by the processor.

I took your code and ran it on a LoLin NodeMCU using my 5-pin RotaryEncoder.

I connected (NodeMCU to RotaryEncoder):

* `D0` to `Clk`;
* `D3` to `DT`;
* `GND` to `GND`; and
* `3V` to `+`.

I ran the code, and it worked: the printed value went up when I rotated it in one direction, and down when it rotated in the other. The "bounce" was terrible though - getting just a single increment or decrement for one "detent" was difficult; I typically got 2-4.

Because of my encoder, I was able to remove the two `digitalWrite(..., HIGH);` lines and it continued to work. Perhaps that's what your problem is? Did you connect the `+` input? You mention the two switch pins: perhaps there's only one switch pin, that connects to the `Gnd` pin?

----

## EDIT: The code!

So I went away and wrote a RotaryEncoder polling library, rather than the interrupt code that the original question was based on. The idea is that you can poll a rotary encoder (relatively) infrequently, and stil "catch" the transitions as it rotates. Of course this won't work if you poll it _too_ slowly - your mileage may vary!

But here are three files:

* The header and library source for the RotaryEncoder module; and
* An example usage of the module.

RotaryEncoder.h:

    //
    // RotaryEncoder.h
    //
    // This library manages a Keyes KY-040 Rotary Encoder by sampling the
    // appropriate pins when requested. It is NOT interrupt driven, so you'll need
    // to sample often.
    //
    // The encoder has five pins in a 0.1" row, so you can directly plug it into
    // an Arduino's data-pin sockets. The sequence of pins matches the order of
    // parameters in the constructor - use ascending (or descending) numbers for
    // ease.
    //
    // If you pass in NoPin for gnd, vcc, or sw (the switch), then that parameter
    // is ignored. You'll need to organise those pins yourself! Of course, NoPin is
    // not valid for dt or clk.
    //

    #ifndef RotaryEncoder_h
    #define RotaryEncoder_h

    class RotaryEncoder {

    public: // Typedefs and enums

       typedef byte Pin;

       typedef signed char OptPin;

       enum Pins : OptPin {
          NoPin = -1
       }; // Pins

    public: // Methods

       // Define which pins to use for the various functions.
       // If Optional Pins are "NoPin", then they won't be initialised
       RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk);

       // Start RotaryEncoder with optional maxBias (call Rebias() periodically)
       void Begin(byte maxBias=1);

       // Returns true if switch is currently pressed
       bool Switch() const;

       // Returns 0 for no change, +ve for clockwise, -ve for counter-clockwise
       int Get();

       // Call this periodically to reduce the bias
       void Rebias(int delta=1);

    private: // Variables

       const OptPin gndPin;

       const OptPin vccPin;

       const OptPin swPin;

       const Pin dtPin;

       const Pin clkPin;

       byte maxBias;

       byte bias;

       bool clk;

       bool dt;

    }; // RotaryEncoder

    #endif // RotaryEncoder_h

RotaryEncoder.cpp:

    //
    // RotaryEncoder.cpp
    //

    #include <Arduino.h>
    #include "RotaryEncoder.h"

    RotaryEncoder::RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk) :
                   gndPin(gnd),
                   vccPin(vcc),
                   swPin(sw),
                   dtPin(dt),
                   clkPin(clk),
                   maxBias(1),
                   bias(1),
                   clk(false),
                   dt(false) {
    } // RotaryEncoder::RotaryEncoder(gnd, vcc, sw, dt, clk)

    void RotaryEncoder::Begin(byte maxBias) {
       this->maxBias = maxBias;
       if (gndPin!=NoPin) {
          pinMode(gndPin, OUTPUT); // Let's power the device,
          digitalWrite(gndPin, LOW);  // Power -ve with 0
       } // if
       if (vccPin!=NoPin) {
          pinMode(vccPin, OUTPUT); // ,with both - and +
          digitalWrite(vccPin, HIGH); // Power +ve with 1
       } // if
       if (swPin!=NoPin) {
          pinMode(swPin, INPUT_PULLUP); // They pushed it!
       } // if
       pinMode(dtPin,  INPUT); // One half
       pinMode(clkPin, INPUT); // The other half
    } // RotaryEncoder::Begin(maxBias)

    bool RotaryEncoder::Switch() const {
       return swPin!=NoPin ?
              digitalRead(swPin)==LOW :
              false;
    } // RotaryEncoder::Switch()

    int RotaryEncoder::Get() {
       bool clkNew = digitalRead(clkPin);
       if (clk!=clkNew) {
          clk = clkNew; // Clock's changed; sample data
          bool dtNew = digitalRead(dtPin);
          if (dt!=dtNew) {
             dt = dtNew; // Data's changed; remember it!
             if (clk) {  // Only pay attention to Clk Low-High
                int temp = bias;
                bias = maxBias;
                if (dt) {
                   return -temp;
                } // if
                else {
                   return +temp;
                } // else
             } // if
          } // if
       } // if
       return 0;
    } // RotaryEncoder::Get()

    void RotaryEncoder::Rebias(int delta) {
       if (bias<=1) {
           return;
       } // if
       bias -= bias>delta ? delta : bias-1;
    } // RotaryEncoder::Rebias()

RotaryBlinker.ino:

    //
    // RotaryBlinker
    //
    // This example changes how fast the built-in LED blinks by using the
    // RotaryEncoder library.
    // It starts with an intermediate value (80h).
    // * If you rotate it left, it slows down (then it jumps to the fastest).
    // * If you rotate it right, it speeds up (then it jumps to the slowest).
    // The jumps are because there is no logic to handle wrap-around - an exercise
    // for the reader!
    //
    // Also note that a bias feature has been included. The faster you turn the knob, the
    // exponentially quicker the rate changes. This is done by setting a fast rate on
    // every detent, then when the millisecond has changed it re-biases the knob lower.
    //
    // To handle the knob correctly, it needs to INCREASE the time interval when
    // dialling LOWER - hence you'll see a negative number in the code.
    //
    // It also checks for the switch. If it's pressed, it simply turns the LED full on.
    //

    #include <RotaryEncoder.h>

    // Choose pins that are convenient for the RotaryEncoder's pins
    #if defined(ESP8266)

    const byte LED = D5;                   // No built-in LED! Choose... this one!
    const unsigned baud = 115200;
    const RotaryEncoder::OptPin GND = -1; // Use GND pin
    const RotaryEncoder::OptPin VCC = -1; // Use V+ pin
    const RotaryEncoder::OptPin SW  =  D4; // Switch
    const RotaryEncoder::Pin    DT  =  D3; // Data
    const RotaryEncoder::Pin    CLK =  D2; // Clock

    #elif defined(ADifferentBoard) // Put the board's definition here

    // And then change these assignments
    const byte LED = LED_BUILTIN;
    const unsigned baud = 57600;
    const RotaryEncoder::OptPin GND =  8; // Need 0V
    const RotaryEncoder::OptPin VCC =  9; // Need +V
    const RotaryEncoder::OptPin SW  = 10; // Switch
    const RotaryEncoder::Pin    DT  = 11; // Data
    const RotaryEncoder::Pin    CLK = 12; // Clock

    #else // Arduino Uno default

    const byte LED = LED_BUILTIN;
    const unsigned baud = 57600;
    const RotaryEncoder::OptPin GND =  8; // Need 0V
    const RotaryEncoder::OptPin VCC =  9; // Need +V
    const RotaryEncoder::OptPin SW  = 10; // Switch
    const RotaryEncoder::Pin    DT  = 11; // Data
    const RotaryEncoder::Pin    CLK = 12; // Clock

    #endif // Boards

    // Tell library which pin does what. Note Optional Pins can be -1
    RotaryEncoder encoder(GND, VCC, SW, DT, CLK);

    // Setup the board for these definitions
    void setup() {
        Serial.begin(baud);
        pinMode(LED, OUTPUT); // Want to see it working

        encoder.Begin(10); // Start, with a re-bias of 10
    } // setup()

    bool ledON = false;  // Current LED state
    byte repeat = 0x80;  // How quickly to restart, in ms
    byte count = repeat; // Count down 'til next time!

    unsigned last = 0;   // Last time millis() was recorded

    void loop() {
        // Have switch override pulsing - turn it hard ON
        if (encoder.Switch()) { // Hard override!
            ledON = false; // Pretend LED is now OFF
            digitalWrite(LED, HIGH);
        } // if
        else {
            int value = encoder.Get(); // Returns positive for clockwise turn
            repeat += -value;   // We want to INCREASE time to slow down blinking
            if (value!=0) {     // Did it change?
                Serial.print(value);    // Print latest value
                Serial.print('=');
                Serial.println(repeat); // Print new result
            } // if
        } // else

        // Is it time to blink the LED again?
        unsigned latest = millis();
        if (last!=latest) {
            last = latest;
            encoder.Rebias();    // Re-bias encoder, to decelerate rotation
            if (--count==0) {    // Reached zero yet?
                ledON = !ledON;  // Yes! Toggle LED
                digitalWrite(LED, ledON ? HIGH : LOW);
                count = repeat;  // Count for next time
           } // if
        } // if
    } // loop()


body:
did you try a different pin? (D2, D1) should work..
Seems like D0 does not have interrupt
https://opensprinkler.com/wp-content/uploads/2016/03/NODEmcuPinOut.png

also there is a rotary encoder library so try using that
..

The library i use is able to work without interrupts
Encoder by Paul Stoffregen available from Arduino Library Manager or
https://www.pjrc.com/teensy/td_libs_Encoder.html


message:
"Exit(0);" caused uninterruptible uninterruptible loop on 32u4 board

I bought this 32u4 board on Amazon (*https://www.amazon.it/gp/product/B019SXN84E/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1*) that should be recognised as an Arduino Leonardo by the Arduino IDE.
At first it totally worked as I was only trying to emulate keyboard and mouse USB input. I was searching for a code line that could stop the void loop(), so I tried using "exit(0);", as it was suggested in an other topic here. Now since that moment the board is stuck in a loop.

It continuously repeat the loop, while the red led is always on. I tried to upload a different code, but the IDE gives me alternatively two error messages:

- "processing.app.debug.RunnerException
 at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:159)
 at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
 at processing.app.SketchController.upload(SketchController.java:707)
 at processing.app.SketchController.exportApplet(SketchController.java:680)
 at processing.app.Editor$DefaultExportHandler.run(Editor.java:2176)
 at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM3'.
 at processing.app.Serial.touchForCDCReset(Serial.java:87)
 at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:143)
 ... 5 more
Caused by: jssc.SerialPortException: Port name - COM3; Method name - openPort(); Exception type - Port busy.
 at jssc.SerialPort.openPort(SerialPort.java:164)
 at processing.app.Serial.touchForCDCReset(Serial.java:81)
 ... 6 more";

- "Forcing reset using 1200bps open/close on port COM3". *(Even waiting for hours didn't solve the "forcing")*

I already tried uninstalling drivers, uninstalling the IDE and changing COM port. Nothing worked. Unfortunately the reset button is missing on this board.

Is possible to restore the board or is totally lost?

Thanks in advance!

---

*My question is different from the one there (https://arduino.stackexchange.com/questions/188/what-happens-when-i-call-exit-from-my-program) because I used that code and I need to solve a loop problem, it's not just a theorical question. I'm also using a different type of board.*

body:
`exit(0)` basically shuts the board down. That includes the USB connection, which is managed by software. All functions stop - interrupts are disabled, etc.

You need to do a manual reset of the board when it's time to program. For that you need a reset button. If there isn't one on the board then just connect one between the RESET and GND pins.  Press it just before programming (LED should glow for something like 8 seconds) and upload your new sketch.

`exit(0)` is only safe to use on boards with a UART interface (such as the Uno). Other boards you should use `while(1);` or `for(;;);`


message:
amblone error :85: error: 'TCCR3B' was not declared in this scope - no fullscreen vlc support

getting the following error when trying to upload Amblone code to my Arduino One board:

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

    C:\Users\pha\Desktop\amblone\amblone.pde: In function 'void setup()':

    amblone:85: error: 'TCCR3B' was not declared in this scope

       TCCR3B = TCCR0B & 0b11111000 | 0x2;

       ^

    amblone:86: error: 'TCCR4B' was not declared in this scope

       TCCR4B = TCCR0B & 0b11111000 | 0x2;

       ^

    exit status 1
    'TCCR3B' was not declared in this scope

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe1
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Code:

    void setup()   {
      // initialize the serial communication
      Serial.begin(256000); // opens serial port, sets data rate to 256000 bps

      TCCR0B = TCCR0B & 0b11111000 | 0x2;
      TCCR1B = TCCR0B & 0b11111000 | 0x2;
      TCCR2B = TCCR0B & 0b11111000 | 0x2;
      TCCR3B = TCCR0B & 0b11111000 | 0x2;
      TCCR4B = TCCR0B & 0b11111000 | 0x2;

      State = S_WAIT_FOR_SF;
    }

body: Amblone doesn't work on an Uno. As stated in the requirements list, you require a Mega.


body:
Thanks to @Majenko, I realised I was uploading code to wrong arduino board as mine was Mega not Uno.

I was also not getting colour changes (Amblone) when playing a file on VLC player full screen - downgraded version and it works again now.


message:
Unable to connect esp8266 12 module with arduino uno

Here is what I am doing

    Arduino(UNO)--------Esp8266
    3.3 v -- vcc
    TX      -- RX
    RX      -- TX
    3.3 v  -- EN(ch_pd)
    GND     -- GND

there is no blinking of LED on Esp8266, sometimes the LED is on and sometimes it is not. And when I send "AT" command using Serial of Arduino IDE, only RX light of Arduino blinks, TX is not blinking and there is no response of that command. I am having 3.3 voltage on my Vcc pin of Esp8266 but the voltage on the TX and RX pins of Esp8266 is 5 volts, I know that i can reduce this to 3.3 voltage by using a voltage regulator but my question is why there is no blinking on the module even when i have supplied the proper 3.3 voltage and GND?
What's the difference between the blinking and a still LED on Esp8266?
I have tried every tutorial on internet. No help at all. Right now I am so exhausted that I want to quit.If you can help in solving the problem, I would be very thankful to you sir.

body:
When you are using Arduino board just as USB --> RS232 converter to send AT commands from PC to ESP8266 you have to connect **TX to TX** and **RX to RX**. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. [Here][1] I explained that in details.

  [1]: https://arduino.stackexchange.com/questions/30689/arduino-uno-and-esp8266-serial-monitor-issue/31929#31929


message:
Male header pins on Arduino Uno

On my board, there are 12 (2 groups of 6, each group consistent of 3 rows of 2 pins) weird male header pins. What are these, and how would you use them?

[![Picture of Arduino with header pins identified][1]][1]

  [1]: https://i.stack.imgur.com/Rrd9x.jpg

body:
The one by the USB connector is ICSP for the USB interface chip. The other is ICSP for the main chip and doubles as the (now standard) SPI interface for shields.

* https://www.arduino.cc/en/Reference/SPI


body:
These are the In System Programming (ISP) pins. They are used to program the microcontroller without using the bootloader.

The bootloader is a program already loaded into the flash of the microcontroller that allows the program to be loaded into the microcontroller through the Tx & Rx serial lines and hence not requiring a programming device.

Using the ISP can be useful when:

 * The bootloader program doesn't exist in the microcontroller such as on a new chip.
 * The bootloader is corrupted.
 * Your program is just that little bit too big and you wish to gain the couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

The standard connection for the ISP is a 100 mil 6-pin header (2x3).
[![ISP pinout][1]][1]

There are two ISP headers on the Arduino Uno because there are actually 2 microcontrollers on the board. There is the main microcontroller (aka the ATmega328P) which is used to execute the program you load into the Arduino board. The second microcontroller (ATmega16U2 or ATmega8U2) is used as a USB interface - converting the USB signals into serial data that is connected to the ATmega328P's UART (ie. Tx & Rx).
[![Arduino ISP headers & their respective microcontrollers][2]][2]

The following document details the ISP and gives descriptions of the pins used on the ISP header and how to interface them with the microcontroller etc.:
[[PDF] AVR: In-System Programming - Atmel][3]

----------

EDIT: As Majenko correctly points out, the 2x3 ISP header closest to the ATmega328P can also be used to connect sensors and controllers that communicate using the Serial Peripheral Interface (SPI).

More information on the Serial Peripheral Interface and the SPI Library can be found at: [https://www.arduino.cc/en/Reference/SPI][4]

  [1]: https://i.stack.imgur.com/nxknS.png
  [2]: https://i.stack.imgur.com/vnKU1.jpg
  [3]: http://www.atmel.com/Images/doc0943.pdf
  [4]: https://www.arduino.cc/en/Reference/SPI


message:
Switching methods/functions with a button

I am trying to program a basic counter using 7segment display and a button.
What I am trying to achieve is the following:

 1. Display 0 at the beginning.
 2. When the button is pressed: Start Loop 0-9
 3. Display 0 when the button is pressed the second time.

So basically the button should function as ON/OFF switch for the looping numbers function.

So far I have managed to change the mode from  displaying 0 to looping 0-9, but can't seem to get changing the mode back to displaying 0:

    int buttonPin = 10; // Button connected to digital pin 10.
    // variable for reading the pushbutton status
    boolean buttonPressed = false;
    int mode;

    void setup() {
        // initialize the pushbutton pin as an input:
        pinMode(buttonPin, INPUT);

        pinMode(1, OUTPUT);
        pinMode(2, OUTPUT);
        pinMode(3, OUTPUT);
        pinMode(4, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(6, OUTPUT);
        pinMode(7, OUTPUT);
        pinMode(8, OUTPUT);
        pinMode(9, OUTPUT);
        pinMode(10, OUTPUT);
        pinMode(11, OUTPUT);
        pinMode(13, OUTPUT);
    }

    void displayZero() {
        //while (buttonState == true){
        // Displays 0.
        digitalWrite(11,1);
        //button();
        delay(1000);
        //}
    }

    void displayCounter() {
        // Displays 0.
        digitalWrite(4,1);
        digitalWrite(11,1);
        delay(1000);

        //Displays 1.
        digitalWrite(2,1);
        digitalWrite(3,1);
        digitalWrite(4,1);
        digitalWrite(8,1);
        delay(1000);

        //Displays 2.
        digitalWrite(2,0);
        digitalWrite(8,0);
        digitalWrite(6,0);
        digitalWrite(4,0);
        digitalWrite(9,1);
        digitalWrite(3,1);
        digitalWrite(11,0);
        delay(1000);

        //Displays 3.
        digitalWrite(4,1);
        digitalWrite(9,0);
        digitalWrite(11,0);
        delay(1000);

        //Displays 4.
        digitalWrite(2,1);
        digitalWrite(8,1);
        digitalWrite(3,0);
        delay(1000);

        //Displays 5.
        digitalWrite(6,1);
        digitalWrite(2,0);
        digitalWrite(8,0);
        digitalWrite(11,0);
        delay(1000);

        //Displays 6.
        digitalWrite(4,0);
        delay(1000);

        //Displays 7.
        digitalWrite(3,1);
        digitalWrite(4,1);
        digitalWrite(6,0);
        digitalWrite(8,1);
        digitalWrite(11,1);
        delay(1000);

        //Displays 8.
        digitalWrite(3,0);
        digitalWrite(4,0);
        digitalWrite(8,0);
        digitalWrite(11,0);
        delay(1000);

        //Displays 9.
        digitalWrite(4,1);
        //button();
        delay(1000);
    }

    void loop() {
        // Check button status.
        int buttonStatus = digitalRead(buttonPin);

        if (buttonStatus == HIGH)
        {
            // Checks if button is pressed and changes buttonPressed from false to true.
            buttonPressed = true;

            // While button is pressed.
            while(buttonPressed == true) {
                // Calls displayCounter method 10 times.
                for (int i=0; i<10; i++) {
                    displayCounter();
                    delay(30);
                    buttonPressed == false;
                }
            }
        }
        else if (buttonStatus == LOW)
            displayZero();
    }

body:
Not sure but this should work

    const int segment[7] = {2,3,4,5,6,7,8}; //pins for each segment

    const int nums[10][7] = //declaring array
    {
      {1,1,1,1,1,1,0}, //0
      {0,1,1,0,0,0,0}, //1
      {1,1,0,1,0,0,1}, //2
      {1,1,1,1,0,0,1}, //3
      {0,1,1,0,0,1,1}, //4
      {1,0,1,1,0,1,1}, //5
      {1,0,1,1,1,1,1}, //6
      {1,1,1,0,0,0,0}, //7
      {1,1,1,1,1,1,1}, //8
      {1,1,1,0,0,1,1}  //9
    };

    //=======================================================================

    #define button 9 //defining button that is connected to pin 9

    //=======================================================================

    void setup() {
      for(int i=2; i<=8; i++) //shorcut for declaring a buch of pin modes
      {
        pinMode(i, OUTPUT);
      }

      pinMode(button, INPUT); //set button as an input
    }

    //=======================================================================

    void loop() {
      while(digitalRead(button) == LOW) //wait until user click the button
      {
        number(0); //display 0 when waiting
      }

      bool state = false; // create a status varible

      for(int i=0; i<10 && state == false; i++) //run the numbers from 0-9
      {

        number(i); //display the number

        for(int j=0; j<100 && state == false; j++)
        {

          if(digitalRead(button) == HIGH) //if the button is clicked, then cancel the loop ans go back to displaying 0
          {
            state = true;
          }

          delay(10); //this delay while execute a 1000 times so there is actualy a 1sec delay

        }
      }
    }

    //=======================================================================

    void number(int num) //num is the number to display
    {
      for(int i=0; i<7; i++)
      {
        digitalWrite(segment[i], nums[num][i]);
      }
    }


body:
In your loop() function, the statement `buttonPressed == false;` doesn't do anything; it is simply an expression that evaluates to 0 or false (because buttonPressed is equal to true). Your while() loop will never end which is why you can't stop the counter by pressing the button again.

You probably meant `buttonPressed = false;`, which is an assignment statement setting the value of buttonPressed.  But doing that within the while loop makes the loop contents iterate once which it would do anyway, so there is no need for the surrounding `while` statement. The `for()` statement will still be executed once, without the while (the loop contents will be *iterated* 10 times in that one execution).

So you can reduce your loop() function to:

    void loop() {

    // Check button status.
       int buttonStatus = digitalRead(buttonPin);

       if (buttonStatus == HIGH)
       {
          // Calls displayCounter method 10 times.
          for (int i=0; i<10; i++){
             displayCounter();
             delay(30);
          }
       }
       else
          displayZero();
    }

which will check the button state on each call to `loop()` and either run the counter or zero it, once, depending on the state.

You'll need another refinement, that of debouncing the button. Push buttons (and some other kinds of switches don't have a clean 0 -> 1 (or vice versa) transition but take some amount of time during which their state appears to bounce between 0 and 1 before finally settling to the new state. Read Nick Gammon's excellent [article about contact bounce][1] to see why and what to do about it.

  [1]: http://www.gammon.com.au/switches


message:
Uploading Error: no programmer has been specified

Whenever I upload a code I get this error:

```avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again
```

I am able to upload from other PCs, but ever since I got the newest IDE, it stopped working. I even tried downgrading to 1.6.8, and still i get this error... Any help? Thanks,

Sean

body:
This issue occurs when using Arduino IDE 1.6.8 or older with Arduino AVR Boards 1.6.12 or 1.6.14. There are two solutions:

 1. Upgrade your Arduino IDE to 1.6.9 or newer by downloading and
    installing the appropriate file from
    [https://www.arduino.cc/en/Main/Software][1].

 2. Downgrade your Arduino AVR Boards version to 1.6.11 or older(or 1.6.13) via
    **Tools > Board > Boards Manager...**

I submitted a pull request to fix this backwards compatibility issue and it was merged by the Arduino developers so this issue will no longer occur with Arduino AVR Boards 1.6.15 and up. It explains the cause of the issue:
[https://github.com/arduino/Arduino/pull/5427][2]

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: https://github.com/arduino/Arduino/pull/5427


message:
Arduino uno board not detected when connected via USB no matter what OS

I was working with Arduino in Win 8.1, when suddenly it stopped work. I tried to reinstall the drivers and IDE several times, but it didn't solved.

In Win 8.1, when I plug the arduino, I get the pop up message:

USB Device Not Recognized in Windows

Also, when I try to upload a sketch, I get this error in Arduino IDE:

    avrdude: ser_open(): can't open device "\\.\com5": the system cannot find the file specified

I switched to Linux (Debian Jessie 64 bits), but it also doesn't get recognized, and I getting the same error, only the port Is different.

I am guessing is a problem with avr, but I don't know what can I do about it.

Other  symptoms:

- In both systems the port tool in IDE is grey, so I can't choose a port.

- When I press the reset button in Arduino, nothing happens.

- The led L (13) is constantly shinning. It never blinks or stops.

Solutions I tried:

- Reinstall drivers
- Modify the preferences.txt file to change the COM port
- Fall back to a previous IDE version
- Change the usb cable

body: Arduino is most probably aproaching the wrong com. You can set a new com. in the IDE of arduino under settings. Change it to the available com. It might be required to find out in Windows/ system configuration for the available coms  Maybe something there is wrong.


body: If the port selector in the IDE is greyed out, and the OS is throwing an error, it's likely the Board is damaged. Either The firmware on the serial device or the chip is fried somehow. What's happening is that the usb part is failing, so the Com port part never works.


message:
Get an additional analog pin?

I have the following board:

[![enter image description here][1]][1]

As far as I can tell, there's only a single analog pin (`A0`). But I need at least 2 additional (for 3 total).

Is there some way to fake analog input on GPIO pins?

  [1]: https://i.stack.imgur.com/AkunN.jpg

body:
The ESP8266 only has one ADC pin. You can:

1. Use an analog MUX to switch that pin between different signals
2. Connect an external I2C ADC chip
3. Connect an external SPI ADC chip
4. Connect the ESP8266 to another MCU (such as an Arduino) and get that to do analog readings.


message:
Issue with photoresistor - the analogRead stays pretty much the same?

**UPDATE:** If I could **I'd downvote myself**. I'm a web developer and as I see that my job will be eaten, I'm trying to expand my skill set. Sometimes I wish I had a second pair of eyes or https://en.wikipedia.org/wiki/Rubber_duck_debugging

---

Previously I was asking which sensor use to measure the light: https://arduino.stackexchange.com/questions/29758/which-sensor-to-detect-light

Here is a short video showcasing my issue: https://www.youtube.com/watch?v=VGs_Ax_wlbg

Super simple .INO sketch from https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module

<!-- language: lang-c++ -->

    int sensorPin = A5; // select the input pin for the potentiometer
    int ledPin = 13; // select the pin for the LED
    int sensorValue = 0; // variable to store the value coming from the sensor
    void setup() {
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600);
    }
    void loop() {
      sensorValue = analogRead(sensorPin);
      digitalWrite(ledPin, HIGH);
      delay(sensorValue);
      digitalWrite(ledPin, LOW);
      delay(sensorValue);
      Serial.println(sensorValue, DEC);
    }

I'm worried that my sensor readings are pretty much the same - in shade, brighten up by green laser...

**Am I doing it right?**

**Are values from the sensor in the expected range?**

Alternatively: is there any more sensitive sensor I should buy that will tell me more reliably if the there is green laser light pointing at it?

body:
***** ITS ANALOG 5 not DIGITAL 5 *****

Also try doing this:

    delay(sensorValue*10);

The times 10 will help show the differences between each value.