body:
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;
    }

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

Answers: 1

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;


body:
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?

title: Arduino Mega 2560 and Android USB OTG serial communication

Answers: 1

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.


body:
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! :)

title: Transmitting Variables over RF

Answers: 2

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


body:
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!

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

Answers: 1

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/


body:
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

title: W5100 Ethernet Shield to Custom Board Problem

Answers: 2

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


body:
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.

title: Smooth servo control library

Answers: 3

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


body:
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

title: lcd has no contrast pin

Answers: 1

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.


body:
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.

title: Arduino char showing as 2 characters

Answers: 1

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.


body:
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?

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

Answers: 3

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
      }


body:
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.

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

Answers: 3

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);

body:
It can be done the **C way**:

`sprintf()` can be used to generate a formatted string, and then `Serial.println()` to send the string

```
char buf[32];
sprintf(buf, "#S|SKAITYMAS|[%d]#", LINENR);
Serial.println(buf);
```
or with **String class** as explained here:

[https://www.arduino.cc/en/Tutorial/StringAdditionOperator][1]
```
  String str = "#S|SKAITYMAS|["
  str += LINENR;
  str += "]#";
  Serial.println(str);
```
**Do not do everything in just one line, as explained on the page link above.**

  [1]: https://www.arduino.cc/en/Tutorial/StringAdditionOperator


body:
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?

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

Answers: 3

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/


body:
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!

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

Answers: 1

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.


body:
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 ?

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

Answers: 1

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!


body:
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)

title: Questions about the Arduino Micro PCB

Answers: 3

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.


body:
I installed the drivers for x64 and got this:

[![Device driver install][1]][1]

Notice it did not install the first one - USBSER.

However, I am able to upload code in the Arduino IDE so I went ahead and uploaded the CDC ECHO sketch and all went well there.

But Windows does not see it as a VCP:

[![Devices][2]][2]

[![Device properties][3]][3]

[![Driver file][4]][4]

[![Select device driver][5]][5]

[![Windows encountered a problem][6]][6]

What can I do in order to fix this?

  [1]: https://i.stack.imgur.com/MkjzW.png
  [2]: https://i.stack.imgur.com/lhG5A.png
  [3]: https://i.stack.imgur.com/F7AXz.png
  [4]: https://i.stack.imgur.com/XOja5.png
  [5]: https://i.stack.imgur.com/ijxyG.png
  [6]: https://i.stack.imgur.com/JDFcr.png

title: DigiSpark USB issue

Answers: 1

body:
Use this bootloader:

https://github.com/micronucleus/micronucleus

Make sure you have Arduino IDE 1.6.5+

Open the IDE, go to

> File > Preference

then find "Additional Boards" URL. Then paste [this link](http://digistump.com/package_digistump_index.json) and then click OK.

Then go to

> Tools > Boards > Boards Manager

and change the type to "Contributed" then install the "Digistump AVR Boards". Then change the Arduino board to the Digispark that you have and you're ready to go!


body:
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.

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

Answers: 1

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.


body:
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);
    }

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

Answers: 2

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


body:
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.*

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

