# Question
Title: How to handle an interrupt that interrupts a serial communication?
I am at the moment trying via ros to publish a status message about how many steps a motor has moved. Problem, is that value doesn't to be readable, or the only thing I am able to read from the topic is a zero.

The value i want to publish is being incremented inside a ISR routine, so i have a single thread that continuesly publishes the messages, and then when an ISR is called, increment it the value.

I tested with serial to see what might have been wrong, but the output of the serial doesn't seem to make any sence, isn't readable.. Is outputs alot of "??" eventhoug I am using the right baudrate and so on. So what is the problem here?

speed\_profile.cpp

```
#include "speed_profile.h"

volatile speed_profile profile;
ros::NodeHandle nh;

std_msgs::Int16 status_step_count;
ros::Publisher chatter("tipper_status", &status_step_count);

void output_pin_setup()
{
  pinMode(en_pin,OUTPUT);
  pinMode(dir_pin,OUTPUT);
  pinMode(step_pin,OUTPUT);
  nh.initNode();
  nh.advertise(chatter);
}

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

  // 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 compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
{
  digitalWrite(en_pin,HIGH);
  delay(1);

  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 (motor_steps < 0)
  {
    profile.dir = CCW;
    motor_steps = -motor_steps;
    digitalWrite(dir_pin,LOW);
  }
  else
  {
    profile.dir = CW;
    digitalWrite(dir_pin,HIGH);
  }

  delay(1);

  // 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 = steps_to_speed - motor_steps;
      profile.decel_length = -(motor_steps-acceleration_step_limit); //---
    }
    else
    {
      //profile.decel_length = -((long)steps_to_speed * acceleration_step_limit) / motor_decel;acceleration_step_limit
      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.
    //int steps_in_run = motor_steps - steps_to_speed-profile.decel_length;

    profile.decel_start = motor_steps + profile.decel_length;
    //profile.decel_start = motor_steps - steps_to_speed-steps_in_run;

    // 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;
    OCR1A = 10;
    // Set Timer/Counter to divide clock by 8
    TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
    profile.moved_steps = 0;

  }

  while(1)
  {
    cli();
    status_step_count.data = profile.moved_steps;
    Serial.print("profile.moved_steps: ");
    Serial.println(profile.moved_steps);
    Serial.print('\n');
    sei();
    //chatter.publish( &status_step_count);
    //nh.spinOnce();
    delay(1);
  }

}

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;
      rest = 0;
      TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10)); // Stop the timer,  No clock source
      break;

    case ACCEL:
      digitalWrite(step_pin,!digitalRead(step_pin));
      //delay(1);
      //digitalWrite(step_pin,LOW);
      step_count++;
      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));

      //delay(1);
      //digitalWrite(step_pin,LOW);
      step_count++;
      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));
      step_count++;
      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
      //digitalWrite(step_pin,!digitalRead(step_pin));
      if(profile.accel_count >= 0)
      {
        digitalWrite(en_pin,!digitalRead(en_pin));
        profile.run_state = STOP;
      }

      break;

  }
    profile.first_step_delay = new_first_step_delay;
    profile.moved_steps = step_count;
}

```

speed\_profile.h

```
#ifndef speed_profile_h
#define speed_profile_h

#include <Arduino.h>
#include <ros.h>
#include <std_msgs/Int16.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

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

typedef struct
{
 volatile unsigned char run_state : 3; // Determining the state of the speed profile
 volatile unsigned char dir: 1; // Determining the direction the motor has to move - Start being CCW
 volatile unsigned int first_step_delay; // Period time for the next timer_delay, determines the acceleration rate.
 volatile unsigned int decel_start; //  Determines at which step the deceleration should begin.
 volatile signed int decel_length; // Set the deceleration length
 volatile signed int min_time_delay; //minium time delay c0
 volatile signed int accel_count; // counter used when computing step_delay for acceleration/decelleration.
 volatile unsigned int moved_steps; // Used by ros to publish current tipper position

}speed_profile;

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

```

main.ino

```
#include "speed_profile.h"

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

void loop()
{
  // put your main code here, to run repeatedly:
    Serial.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

    int motor_steps = -3000;//-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
    compute_speed_profile(motor_steps, motor_acceleration, motor_deceleration, motor_speed);
    while(1)
    {

    }
}

```

# Answer
> 2 votes
This is highly inadvisable:

> ```
> cli();
> status_step_count.data = profile.moved_steps;
> Serial.print("profile.moved_steps: ");
> Serial.println(profile.moved_steps);
> Serial.print('\n');
> sei();
>
> ```

Doing serial prints with interrupts off could hang your sketch because the Serial output routines require interrupts on to work.

Later versions of the IDE might not hang completely but will block until the data can be written.

# Answer
> 1 votes
The problem may be due to something you haven't told us about, so the following suggestions are just general ideas.

First, try out whether serial communication works ok at 230400 when your stepper code isn't running. For example, add some debug lines to skip over whatever code turns on interrupts to run the stepper, and see if serial communication is ok.

If serial communication still fails with stepper interrupts off, try lower serial rates, eg 19200 or 9600. In addition, in your Publisher add a reasonable delay, eg half a second or a second, between serial writes. You might also not issue a write whenever the total steps has changed less than a hundred counts, or some similar number.

I'd probably factor toggling `step_pin` out of the `switch`, via code like the following.

```
if (profile.run_state != STOP) {
   // Toggle step_pin by writing 1 to its bit in PINB
   PINB = step_pin_mask; // pin 11 = PB3, so mask is 1<<PB3, ie, 1<<3
   step_count++;
}
switch (profile.run_state) {
   ...

```

Using `digitalRead()` and `digitalWrite()` adds a fair amount of overhead, undesirable in an ISR. (See their source code at garretlab links, `digitalRead()` and `digitalWrite()`) That extra overhead could possibly account for glitches in serial communications.

By contrast, writing a mask bit to an input port is about the fastest way for software to toggle a bit or set of bits. It is, of course, less flexible and less obvious.

# Answer
> 0 votes
That is QUITE a high baud rate. You might want to lower it. I know that Arduinos running at 8MHZ can barely handle 112500. Do not push it too far. I do not know what Arduino you are using but at 16MHZ, don't push it too far. Also make sure that at that baud rate you supply a lot of juice to your Arduino so that it can run more smoothly.

---
Tags: serial, c++
---


# Question
Title: Arduino mini pro as ISP for Atmega329P-PU serial monitor failing
After trying a lot of tutorials and manuals around the web including at least 20 solutions here on StackExchange, I don't know what to try anymore.

My goal is to write a message in the serial monitor window of the Arduino IDE from my ATMEGA328P-PU.

I have written the Arduino bootloader (tried 8 and 16MHz) to the ATMEGA and I use a 'blink' sketch as follows:

```
void setup()  {
 Serial.begin(9600);
 delay(100);
 pinMode(9, OUTPUT);
}

void loop()
{
 digitalWrite(9, HIGH);
 Serial.print("high");
 delay(1000);
 digitalWrite(9, LOW);
 Serial.print("low");
 delay(1000);
}

```

The blinking works fine, the timing looks good, not overly fast or slow.

I connect PIN3 (PCINT17, PD1, TXD) directly to the RX on the Arduino (lower red wire) and the serial monitor responds by returning nonsense like `����������`.

I have checked the baud rate. I have also tested with all other baud rates in combination with and without 8Mhz and 16MHz.

I have tested the entire setup with another ATMEGA328P-PU and using an entirely other PC. Same results.

It is not possible to upload a sketch while leaving the TXD -\> RX connected, so I disconnect this cable when I upload a sketch. I have also tested with only power and TXD -\> RX connected.

I have also tried a few types of resistor between the TXD and RX, one of many tutorials recommended this.

This is what I am trying: http://www.instructables.com/id/Attiny-serial-monitor-using-arduino-walkthrough/

And this is my boards.txt:

```
##############################################################

atmega328bb.name=ATmega328 (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=16000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

```

# Answer
As you can see at image from linked instructables, they've connected `TX` pin from Tiny to `TX` pin on `UNO` through `220R` resistor. This is extremely lousy idea as `UNO` and `Tiny` are both driving `TX` pins.

On the other side you've connected `TX` Output pin from `Target CPU` into `RX` Input of the `Arduino ISP (pro mini)`. `Arduino ISP` returns some error responses from its `TXO` pin directly into the monitor. And it's at different speed I suppose, as default baud rate is `19200` in `Arduino ISP` sketch.

Also using internal `8MHz` oscillator and: `atmega328bb.build.f_cpu=16000000L` means you are running at half speed as compiler and everything else expects. All speeds will be at half rate. Delays twice as long and so on.

Anyway, you can disconnect your USB to Serial converter and connect it directly to the target CPU. Or use two of them. Or just upload bootloader and get rid of ISP.
> 1 votes

# Answer
The thing is that you have 2 ATmegas for 1 uploader. You can't really remove the ATmega on the Pro Mini so I suggest removing the ATmega of an UNO and using the UNO without the ATmega to program your seperate ATmega. Tx to Rx and vice versa. 16MHz will work.
> 0 votes

---
Tags: serial, atmega328, arduino-pro-mini
---


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

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

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

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

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

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

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

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

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

```

# Answer
> 1 votes
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;

```

---
Tags: sketch
---


title: Transmitting Variables over RF

text:
# Question
Title: Transmitting Variables over RF
I'm using the 3715 RF arduino modules and a hc-sr04, and i'm trying to send the distance i get from the ultrasonic over to the arduino with the rf recieving module but i get something like this:

Instead of getting this:

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

# Answer
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
> 0 votes

# Answer
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.
> 3 votes

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


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

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

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

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

Thanks Dave

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

# Answer
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: Atmel studio 7 - my own libraries

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/
> 1 votes

---
Tags: arduino-uno, arduino-ide, avr, atmel-studio
---


title: lcd has no contrast pin

text:
# Question
Title: lcd has no contrast pin
i just bought this lcd. I connected all pins as discripted on this datasheet (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()
{
}

```

# Answer
> 2 votes
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:

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.

---
Tags: lcd
---


# Question
Title: How to set up one second interrupt/ISR for ds3231 RTC
I am able to set up one hz interrupts using millis and other timers, but would like to do it instead using the RTC I have attached (DS3231)

I am not sure how I can do that. Can someone point me to a reference for this?

**EDIT/UPDATE**

I tried to use the square wave to trigger a call back/interrupt, but it's not working for me. I followed what I thought was the wiring diagram here and here and here

I also added a led in the circuit to see if I could figure out something that way, but no dice.

Here is some simple code for a sketch that I think should trigger a 1 second interrupt and call my function:

```
#include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
#include <Time.h>         //http://www.arduino.cc/playground/Code/Time
#include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

const int rtcTimerIntPin = 2;
bool flag = false;

void setup(void)
{
    Serial.begin(9600);
    setSyncProvider(gRTC.get);   // the function to get the time from the RTC
    if (timeStatus() != timeSet)
        Serial.println("Unable to sync with the RTC");
    else
        Serial.println("RTC has set the system time");

    bool stopped = gRTC.oscStopped();
    if (stopped)
    {
        Serial.println("Detected clock power loss - resetting RTC date");
        time_t newTime = cvt_date(__DATE__, __TIME__);
        adjustTime(newTime);
        setTime(newTime);
    }
    else {
        Serial.println("Clock did not lose power");
    }

    pinMode(13, OUTPUT);    // onboard LED
    pinMode(rtcTimerIntPin, INPUT);
    attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);
    gRTC.squareWave(SQWAVE_1_HZ);

    digitalClockDisplay();
}

void rtc_interrupt(void)
{
    flag = true;
}

void loop(void)
{
    //digitalClockDisplay();

    if (flag) {
        digitalWrite(LED_BUILTIN, HIGH);    // flash the led
        digitalClockDisplay();              // this just prints time to serial port
        delay(500);                         // wait a little bit
        digitalWrite(LED_BUILTIN, LOW);     // turn off led
        flag =  false;                      // clear the flag until timer sets it again
    }
}

void digitalClockDisplay()
{
// do something
}

```

# Answer
> 4 votes
This answer addresses the original question of why the interrupts didn't work. I happened to have a DS3231 lying around so I made up a test.

---

## Interrupt vs pin number

First, this is wrong in your code:

> ```
> attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);
>
> ```

You need an interrupt number, not a pin number. This is correct:

```
  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);

```

I also made it a CHANGE interrupt so you get both the rising and falling pulse.

---

## Pull-up resistor

Next, the 1 Hz output needs a pull-up resistor, so you should add that or make it INPUT\_PULLUP like this:

```
  pinMode (rtcTimerIntPin, INPUT_PULLUP);

```

---

## Testing

I used this library from Adafruit.

Adapting one of their examples, and putting in your interrupt code (with my modifications), it worked!

```
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

const byte rtcTimerIntPin = 2;

volatile byte flag = false;

void rtc_interrupt ()
{
  flag = true;
}  // end of rtc_interrupt

void setup () {

  Serial.begin(115200);

  while (!Serial); // for Leonardo/Micro/Zero

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  // enable the 1 Hz output
  rtc.writeSqwPinMode (DS3231_SquareWave1Hz);

  // set up to handle interrupt from 1 Hz pin
  pinMode (LED_BUILTIN, OUTPUT);
  pinMode (rtcTimerIntPin, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);
}

void loop () {
  if (flag) {
    digitalWrite(LED_BUILTIN, HIGH);    // flash the led
    delay(100);                         // wait a little bit
    digitalWrite(LED_BUILTIN, LOW);     // turn off led
    flag =  false;                      // clear the flag until timer sets it again
  }
}

```

# Answer
> 1 votes
Try the following code. It pretty much detects a change in time and when a change has been detected, it will do something. In this case, it will print "do something".

```
#include <DS3231.h>
DS3231 rtc(SDA, SCL);
String t; //time as a string
String s;    //second
String Ps;   //previous second

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

void loop() {
  t = rtc.getTimeStr();             //finding time
  s = t.substring(6, 8);            //finding seconds

  if(s != Ps)                       //if the time has changed
  {
    Serial.println("do something"); //put whatever you want here
    Ps = t.substring(6, 8);         //redeclaring the previous second because it has advanced
  }
}

```

# Answer
> 1 votes
Use this DS3231 library. It has a method to set the squarewave `RTC.squareWave(SQWAVE_1_HZ)`

# Answer
> 1 votes
> I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.

> ```
>  bool flag = false;
>  ...
>  void rtc_interrupt(void)
>  {
>      flag = true;
>  }
>
> ```

Flags set in interrupts should be declared `volatile` otherwise the compiler may optimize away the comparison to the flag. That is:

```
volatile bool flag = false;

```

---

If you are using the Adafruit library (from the page you linked to) then it should have a couple of functions that can be used to detect when the second has changed, for example:

```
DateTime now = rtc.now();
int second = now.second();
unsigned long unixtime = now.unixtime();

```

In either case you just have to check if either one has changed in `loop`. For example:

```
void loop(void)
{
  static unsigned long previousTime = 0;
  DateTime now = rtc.now();
  unsigned long timeNow = now.unixtime();

  if (timeNow != previousTime) {
      digitalWrite(LED_BUILTIN, HIGH);    // flash the led
      digitalClockDisplay();              // this just prints time to serial port
      delay(500);                         // wait a little bit
      digitalWrite(LED_BUILTIN, LOW);     // turn off led
      previousTime = timeNow;             // remember previous time
    }
}

```

---
Tags: rtc, isr
---


title: Arduino char showing as 2 characters

text:
# Question
Title: Arduino char showing as 2 characters
I'm writing the character `1` from a node.js XBee using the code `sp.write("1");` to my Arduino's XBee. Then on my Arduino's XBee I read it like this (inside a loop):

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

```

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

EDIT:

Arduino code:

```
#include <SoftwareSerial.h>

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

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

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

```

Node code:

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

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

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

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

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

```

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

# Answer
> 4 votes
```
 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:

```
  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.

---
Tags: arduino-uno, softwareserial, xbee
---


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

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

# Answer
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!
> 2 votes

---
Tags: sensors
---


title: DigiSpark USB issue

text:
# Question
Title: DigiSpark USB issue
I installed the drivers for x64 and got this:

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:

What can I do in order to fix this?

# Answer
> -2 votes
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 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!

---
Tags: arduino-ide, usb, installation, digispark
---


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

I tried the following approaches without success:

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

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

# Answer
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.
> 0 votes

---
Tags: arduino-uno
---


title: Questions about the Arduino Micro PCB

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

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

# Answer
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* and are special patterns on the board used for aligning a pick-and-place machine when manufacturing.
> 1 votes

# Answer
> • “... 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* in electronics.stackexchange, or *arduino power supply selector* 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.
> 2 votes

# Answer
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.
> 1 votes

---
Tags: usb, arduino-micro, pcb-design
---


# Question
Title: Can I use IR Transmitter/Receiver for heart beat detecting?
Specifically, I want to know if the KY-022 module and KY-005 module can be used for heart beat detecting according to this tutorial?

KY-005:

KY-022:

If so, can you please explain to me how can I achieve such thing with respect to the following:
1- Is there any kind of synchronization between transmitter/receiver?
2- How to get a stable analog value from the receiver?
3- The Correlation between Heart beat rate and the obtained values?

providing circuit sketch will be very helpful but not necessary.
Thanks in advance.

# Answer
> 1 votes
No, you cannot. The sensor you link to has a circuit which attempts to detect IR light modulated at a specific frequency, and produces a digital output. For a heartbeat sensor you need an analog output to feed into far more sophisticated signal processing - effectively the built-in processing gets in the way and means you cannot use it for this purpose.

Additionally, sensors of this type typically have an automatic gain control which means that they desensitize when subjected to continuous signal - they are designed for sources like remote controls where the modulation is itself pulsed on an off in small fractions of a second, so they interpret constant modulated light as noise and soon turn off their output.

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


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

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

Thanks!

# Answer
> 1 votes
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.

---
Tags: c++, interrupt, isr
---


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

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

* "processing.app.debug.RunnerException at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:159) at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78) at processing.app.SketchController.upload(SketchController.java:707) at processing.app.SketchController.exportApplet(SketchController.java:680) at processing.app.Editor$DefaultExportHandler.run(Editor.java:2176) at java.lang.Thread.run(Thread.java:745) Caused by: processing.app.SerialException: Error touching serial port 'COM3'. at processing.app.Serial.touchForCDCReset(Serial.java:87) at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:143) ... 5 more Caused by: jssc.SerialPortException: Port name - COM3; Method name - openPort(); Exception type - Port busy. at jssc.SerialPort.openPort(SerialPort.java:164) at processing.app.Serial.touchForCDCReset(Serial.java:81) ... 6 more";
* "Forcing reset using 1200bps open/close on port COM3". *(Even waiting for hours didn't solve the "forcing")*

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

Is possible to restore the board or is totally lost?

Thanks in advance!

---

*My question is different from the one there (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.*

# Answer
> 2 votes
`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(;;);`

---
Tags: arduino-leonardo
---


# Question
Title: amblone error :85: error: 'TCCR3B' was not declared in this scope - no fullscreen vlc support
getting the following error when trying to upload Amblone code to my Arduino One board:

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

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

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

   TCCR3B = TCCR0B & 0b11111000 | 0x2;

   ^

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

   TCCR4B = TCCR0B & 0b11111000 | 0x2;

   ^

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

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

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

```

Code:

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

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

  State = S_WAIT_FOR_SF;
}

```

# Answer
Amblone doesn't work on an Uno. As stated in the requirements list, you require a Mega.
> 1 votes

# Answer
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.
> 0 votes

---
Tags: arduino-uno
---


title: Male header pins on Arduino Uno

text:
# Question
Title: Male header pins on Arduino Uno
On my board, there are 12 (2 groups of 6, each group consistent of 3 rows of 2 pins) weird male header pins. What are these, and how would you use them?

# Answer
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).

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

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

---

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
> 11 votes

# Answer
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.
> 3 votes

---
Tags: arduino-uno, pins, isp
---


# Question
Title: Switching methods/functions with a button
I am trying to program a basic counter using 7segment display and a button. What I am trying to achieve is the following:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

# Answer
> 3 votes
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 to see why and what to do about it.

# Answer
> 1 votes
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]);
  }
}

```

---
Tags: arduino-uno, 7-segment
---


# Question
Title: Arduino uno board not detected when connected via USB no matter what OS
I was working with Arduino in Win 8.1, when suddenly it stopped work. I tried to reinstall the drivers and IDE several times, but it didn't solved.

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

USB Device Not Recognized in Windows

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

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

```

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

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

Other symptoms:

* In both systems the port tool in IDE is grey, so I can't choose a port.
* When I press the reset button in Arduino, nothing happens.
* The led L (13) is constantly shinning. It never blinks or stops.

Solutions I tried:

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

# Answer
> 1 votes
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.

# Answer
> 0 votes
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.

---
Tags: avr, communication, avrdude
---


title: Get an additional analog pin?

text:
# Question
Title: Get an additional analog pin?
I have the following board:

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?

# Answer
> 2 votes
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.

---
Tags: analogread, input, nodemcu
---


# Question
Title: Issue with photoresistor - the analogRead stays pretty much the same?
**UPDATE:** If I could **I'd downvote myself**. I'm a web developer and as I see that my job will be eaten, I'm trying to expand my skill set. Sometimes I wish I had a second pair of eyes or https://en.wikipedia.org/wiki/Rubber\_duck\_debugging

---

Previously I was asking which sensor use to measure the light: 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

```
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?

# Answer
\***** ITS ANALOG 5 not DIGITAL 5 \*****

Also try doing this:

```
delay(sensorValue*10);

```

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

---
Tags: sensors
---


# Question
Title: Uploading Error: no programmer has been specified
Whenever I upload a code I get this error:

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

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

Sean

# Answer
> 4 votes
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.
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

---
Tags: arduino-uno, programming, arduino-ide, uploading
---


title: why does function affect my ISR?

text:
# Question
Title: why does function affect my ISR?
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?

# Answer
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.
> 3 votes

# Answer
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.
> 2 votes

# Answer
> 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:

```
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;`).
> 0 votes

---
Tags: arduino-uno, c++, debugging, isr
---


# Question
Title: Is it possible to print client IP or MAC address from Arduino WiFi web server?
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.

# Answer
\***** 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
> 1 votes

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


title: connecting ESP8266 to mega 2056

text:
# Question
Title: connecting ESP8266 to mega 2056
im trying to connect wifi module to my MEGA 2560 board. i set up the board as the picture bellow

and my program is as follows

```
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(18,19); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  pinMode(10,OUTPUT);
  digitalWrite(10,LOW);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"mySSID\",\"myPassword\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // build string that is send back to device that is requesting pin toggle
     String content;
     content = "Pin ";
     content += pinNumber;
     content += " is ";

     if(digitalRead(pinNumber))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }

     sendHTTPResponse(connectionId,content);

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendCommand(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

```

but i always recieve the following error

```
Arduino: 1.6.12 (Windows 7), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 228,949 bytes (52%) of program storage space. Maximum is 434,160 bytes.
Global variables use 32,796 bytes (40%) of dynamic memory, leaving 49,124 bytes for local variables. Maximum is 81,920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

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

```

any idea where i went wrong ?

# Answer
* Do not use SoftwareSerial on a hardware serial port. It is pointless.
* Do use a voltage divider to convert the Arduino's 5V TX to the required 3.3V the ESP8266 needs.
* Do not try and program the Arduino as if it were an ESP8266 - it won't work.

I think you are getting a little confused here...
> 1 votes

# Answer
Connect your ESP directly to your PC. Test AT commands first. They will tell you if your good to go or not. Just open your serial monitor and set the baud rate to 115200. Select carriage return and type in AT. If it responds OK. Then your code is the problem. If it doesn't return OK, then your ESP or circuit is the problem.
> 0 votes

---
Tags: arduino-mega, esp8266, java
---


# Question
Title: Using ps2 mouse (PAW3402 / PAW3412) as a distance sensor for arduino
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

# Answer
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.
> 1 votes

# Answer
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
> 0 votes

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


# Question
Title: arduino pro mini analog pins read different values
i need to read a voltage with an arduino pro mini using the analog pins.

I created this simple test code:

```
int sensorValue;
float voltage;

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

void loop() {
  sensorValue = analogRead(A0);
  voltage= sensorValue * (5.0 / 1023.0);
  Serial.println(voltage);
}

```

my setup looks like this:

everything works so far. I get about 4,5v as a result. Now i want to port everything to an arduino pro mini. After i did that i only got 2,5v as a result. I also tried it with different pins and with an other arduino pro mini.

So what did i do wrong? Do i need an other pull-up resistor?

# Answer
> 1 votes
I made a circuit bellow for you. Note that the top resistor is 100 ohm and the bottom one is only 10 ohm. What I did is called a voltage divider. This way you can read voltages up to 50V. Simply connect the positive of your power source that you want to measure to the red wire and the ground of that same source to the black wire.

I also included a code that you could use:

Please notify me if any mistakes were spotted.

```
#define sensor A0 //defining sensor pin

float resistor1 = 100; //you can change it if you want, just make sure you also do it on the circuit
float resistor2 = 10;

float Vmax = (5*resistor1 + 5* resistor2)/resistor2;

void setup() {
  pinMode(sensor, INPUT); //declaring sensor as an output
  Serial.begin(9600);

  Serial.print("Do not input more then (V) : "); // print max input voltage
  Serial.print(Vmax);

  Serial.println(); //skip line
}

void loop() {
  float V = analogRead(sensor); //measuring analog values

  V = analogRead(sensor) * Vmax / 1024

  Serial.println(V); //printing voltage
}

```

---
Tags: voltage-level, analogread
---