Answers: 1

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(;;);`


body:
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;
    }

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

Answers: 2

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.


body:
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.

title: Unable to connect esp8266 12 module with arduino uno

Answers: 1

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


body:
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

title: Male header pins on Arduino Uno

Answers: 2

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


body:
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();
    }

title: Switching methods/functions with a button

Answers: 2

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


body:
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

title: Uploading Error: no programmer has been specified

Answers: 1

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


body:
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

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

Answers: 2

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.


body:
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

title: Get an additional analog pin?

Answers: 1

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.


body:
**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?

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

Answers: 1

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.


body:
I am currently running this piece of code:

main.ino

    #include "speed_profile.h"

    void setup() {
      // put your setup code here, to run once:
      output_pin_setup();
      cli();
      timer1_setup();
      sei();
    }

    void loop()
    {
          //int motor_steps = 23400;//-9600; //23400 -  100%
          // Accelration to use.
          //int motor_acceleration = 500;//500;
          // Deceleration to use.
          //int motor_deceleration = 500;//500;
          // Speed to use.
          //int motor_speed = 1000; // 1000
          init_tipper_position();
          compute_speed_profile(23400, 500, 500, 1000);
    }

Speed_profile.cpp

    #include "speed_profile.h"

    volatile speed_profile profile;

    ros::NodeHandle_<ArduinoHardware, 1, 2, 125, 125> nh;
    //ros::NodeHandle nh;

    std_msgs::Int16 status_step_count;
    std_msgs::Int16 status_tipper_availability;
    ros::Publisher chatter_status("tipper_status", &status_step_count);
    ros::Publisher chatter_availabilty("tipper_availability", &status_tipper_availability);

    volatile bool global_state = false;
    int received_data = 0;

    void call_back_control( const std_msgs::Empty & msg)
    {
      global_state = true;
      // For HMI
      received_data  = (100 *23400.0)/100.0; // Converts input to motor_steps.
    }

    ros::Subscriber<std_msgs::Empty> sub_control("tipper_control", &call_back_control );

    void output_pin_setup()
    {
      pinMode(en_pin, OUTPUT);
      pinMode(dir_pin, OUTPUT);
      pinMode(step_pin, OUTPUT);
      pinMode(slot_sensor_pin,INPUT_PULLUP);
      nh.initNode();
      nh.advertise(chatter_status);
      nh.advertise(chatter_availabilty);
      nh.subscribe(sub_control);
      //nh.subscribe(sub_command);
      profile.current_step_position = 0;
      delay(10);
      nh.getHardware()->setBaud(57600);
    }

    void init_tipper_position()
    {
      //digitalWrite(en_pin, HIGH);
      //delay(1);

      //digitalWrite(dir_pin, LOW);
      //delay(1);

      while(!(PINB & (1 << 2)))
      {
        //PORTB ^= _BV(PB3);
        //delayMicroseconds(100);
      }

      //digitalWrite(en_pin, LOW);

    }
    void timer1_setup()
    {
      // Tells what part of speed ramp we are in.
      profile.run_state = STOP;

      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1  = 0;  // reset the timer

      // Timer/Counter 1 in mode 4 CTC (Not running).
      TCCR1B = (1 << WGM12);

      // Timer/Counter 1 Output Compare A Match Interrupt enable.
      TIMSK1 = (1 << OCIE1A);
    }

    void computation_of_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
    {
      unsigned int steps_to_speed;  // Steps required to achieve the the speed desired
      unsigned int acceleration_step_limit; // If desired speed is not achieved, will this variable contain step_limit to when to stop accelerating.
      // If moving only 1 step.
      if (motor_steps == 1)
      {
        // Move one step
        profile.accel_count = -1;
        // in DECEL state.
        profile.run_state = DECEL;
        // Just a short delay so main() can act on 'running'.
        profile.first_step_delay = 1000;
        OCR1A = 10;
        // Run Timer/Counter 1 with prescaler = 8.
        TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
      }
      else if (motor_steps != 0)
      {
        // Set max speed limit, by calc min_delay to use in timer.
        // min_delay = (alpha / tt)/ w
        profile.min_time_delay = A_T_x100 / motor_speed;

        // Set accelration by calc the first (c0) step delay .
        // first_step_delay = 1/tt * sqrt(2*alpha/accel)
        // first_step_delay = ( tfreq*0.676/100 )*100 * sqrt( (2*alpha*10000000000) / (accel*100) )/10000
        profile.first_step_delay = (T1_FREQ_148 * sqrt(A_SQ / motor_accel)) / 100;

        // Find out after how many steps does the speed hit the max speed limit.
        // steps_to_speed = speed^2 / (2*alpha*accel)
        steps_to_speed = (long)motor_speed * motor_speed / (long)(((long)A_x20000 * motor_accel) / 100);
        // If we hit max speed limit before 0,5 step it will round to 0.
        // But in practice we need to move atleast 1 step to get any speed at all.
        if (steps_to_speed == 0)
        {
          steps_to_speed = 1;
        }

        // Find out after how many steps we must start deceleration.
        // n1 = (n1+n2)decel / (accel + decel)
        acceleration_step_limit = ((long)motor_steps * motor_decel) / (motor_accel + motor_decel);
        // We must accelrate at least 1 step before we can start deceleration.
        if (acceleration_step_limit == 0)
        {
          acceleration_step_limit = 1;
        }

        // Use the limit we hit first to calc decel.
        if (acceleration_step_limit <= steps_to_speed)
        {
          profile.decel_length = -(motor_steps - acceleration_step_limit); //---
        }
        else
        {
          profile.decel_length = -((long)steps_to_speed * motor_accel) / motor_decel; //--
        }
        // We must decelrate at least 1 step to stop.
        if (profile.decel_length == 0)
        {
          profile.decel_length = -1;
        }

        // Find step to start decleration.
        profile.decel_start = motor_steps + profile.decel_length;

        // If the maximum speed is so low that we dont need to go via accelration state.
        if (profile.first_step_delay <= profile.min_time_delay)
        {
          profile.first_step_delay = profile.min_time_delay;
          profile.run_state = RUN;
        }
        else
        {
          profile.run_state = ACCEL;
        }

        // Reset counter.
        profile.accel_count = 0;
        //profile.step_counter = steps_to_speed;
      }
    }

    void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
    {
      while (global_state == false)
      {
        //do nothing
        status_step_count.data = ((float)(profile.current_step_position / 23400.0)) * 100.0; //map(profile.current_step_position,0,23400,0,100); // could be expensive -- Nice flowing is only available with float
        status_tipper_availability.data = 1;

        chatter_status.publish( &status_step_count);
        chatter_availabilty.publish(&status_tipper_availability);
        nh.spinOnce();
      }

      digitalWrite(en_pin, HIGH);
      delay(1);

      signed int move_steps;
      //if (motor_steps < 0)
      if(received_data > profile.current_step_position) // Compares whether received percentage (converted to motor_steps) is greater or smaller than current_step_position.
      {
        profile.dir = CCW;
        move_steps =  received_data - profile.current_step_position;
        digitalWrite(dir_pin, HIGH);
      }
      else
      {
        profile.dir = CW;
        move_steps =  profile.current_step_position - received_data;
        digitalWrite(dir_pin, LOW);
      }

      delay(1);
      // received_data = percentage converted to a step number received from tipper_control topic

      computation_of_speed_profile(move_steps, motor_accel, motor_decel, motor_speed); // function should be called with the correct motor_steps value

      OCR1A = 10;
      // Set Timer/Counter to divide clock by 8
      TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));

      while (global_state == true)
      {
        status_step_count.data = ((float)(profile.current_step_position / 23400.0)) * 100.0; //map(profile.current_step_position,0,23400,0,100); // could be expensive -- Nice flowing is only available with float
        status_tipper_availability.data = profile.run_state;

        chatter_availabilty.publish(&status_tipper_availability);
        chatter_status.publish( &status_step_count);
        nh.spinOnce();
      }
    }

    ISR(TIMER1_COMPA_vect)
    {
      // Holds next delay period.
      unsigned int new_first_step_delay;

      // Remember the last step delay used when accelrating.
      static int last_accel_delay;

      // Counting steps when moving.
      static unsigned int step_count = 0;

      // Keep track of remainder from new_step-delay calculation to incrase accurancy
      static unsigned int rest = 0;
      OCR1A = profile.first_step_delay;
      switch (profile.run_state)
      {

        case STOP:
          step_count = 0;
          global_state = false;
          rest = 0;
          TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10)); // Stop the timer,  No clock source
          break;

        case ACCEL:
          //digitalWrite(step_pin, !digitalRead(step_pin));
          PORTB ^= _BV(PB3);  // Toggles the step_pin
          step_count++;

          if (profile.dir == CCW)
          {
            profile.current_step_position++;
          }
          else
          {
            profile.current_step_position--;
          }

          profile.accel_count++;
          new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
          rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);

          // Chech if we should start decelration.
          if (step_count >= profile.decel_start)
          {
            profile.accel_count = profile.decel_length;
            profile.run_state = DECEL;
          }

          // Chech if we hitted max speed.
          else if (new_first_step_delay <= profile.min_time_delay)
          {
            last_accel_delay = new_first_step_delay;
            new_first_step_delay = profile.min_time_delay;
            rest = 0;
            profile.run_state = RUN;
          }
          break;
        case RUN:
          //digitalWrite(step_pin, !digitalRead(step_pin));
          PORTB ^= _BV(PB3); // Toggles the step_pin
          step_count++;

          if (profile.dir == CCW)
          {
            profile.current_step_position++;
          }
          else
          {
            profile.current_step_position--;
          }
          new_first_step_delay = profile.min_time_delay;
          // Chech if we should start decelration.
          if (step_count >= profile.decel_start)
          {
            profile.accel_count = profile.decel_length;
            // Start decelration with same delay as accel ended with.
            new_first_step_delay = last_accel_delay;
            profile.run_state = DECEL;
          }
          break;
        case DECEL:
          //digitalWrite(step_pin, !digitalRead(step_pin));
          PORTB ^= _BV(PB3); // Toggles the step_pin
          step_count++;
          if (profile.dir == CCW)
          {
             profile.current_step_position++;
          }
          else
          {
            profile.current_step_position--;
          }
          profile.accel_count++;
          new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
          rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);
          // Check if we at last step

          if (profile.accel_count >= 0)
          {
            digitalWrite(en_pin, !digitalRead(en_pin));
            //PORTB &= ~_BV(PB3);
            profile.run_state = STOP;
          }
          break;

      }

      profile.first_step_delay = new_first_step_delay;

    }

And the Speed_profile.h

    /*
     * Contains the class concerning with calculating the proper speed profile
     * for accelerating and decelerating the stepper motor.
     *
     */

    #ifndef speed_profile_h
    #define speed_profile_h

    #include <Arduino.h>
    #include <ros.h>
    #include <std_msgs/Int16.h>
    #include <std_msgs/Empty.h>

    // Timer/Counter 1 running on 3,686MHz / 8 = 460,75kHz (2,17uS). (T1-FREQ 460750)
    //#define T1_FREQ 460750
    #define T1_FREQ 1382400

    //! Number of (full)steps per round on stepper motor in use.
    #define FSPR 1600

    // Maths constants. To simplify maths when calculating in compute_speed_profile().
    #define ALPHA (2*3.14159/FSPR)                    // 2*pi/spr
    #define A_T_x100 ((long)(ALPHA*T1_FREQ*100))     // (ALPHA / T1_FREQ)*100
    #define T1_FREQ_148 ((int)((T1_FREQ*0.676)/100)) // divided by 100 and scaled by 0.676
    #define A_SQ (long)(ALPHA*2*10000000000)         // ALPHA*2*10000000000
    #define A_x20000 (int)(ALPHA*20000)              // ALPHA*20000

    // Speed ramp states
    #define STOP  0
    #define ACCEL 1
    #define DECEL 2
    #define RUN   3

    // Pin numbering
    #define en_pin 13
    #define dir_pin 12
    #define step_pin 11
    #define slot_sensor_pin 10

    // Motor direction
    #define CW  0
    #define CCW 1

    typedef struct
    {
      unsigned char run_state : 3; // Determining the state of the speed profile
      unsigned char dir: 1; // Determining the direction the motor has to move - Start being CCW
      unsigned int first_step_delay; // Period time for the next timer_delay, determines the acceleration rate.
      unsigned int decel_start; //  Determines at which step the deceleration should begin.
      signed int decel_length; // Set the deceleration length
      signed int min_time_delay; //minium time required time_delay for achieving the wanted speed.
      signed int accel_count; // counter used when computing step_delay for acceleration/decelleration.
      volatile signed int current_step_position; // contains the current step_position

    }speed_profile;

    void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
    void computation_of_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
    void init_tipper_position();
    void timer1_setup(void);
    void output_pin_setup(void);
    #endif

The problems is with the ISR. The function `init_tipper_position` seem to be causing a timing problem that makes is impossible the ISR to go through all its states. I changed some parts of the code based on @EdgarBonet 's answer, which seem have helped a bit. The problem here is that the program stalls when the it reaches the state STOP. This is not a issue at all if the prior function is executed..?? why am I having this issue?

title: why does function affect my ISR?

Answers: 3

body:
This isn't the sort of approach you should use in an ISR.  You need to get into the ISR, and get out of it ASAP.  Set a flag, and read the flag in your code to decide what needs to be done.  There should be *very little* in the way of decisions and branching in an ISR.  Most certainly, there should be *zero* floating point math in your ISR, especially on a platform that doesn't have a floating point processor (actually, my preference is to avoid floating point math wherever possible in an embedded system, but I might be a bit extreme.

Start from scratch, rebuilding your ISR to do only what needs to be done, and use main to do the rest of it (or "loop" or some such on an Arduino).

Having spent no real time on an Arduino, interrupts just don't seem all that convenient to use to me.  If the Arduino environment doesn't let you use interrupts the right way, you should consider programming the AVR wit AVR compilers.

body:
I'm not very familiar with the details of the Arduino infrastructure either, but I think your fundamental problem is the fact that you are doing GPIO (i.e., `digitalRead()` and `digitalWrite()`) both in your ISR and in your main `loop()`.

Since these functions manipulate global hardware and use various "shadow" variables to keep track of their state, it's very unlikely that they are "reentrant". A reentrant function is written without global/static variables (and a few other restrictions), such that one call to it can be interrupted and another call made to it without interfering with the first one.

The Arduino environment was never intended for projects in which issues such as reentrancy should arise; such projects should be using using a "real" RTOS or equivalent. Yes, you can shoehorn such project into the Arduino environment, but only if you already know exactly what you're doing.

body:
> I narrowed the search space to be inside the `init_tipper_position`

I see nothing wrong with this function, except that it takes some time
to execute, and makes `compute_speed_profile()` start later. So I am
guessing yours is a timing problem: your code may be sensitive to the
value held by the timer when `compute_speed_profile()` starts. It is
just a wild guess, as you did not show all your code, and the real
problem may be somewhere we cannot see.

Did you completely initialize Timer 1 before using it? I see no mention
of `TCCR1A` in the part you showed us. You should be aware that the
Arduino core library initializes this timer to provide 8-bit PWM. It is
likely that you will need to undo that initialization, e.g., at the very
beginning of your program:

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

    TCCR1A = 0;  // undo the initialization done by...
    TCCR1B = 0;  // ...the Arduino core library
    TCNT1  = 0;  // reset the timer

This is the default state set by the hardware at boot, and the Atmel
application note you are using as a reference may well assume this state
has not been tampered with.

Also, I did not check your algorithm, but since your are stopping and
restarting the timer, it may make sense to also reset it (`TCNT1 = 0;`).


body:
I am working on a project where I need to calculate distance traveled by a robot. The mouse is connected to the arduino uno processor and I received some sample code from the arduino website to get started.

The problem is that the mouse gives difference distances depending on how fast or slow the it moves. (The same way you can move your pc mouse from side to side, fast and slow, and watch it cover different distances across the screen). Is there anyway to get get around this mouse setting? If not,  is there a more accurate sensor that can be used to accomplish the task? I'm having a hard time finding one.

Here is a link to the datasheet: http://www.alldatasheet.com/datasheet-pdf/pdf/333273/PIXART/PAW3402.html

title: Using ps2 mouse (PAW3402 / PAW3412) as a distance sensor for arduino

Answers: 2

body:
What you can do is use a hall effect (magnetic) sensor. If you connect a small magnet yo your shaft and connect the sensor in a way that the magnet will pass the sensor at every rotation, you can count the number of rotation that the shaft doesn thus calculating the distance.

It's a simple math equation:

distance = rotation * circonference of the wheels

For circonference, here is the equation:

circonfernce = diameter * PI

body:
Assuming under normal conditions a relative pointing device such as a optical mouse always reports relative position changes with out regard to speed.  If true, then consider that the speed of the robot is faster than the mouse can process.  Also, consider that the mouse's optics is out of focus with respect to the surface it is supposedly taking its positioning cues from.  Lastly, consider the surface may not be ideal for an optical mouse.  Attempt the same experiment using a sheet of paper or a "not-shiny" wood surface.

All surfaces have to be flat.  For example, a ceramic tile floor will likely not work as the surface will come in and out of focus during travel.  Make sure the elevation of the robot with respect to the surface is constant.  Inspect the wheels to make sure they are perfectly round and rotating around their center point.

Check and make sure you are not suffering from a integer calculation or type size problem.  Examine your code and make sure you are handling all cases including the expected maximum and minimum values properly.  And that your variables are large enough to handle these expected values.


body:
For a school project I want to make a little project with the Arduino Uno. I want to make a project that does something when a client connects to the WiFi shield.

My first thought was to print out the IP address or MAC address of the client but I can't find the codes for it. It is possible for me to print out the host IP? I have searched on the web for some time but only the ethernet shield will appear. Is my question even possible with an WiFi shield or do I have to get an ethernet shield?

Kind regards.

title: Is it possible to print client IP or MAC address from Arduino WiFi web server?

Answers: 1

body:
***** Assuming it is an ESP8266 based WI-FI shield: *****

Wifi shield > PC

Open serial monitor. Baud rate 155200. Also check COM ports.

Test AT commands by typing AT.

If it responds OK, you're good.

Type AT+CIFSR for IP adress.

Full list of AT commands in this link:

http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf