# Question
Title: Are my arrays stored in sram or in Flash?
I have the following memory allocation:

```
unsigned char g1[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
g2[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
...

 unsigned char* index[10] = {g1,g2,g3,g4,g5,g6,g7,g8,g9,g0};

```

This is accessed in the following way:

```
unsigned char* getMatch(int input){
  return index[input];
}

```

This is then futher acces using the method of

```
unsigned char store[1024]
unsigned char* temp = getMatch(n);
for(int i=0;i <50;i++){
 store[i]=temp[i];
}

```

and store is then modified and send to an external device.

As my program is randomly failing I think it might be running low on SRAM and was wondering if there is any way to force this memory to be placed in flash. Anybody got an idea?

# Answer
> 5 votes
It's stored in both the FLASH and SRAM because it's initialized array. To store in FLASH only you need use PROGMEM attribute.

```
const unsigned PROGMEM char g1[]= ...

```

You cannot access directly but using *memcpy\_P()* function.

---
Tags: arduino-uno, c++, memory-usage, sram
---


# Question
Title: Unable to retrieve heart rate reading and send to JY-MCU Bluetooth
Hello Arduino Community,

I am encountering an issue trying to retrieve a heart rate reading from an op-amp and instrumentation amplifier and sending it via Bluetooth. I used this website as a basis of my design: http://www.instructables.com/id/Electrocardiograph-Heart-Rate-Monitor/?ALLSTEPS. I would appreciate it if you could take a look at that. Here are a couple of pictures of my design.
Here is the code that I used:

```
    const int  signal = 7;    // Pin connected to the filtered signal from the circuit
    unsigned long time;
    unsigned long frequency;

    // Internal variables
    int period = 2000;
    int starttime = 2000;
    int input = 0;
    int lastinput = 0;
    unsigned long death = 0;

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

     void loop() {
       delay(1000);

       time = millis();
       input = digitalRead(signal);

       if ((input != lastinput)&&(input == HIGH)) {
       // If the pin state has just changed from low to high (edge detector)
       period = time - starttime; // Compute the time between the previous beat and the one that has just been detected
       starttime = time; // Define the new time reference for the next period computing
       death = time;
      }
      lastinput = input; // Save the current pin state for comparison at the next loop iteration

      if (period < 0) {
      frequency = 0;
      }
      else {
      frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
      }

      if ((time - death) > 2000) { // Detect if there is no beat after more than 2 seconds
      Serial.println("dead");
      }

      else {
      char freq[3];

      if (frequency/100 == 0) {
       freq[0] = 32; // Print a space to the first character if the frequency is below 100 bpm
      }
      else {
       freq[0] = frequency/100+48; // Sort the hundreds character and convert it in ASCII
      }
       freq[1] = (frequency/10)%10+48; // Sort the thents character and convert it in ASCII
       freq[2] = frequency%10+48; // Sort the units character and convert it in ASCII

      Serial.print(freq);
      Serial.print("alive! ");
      }

      }`

```

But all I'm getting as output is 'dead'. I am really starting to lose it here since I am a complete amateur with Arduino and circuitry. For reference, I copied the design from this image from the website (this is just an enlarged version): http://www.instructables.com/file/FVBC6TYHOW0HQ7H/?size=ORIGINAL. I would appreciate it if anyone could provide some extra guidance.

# Answer
assuming your circuit works, your code has some serious issues. I rewrote the code for you and also provided a simplified circuit that I have tested and know works. Instead of getting the pulse from the heartbeat detector circuit, we will simulate it on the Arduino by pulsing pin 2 periodically.

```
const int  signal = 7;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

unsigned long myBeatFreq;
unsigned long myBeat;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

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

    previousBeatTime = millis();
    myBeat = previousBeatTime;
}

void loop() {
    if ( millis()-myBeat > myBeatFreq )
    {
      digitalWrite(2, HIGH);
      myBeat=millis();
    }
    else
    {
      digitalWrite(2, LOW);
    }

    input = digitalRead(signal);

    if ((input != lastinput) && (input == HIGH)) {
        // If the pin state has just changed from low to high (edge detector)
        currentBeatTime = millis();

        period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
        previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
    }

    lastinput = input; // Save the current pin state for comparison at the next loop iteration

    // Detect if there is no beat after more than 2 seconds
    if ( (millis() - previousBeatTime) > 2000 )
    {
        Serial.println("dead");
    }
    else
    {
        if (period <= 0)
        {
            frequency = 0;
        }
        else
        {
            frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
        }

        Serial.print(frequency);
        Serial.println(" : alive! ");
    }
}

```
> 1 votes

---
Tags: arduino-uno, bluetooth
---


# Question
Title: How to delay so that LED stays on a bit longer?
I have a circuit with a shift register which controls 8 LEDs: http://node-ardx.org/exercises/5. In code, I created a function `cycle()` cycle through each LED one at a time, but this occurs too quickly on the board. How can I add a delay inside the loop so that each LED stays on for 500ms?

Here's my code:

```
var five = require("johnny-five"), board, shiftRegister;

board = new five.Board();

board.on("ready", function() {
  shiftRegister = new five.ShiftRegister({
    pins: {
      data: 2,
      clock: 3,
      latch: 4
    }
  });

  var bytes = [
    00000001,
    00000010,
    00000100,
    00001000,
    00010000,
    00100000,
    01000000,
    10000000,
    00000000
  ];

  function cycle() {
      for ( var i = 0; i < bytes.length; i++ ) {
          console.log(bytes[i]);
          shiftRegister.send(bytes[i]);
      }
    }

  this.repl.inject({
    sr: shiftRegister
  });

  cycle();

});

```

# Answer
The answer is already provided in the article.

```
  var i = 0;
  function cycle() {
    console.log(bytes[i]);
    sr.send(bits[i]);
    i++;
    if( i<bytes.length )
      setTimeout(cycle, 300);
  }

```
> 1 votes

# Answer
Insert a delay of 500ms?

```
function cycle() {
    for ( var i = 0; i < bytes.length; i++ ) {
        console.log(bytes[i]);
        sr.send(bits[i]);
        delay(500);
    }
  }

```
> 2 votes

---
Tags: arduino-uno, johnny-five
---


title: Arduino - Progamming issue

text:
# Question
Title: Arduino - Progamming issue
my first post here.

Anyway I'm working on a Simon Says game. I have a weird bug with the function that reads button input.

This is the code:

```
int deBounce(int count){
  int pressed=-1;
  int laastButtons[3]; // save the previous deBounce read.
  for(int x; x<4; x++)
  {
    laastButtons[x] = lastButtons[x];
    lastButtons[x] = !digitalRead(button[x]);
    if(lastButtons[x] == true)
    {
      delay(50);
      lastButtons[x] = !digitalRead(button[x]);
      if(lastButtons[x] == 1){ pressed = x;}
      nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
    }
  }
  if((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) > 1)
  {
    ntln("ERROR: dont press more than one button at a time. ");
  }
  if( ((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) == 1 ) && !laastButtons[pressed] && (pressed != -1) ) {
    pressButtons[count] = pressed;
    nt("Pressed!, ID: ");nt(count); nt(" Button ID ");ntln(pressed);
    return count++;
  }else return count;
}

```

This is what I recieve in the Serial Monitor if I press one of the buttons.

> Pressed!, Button ID: 3 pressed: -1 state 1

How is that possible? Note the lines where that line is printed and the line above it. Seems like that if should run, but the line pressed = x; doesn't function. Note that, nt and ntln are just a short for Serial.print. I have this weird bug and sometimes it seems like the chip is glitching!

Another question is- I tried attaching interrupt and it didn't worked, Is it possible that my board is not compatiable with them? (It's not original).

Thanks.

EDIT:

After Majenko helped me figure it out, The thing that created the bug was that I expected a x==0, but I didn't define it in the for loop.

Before:

```
for(int x; x<4; x++)

```

After:

```
for(int x=0; x<4; x++)

```

Thanks again Majenko!

# Answer
```
int laastButtons[3]; // save the previous deBounce read.
for(int x; x<4; x++)
{
   laastButtons[x] = lastButtons[x];

```

Well, there's a common bug right away. An array with three slices, numbered 0, 1 and 2, and you're accessing them with a loop that counts from 0 to 3.

Spot the error.

Also, in the for loop, what number does it start counting from?

And now for your "bug". This block of code:

```
if(lastButtons[x] == true)
{
  delay(50);
  lastButtons[x] = !digitalRead(button[x]);
  if(lastButtons[x] == 1){ pressed = x;}
  nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
}

```

I think you have it slightly wrong. Let's convert it into plain english:

* If button is pressed:
    + Delay 50 ms
    + Read button again
    + If button is pressed:
        - Set *pressed* to the button number
    + Print the button message

Note the indenting, which highlights what gets executed for what IF statement. The print is going to happen regardless of the setting of the *pressed* variable.

I think the structure you wanted is:

* If button is pressed:
    + Delay 50 ms
    + Read button again
    + If button is pressed:
        - Set *pressed* to the button number
        - Print the button message

In that layout the second If is controlling both the setting of the *pressed* variable as well as whether or not to print the Pressed! message.

```
if(lastButtons[x] == 1){ pressed = x;}

```

That line is saying "If last buttons X is 1, then set pressed to X. That is all it is doing. Nothing more, nothing less.
> 6 votes

---
Tags: serial, debugging
---


# Question
Title: How to update a variable in an ISR using Timers
I'm trying to check the frequency of Timer3 using a counter. The value of the counter, declared as volatile, is incremented in the ISR and every second the sum is shown in the main loop and the value reset to zero.

The timer has been set up correctly. (If I choose a 3Hz timer I can see the led blinking)

**The problem**

The counter isn't incremented. Here is the output:

```
Setup Completed
tick: 1
tick: 0
tick: 0
tick: 0

```

**CODE**

```
volatile int cont = 0;

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

  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20; // 800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  //digitalWrite(13, digitalRead(13) ^ 1);
  cont++;
}

```

**EDIT** This timer is used to read an anlog value from an accelerometer and store it in an array of float. But at the moment I'm stuck on this update issue.

**SOLUTION 1** Thanks to Gerben

```
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20; // 20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont = 0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

```

**SOLUTION 2** Thanks to BrettM

```
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B =  20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  //TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  Serial.println(cont);
  cont = 0;
  delay(1000);

}

ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

```

# Answer
In CTC mode the top is `OCR3A`, not `OCR3B`!

After that `TIMSK3 |= (1 << OCIE3B);` should also be changed to `TIMSK3 |= (1 << OCIE3A);`, and `ISR(TIMER3_COMPB_vect)` to `ISR(TIMER3_COMPA_vect)`

For 3Hz, `OCR3A` should be 5208, not 20.

Technically `TCCR3B |= (1 << WGM12);` should be `TCCR3B |= (1 << WGM32);`
> 5 votes

# Answer
It seems my answer to this question was previously incomplete, thanks for pointing out that CTC mode only works with OCR3A Gerben. I apologize for not testing an answer before I post it.

Given the information only in this question Gerben's answer is complete, but since your other question implies that you cannot use OCR3A due to the Servo library I'll add a bit. (I've also edited that answer)

you can emulate the behavior of CTC mode by setting TCNT3 to 0 in your interrupt routine. Remember to remove the line that turns on CTC mode in your code.

I've tested your code with this ISR:

```
ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

```

and this configuration of the timer registers

```
OCR3B = 5208; // 800Hz 5; // 3 Hz
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR3B |= (1 << CS30) | (1 << CS32);
// enable timer compare interrupt:
TIMSK3 |= (1 << OCIE3B);

```

This might be a bit less accurate at high frequencies than CTC, I'm not sure, but at 3Hz it worked perfectly. Notice that 5208 was the correct OCR value, not 20 (again thanks to Gerben).
> 3 votes

---
Tags: arduino-mega, interrupt, timers, variables, isr
---


# Question
Title: How to prevent Arduino compiler from merging changing of port pin outputs into a single operation
I want to set one pin's output value, and then set a different pin's output value so that the two pins change value one after the other. However, the compiler optimises the two calls to change both pins in one go.

`PORTD |= _BV(0); //set pd0 to high
PORTD |= _BV(1); //set pd1 to high
PORTD &= ~(_BV(1)); //set pd1 to low`

The two pins go high simultaneously. I tried inserting a NOP between these but it doesn't change behaviour.

(I originally intended to include an oscilloscope screengrab to show what was happening - that's how I knew (or got the wrong impression) that the two pins were changing at the same time. But the photo wasn't shifting from my Nexus 7 for me to access it from my laptop.)

# Answer
> 7 votes
I certainly can't duplicate what you are saying. The small code snippet:

```
void setup() {
    PORTD |= _BV(0);
    PORTD |= _BV(1);
    PORTD &= ~(_BV(1));
}

void loop() {
}

```

compiles into:

```
000000a6 <setup>:
  a6:   58 9a           sbi 0x0b, 0 ; 11
  a8:   59 9a           sbi 0x0b, 1 ; 11
  aa:   59 98           cbi 0x0b, 1 ; 11
  ac:   08 95           ret

000000ae <loop>:
  ae:   08 95           ret

```

That is clearly two separate bit sets followed by a bit clear.

I am using UECIDE that is set to use GCC 4.3.2

If I switch to GCC 4.8.1 instead, the code generated is identical.

Even turning on full -O3 optimization I still get the same results.

So how are you determining that it's happening at the same time?

---
Tags: c
---


# Question
Title: Difference between void setup() and void setup(void)
As it says in the title. I have been searching but I cant seem to find the answer.

What is the difference between void setup() and void setup(void) as well as void loop() and void loop(void)?

# Answer
Absolutely nothing, in modern versions of C and C++. Specifying no arguments is the same as specifying `void`.

In old versions of C a function with no arguments took a single implicit `int` argument or allowed you to specify the arguments on a separate line, but no one uses anything like that nowadays.
> 8 votes

---
Tags: programming, c++
---


title: AVR ATmega328p-pu operating circuit?

text:
# Question
Title: AVR ATmega328p-pu operating circuit?
I used to work with PIC micro-controller so i know what it needs to work from operating circuit to crystal oscillators needed and other components to power it up , my question here where can i find the operating circuit for ATmega32p-pu and other AVR models . or all i need to do is to give it +5v and gnd and it will work ?

# Answer
> 1 votes
You're looking for this I think? How to set up an Arduino on a breadboard.

---
Tags: avr, arduino-micro
---


# Question
Title: Feeble click in relay but it doesn't get activated when connected to Arduino circuit
I have an Arduino uno board and I have a soil moisture sensor

1. connected the digital output pin of the sensor to Arduino input pin
2. connected an output pin of Arduino to the INPUT pin of the relay board
3. programmed the Arduino such that if input is HIGH then the OUTPUT should be HIGH as well
4. connected 5 v pin of Arduino to vcc of the relay board
5. connected gnd pin of Arduino to gnd of the relay board

When my sensor outputs a HIGH DO (digital output), the relay only creates a feeble click sound and does not get activated. The Relay board LED does light up but the relay itself does not work (NC remains closed and NO remains open).

Do I need to supply an external VCC to the relay board? If yes then how should I set up the circuit?

A picture of the relay board is attached. You are right ... it is a 12 v relay. Do I need a 12 v external power source with IN1 coming from Arduino? Any help will be much appreciated.

# Answer
> 6 votes
You need to join the ground of the external supply to the ground being supplied from the Arduino. The 12V supply must be capable of at least 100ma

There appears to be a transistor and resistor on the board. This is probably to drive the relay coil from the Arduino. However, I would need to look at the circuit diagram of the board to be certain. Can you supply images of the copper side and component side of the board to see what the connections are.

Ideally the circuit diagram from the manufacturer would be even better.

---
Tags: arduino-uno, relay
---


# Question
Title: How to detect high/low signal from a DC servo motor using arduino?
I am a newbie to Arduino.

What I am going to do is to change my roll to roll printer to flatbed printer. Rather using print roller, I decided to move the bed from a stepper motor.I know how to run the stepper motor for specific distance using arduino.

So I need to cheat printer to think that its roller is working and media is going through it.But actually what I am going to do is to monitor the printer motor running or not from arduino input and if the printer motor is running stepper motor will turn or if motor stops stepper motor must stop.

What my problem is how can I read that the dc servo motor status? How would I need to wire arduino input to servo motor to get the status.

Please show me some light on this.Sorry if this is a newbie question.

Thank you.

# Answer
Do you need to check if it is stalled? Or simply running?

Either way, you could check the voltage with an analogue input, compare against a threshold (empirically set) & use that. Take the voltage reading from the non-commoned side of the motor, after any driver circuit.

If you want stalled, a small resistance would help, if just running then you could get away with a digital input.

If the voltages aren't matched then a resistance divider chain would be necessary.
> 1 votes

# Answer
I would definitely use an Opto-Isolator between the motor and the Arduino for these reasons.

You will have a problems with the grounds as the motor reverses. The 24V supply. If you get something slightly wrong then it will take out the Arduino and the PC connected to it. The motor will generate large voltage spikes( circa 50..300Volts) under certain condions. The Arduino and the PC connected to it will complain, but not for long!
> 1 votes

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


# Question
Title: AnalogRead too slow... Faster alternative?
For a program that I'm working on, I want to get an accurate reading from a noisy pressure sensor. So, the idea that I have is to do a thousand AnalogRead commands on the same port very quickly and then average them. The pressure readings become very precise, however, the program that I am running becomes very slow. I need my program to be orders of magnitude faster.

I'm sure that there's a faster way to do AnalogRead commands, especially because I am requesting the same port over and over. Maybe there's a way that I can take lower resolutions of readings and then average those? I don't know. Can anyone help me? I am an amateur Arduino user looking to learn.

I have done a little bit of research on my own and had trouble finding concrete examples.

# Answer
Ignacio's proposal is surely a good one if you really need higher sample rates, but I would try another approach:
Average your signal before sampling it! This can be done by connecting a simple RC lowpass to your AD input.
With that you get rid off those high frequency noise you don't need, but without wasting CPU time.
> 3 votes

# Answer
The ADC is rated at up to 15K samples per second. So reading a 1000 is not a problem. However, care must be taken in the Vcc used for the ADC (AVcc). It must be noise free otherwise it will introduce noise into the digital readings, when it actually isn't there in the analogue signal.

See page 256 on the Atmel 328 datasheet for further information.

The RC Lowpass filter should also be used on the AVcc supply, as well as the pressure sensor signal.

I just thought! Are you using a Serial.print() after each analogRead()??? If so, the serial port will drastically slow down the sample rate. If this is the case perform a number of analogRead()s then use Serial.print() after some form of processing.
> 0 votes

---
Tags: arduino-due, analogread
---


title: Sweep with two shift registers

text:
# Question
Title: Sweep with two shift registers
I am working with 8 dual color LED's and 2 shift registers. My connections are in place. But I do not understand how to work with 2 shift registers.

So I am trying to make this: turn the first led on, turn the first led of, go to the next led, turn it on, turn in off, etc...

I do not know how to jump from the first shift register to the second shift register when the last LED of the first shift register is turned off.

# Answer
> 2 votes
Exactly the same as when you're trying to keep them dark when lighting an LED with the first register: shift two bytes.

The first byte shifts into the first register to begin with, and then *out* of the first register and *into* the second register when you shift the second byte into the first register. Just make sure only the appropriate bits are set in both bytes and you're good to go.

---
Tags: arduino-uno, programming, c, code-optimization
---


# Question
Title: how to block Arduino code until a certain event?
i am tring to enter a series of numbers using "keypad" to different variables..when simulate the code on proteus it only took the first "getkey()" function and ignored the rest .. SO, How can i block an arduino code until a key is pressed by keypad, in other words prevent the rest of code from being executed before a key is pressed

# Answer
It depends on how the "keypad" is implemented. If you've got it hooked up to a hardware interrupt, then you only need to add an interrupt handler for that event.

On the other hand, the more "straight-forward" implementation is that you have to poll the pins to see if a key was pressed. Simply do that in a loop until you see a key press, call your event-handler method, and then continue to loop.
> 1 votes

---
Tags: arduino-uno
---


title: Where can I see the output of printf?

text:
# Question
Title: Where can I see the output of printf?
I would like to know where I can see the output when I use the command `printf`. I am programming using the Arduino interface.

## Update

I'll add a few lines of code for better understanding:

```
#include <stdio.h>

int main(void)
{
    printf("Hello World");

    return 0;
}

```

# Answer
If you're working with the standard Arduino environment and libraries then `printf()` won't display anything anywhere. The reason is that microcontrollers could be connected to any number of different output/communication devices in any way. `stdio` would have no idea how or where to send the data.

The most common approach to outputting text from an Arduino (particularly during development) is to send it to the primary UART port using `Serial.begin()` and `Serial.print()`. If the Arduino is connected to your computer via USB then the Arduino IDE's serial monitor should display the result.

If you *really* want to use `printf()` though then it is possible to make it work (or implement similar functionality). A full explanation is on this page:
> 7 votes

# Answer
In `setup()`, start serial and choose your speed:

```
Serial.begin(9600);

```

Wherever you want to write to serial:

```
Serial.write("write this");

```

Wherever you want a newline:

```
Serial.println();

```

## example

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.write("Hello World");

}

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

}

```
> 2 votes

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


title: Button reading not going off

text:
# Question
Title: Button reading not going off
I made a circuit which in my intentions would allow me to toggle a LED dimming loop.

Problem is that once I push the button the first time pushing it a second time doesn't toggle the LED loop off.

Here is the code:

```
const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;

int old_val = LOW;
int state = 0;
int i = 0;

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

}

void loop()
{
  val = digitalRead(BUTTON);

  if ((val == HIGH) && (old_val==LOW))
  {
    state = 1 - state;
    delay(10);
  }

  old_val = val;

  if (state == 1)
  {
    for (i = 0; i < 255; i++)  // loop from 0 to 254 (fade in)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms because analogWrite
      // is instantaneous and we would
      // not see any change
    }

    for (i = 255; i > 0; i--) // loop from 255 to 1 (fade out)
    {
      analogWrite(LED, i); // set the LED brightness
      delay(10);           // Wait 10ms
    }
  } else
  {
    analogWrite(LED, 0);
  }

  if ((val == LOW) && (old_val == HIGH))
  {
    delay(10);
  }
}

```

Here is the circuit scheme:

I would be interested both in learning what the problem is AND learning any mental methods I can apply to debug in such situations.

# Answer
> 0 votes
While the led is fading in and out (which takes 5 seconds), the state of the button is never checked. So you'd need to have the button released for at least 5 seconds (so old\_val becomes LOW), and then pressed exactly we the led is faded out (again, 5 seconds later). So try keeping the button pressed for at least 5 seconds.

You probably want to rewrite your code, so the button is more 'responsive'. Below I added an example of how to do this.

```
const int LED = 9; // the pin for the LED
const int BUTTON = 7;

int val = LOW;
int old_val = LOW;

bool fadeLed = false;
int brightness = 0;//current pwm value
int direction = 1;// 1 is brightness is increasing, -1 if brightness is decreasing

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop()
{

  /* check the button */
  val = digitalRead(BUTTON);
  if ((val == HIGH) && (old_val==LOW))
  {
    // button pressed ( called only once per press )
    fadeLed = !fadeLed;// invert boolean
  }
  old_val = val;

  /* update the leds brightness */
  if( fadeLed )
  {
    // fade led in and out
    if( brightness==0 )
      direction = 1;//change direction is minimum value reached
    if( brightness==255 )
      direction = -1;//change direction is maximum value reached
    brightness += direction;// increase/decrease brightness
  }
  else
  {
    // fadeLed is disabled, so only decrease brightness till it reaches zero
    if( brightness>0 )
      brightness--;
  }

  analogWrite(LED, brightness); // set the LED brightness
  delay(10);           // Wait 10ms because analogWrite
                       // is instantaneous and we would
                       // not see any change

}

```

Any questions about the code; just let me know.

---
Tags: arduino-uno, led, button
---


title: Comparing a char with the symbols '.-'

text:
# Question
Title: Comparing a char with the symbols '.-'
I'm using the Arduino software to create a Morse code decoder using the serial monitor.

I enter a Morse code such as `.-` as a text string and it's displayed in the LCD as a alphanumeric text. So if I enter `.-` into the serial Monitor, `A` is displayed on the LCD. But it only works for single symbols, not the dot and dash together.

Is there a way to make the if statement as seen below accept both the dots and dashes together?

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  lcd.begin(16, 2);

 Serial.begin(9600);
}

void loop()
{
  char schar;

  if (Serial.available())
  {
    schar = Serial.read();

    Serial.write(schar);

    if (schar== '.-' ){
      Serial.write('A');
      lcd.print('a');
    }
  }
}

```

# Answer
> 4 votes
Your first problem is that there is no way for schar to contain two characters in the first place; Since schar is declared as a char, it can only contain one character.

You need to make a String out of the serial input. `Serial.read()` only returns one character at a time, so you will need to make sure you iterate over all the input. Then you can compare the whole String with another, and see if both characters match at once. Just look at this code to see different ways of manipulating Strings: http://arduino.cc/en/Tutorial/StringComparisonOperators

Notice that string literals use double quotes, not single quotes like characters.

Also, be aware of the fact that `string` and `String` are different things. lowercase 's' is an array of characters, capitol 'S' is the class that has those useful string comparison member functions. The class is more resource intensive, but I think in your case the readability and convenience are worth it.

# Answer
> 2 votes
You could use C strings, (type `char*`) or C++ String objects (type `String`). Both would work.

If you use C strings, you'll need to use functions like `strcmp()` from the C library to see if your input string matches a particular morse sequence.

If you use C++ String objects, you'll need to use the methods of that class. I'm less familiar with that class.

If you have single Morse characters, matching them up is pretty easy. If you have a continuous stream of dots and dashes, though, it's a much thornier problem. You need a way to figure out the boundary between characters. Morse characters can be sequences of between 1 and 5 dots and dashes.

Unless there are extra delays between the dots/dashes for a character, I'm not sure how you figure out where the boundaries are. There are already computer Morse code readers, though, so this must be a "solved problem". I'd do some googling.

# Answer
> 1 votes
`schar` is a `char` variable of size 1. It makes no sense to compare it with `'.-'`, which is supposed to be a string. Declare a `char[3]` array, fill it as string and use the `strcmp` function. It's elementary C knowledge.

---
Tags: c
---


title: Arduino PWM malfunctioning

text:
# Question
Title: Arduino PWM malfunctioning
I am controlling 4 motors using the PWM ports on an Arduino Uno (3,9,10,11). For some reason, the motor hooked up to port 11 doesn't move with my current code. I know it's a code issue because I can create a new basic code that just moves the motor and it works fine, but for some reason it doesn't in this code.

```
#include <SPI.h>
#include <Pixy.h>

Pixy pixy;

int personX = 0;
int offCount = 0;

void setup()
{
  pinMode(3, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  Serial.begin(9600);
  while (! Serial);
  pixy.init();
}

void loop()
{
  static int i = 0;
  int j;
  uint16_t blocks;
  char buf[32];

  blocks = pixy.getBlocks();

  if (blocks)
  {
    personX = pixy.blocks[0].x;
  }

  if (blocks){
    Serial.println(personX);
    if (personX < 110){
      analogWrite(11, 130);
      analogWrite(3, 130);
      analogWrite(9, 250);
      analogWrite(10, 250);
    } else if (personX > 190){
      analogWrite(11, 250);
      analogWrite(3, 250);
      analogWrite(9, 130);
      analogWrite(10, 130);
    } else {
      analogWrite(11, 190);
      analogWrite(3, 190);
      analogWrite(9, 190);
      analogWrite(10, 190);
    }
    offCount = 0;
  } else {
    if (offCount < 1000){
      offCount = offCount + 1;
    } else {
      analogWrite(11, 190);
      analogWrite(3, 190);
      analogWrite(9, 190);
      analogWrite(10, 190);
    }
  }
}

```

Also, when I take the motor and swap it with another, the old one works in the new PWM port, but the new one stops working once I put it in port 11.

# Answer
> 9 votes
Pin 11 is shared between both PWM and SPI. By activating SPI you've disabled PWM from working on that pin. Either use another PWM pin instead, or switch to software SPI on different pins.

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


title: Is arduino starter kit disappearing?

text:
# Question
Title: Is arduino starter kit disappearing?
It seems they stop the production of arduino starter kit (official), it's hard to find it on pro website. Is there an other very good starter kit to start ? I mean I would like to try everything on small given project before starting my own project.

# Answer
> 2 votes
AFAIK, it's still available on the arduino store website

# Answer
> 1 votes
Make has one: Getting Started with Arduino Kit v3.0

# Answer
> 0 votes
I recommmend you this one: Beginner Learning Kit for Arduino, but they do not add the code here.

---
Tags: arduino-uno
---


title: Is this set up appropriate?

text:
# Question
Title: Is this set up appropriate?
Hello Internet Arduino enthusiasts!

I'm totally new to Arduino and as my first project, I'd like to make a controller connected to computer A (the master) and computers B and C as 'slaves'.

The master would simply send commands as USB mouse and USB keyboard inputs to slave computers through an Arduino controller. Think of it as a hardware KVM switch (without the V(ideo)).

Now, I'm planning to work on that during the Christmas vacations, so I need to order the parts now to receive them in time.

I was thinking I could use these parts:

1. Arduino Due (because it has the capability to send keyboard and mouse input)
2. 2 SparkFun FTDI Basic Breakout - 5V, one for the mouse, one for the keyboard (per target computer) (https://www.sparkfun.com/products/9716) (because I can convert it to a 3.3v, what the Due is using)

Please consider:

* The price is not really an issue for now.
* I'm not worried to much about the programming.
* I'll figure out how to make it work once I have the time and the items.
* I know someone who has a starter kit from SparkFun, and there is an electronic store closeby, so I'm not worried about the wires.

Will I be able to make what I'd like with those basic parts, or am I missing something?

Thanks!

# Answer
> 0 votes
You need:

* two MCUs that can act as USB devices (one per slave),
* some way of getting the commands from the master to the MCUs

That means two Arduino Dues (or Arduino Leonardos, or SparkFun ATmega32U4 breakout boards, etc.) and one USB device of some sort that you can talk to and have send commands to the MCUs.

And perhaps something to transport the commands from the master to the slaves, but you need to think about the programming for that first since the transport and the programming will be very closely connected.

---
Tags: arduino-due, usb
---


title: Where do serialport names come from?

text:
# Question
Title: Where do serialport names come from?
I'm currently writing a tool that automatically detects connected arduinos and provides a one-button solution for flashing new firmware. I've got a couple of arduinos at home (Diecimilla, Uno R3 SMD and some nanos from china) and each type presents with a different serial port name.

**Questions**

* Can someone explain where these port names come from?
* Can I assume that `/dev/cu.usbserial-A9UPDRZB` is, atleast in most cases, an arduino nano?
* Are there other ways to identify the type of the board?
* Is the name of the serial port some kind of hash generated from informations retrieved from the device?

# Answer
> 4 votes
You cannot assume anything about serial port names. It's a choice of the operating system, and even if you find the algorithm, there's no guarantee it won't change in the future.

As a reference implementation, the Arduino IDE 1.5.x uses VID (Vendor ID) and PID (Product ID) to identify a board.

Because accessing such information depends on the underlying operating system, the IDE uses three strategies: on windows, it runs a program called ListComPorts.exe, on macosx it uses CLI tool `/usr/sbin/system_profiler`, on linux CLI tool `udevadm`

---
Tags: serial
---


# Question
Title: Newbie needing help with debounce errors in arduino
So I found a code I would like to use and not sure how to edit the code properly.

```
#include <Debounce.h>

void matrix(char matrix[7]) {
  int map[10];
  map[0] = 2;
  map[1] = 3;
  map[2] = 4;
  map[3] = 5;
  map[4] = 6;
  map[5] = 7;
  map[6] = 8;
  map[7] = 9;

  int i=0;
  for(i=0;i<=7; i++) {
   if(matrix[i] == 0x30) { // 0x31=1, 0x30=0
      Serial.println(map[i]);
      digitalWrite(map[i],LOW);
   }
   else digitalWrite(map[i],HIGH);
  }
}

void show(int number) {
  switch(number) {
    case 0:
      matrix("11111100");
      break;
    case 1:
      matrix("01100000");
      break;
    case 2:
      matrix("11011010");
      break;
    case 3:
      matrix("11110010");
      break;
    case 4:
      matrix("01100110");
      break;
    case 5:
      matrix("10110110");
      break;
    case 6:
      matrix("10111110");
      break;
    case 7:
      matrix("11100000");
      break;
    case 8:
      matrix("11111110");
      break;
    case 9:
      matrix("11110110");
      break;
    default:
      matrix("00000010");
      break;
  }
}

#define t1 13
#define t2 12

Debounce debouncert1 = Debounce( 20 , t1 );
Debounce debouncert2 = Debounce( 20 , t2 );

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

  // initialize the digital pin as an output:
  pinMode(13, INPUT);
  pinMode(12, INPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

int setCountPlus(int count){
  if(count == 9){
    count = 1;
  }
  else{
    count++;
    count %= 10;
  }
  return count;
}

int setCountMinus(int count){
  if(count==1){
    count = 9;
  }
  else{
  count--;
  count %= 10;
  }
  return count;
}

void loop()
{
  int i=-1;
  show(i);
  while(1){
    debouncert1.update();
    debouncert2.update();
    if(debouncert1.read()){
      i=setCountPlus(i);
    }
    if(debouncert2.read()){
      i=setCountMinus(i);
    }
    if(i==10){
      i=1;
    }
    show(i);
    delay(250);
  }
}

```

as for the errors.

sketch 65: error: 'Debounce' does not name a type
sketch 66: error: 'Debounce' does not name a type
sketch .ino: In function 'void loop()':
sketch 108: error: 'debouncert1' was not declared in this scope
sketch 109: error: 'debouncert2' was not declared in this scope

Any help would be great on fixing the code to stop getting errors.

# Answer
> 1 votes
In the description of Debounce, you'll find the hint that this library is **outdated** and no longer maintained.

Its successors, **Bounce1** and, more recently, **Bounce2** are available from a **github** repository by Thomas Fredericks, Bounce-Arduino-Wiring.

Instead of simply downloading and unzipping the archive to `${HOME}/sketchbook/libraries`, you might want to consider that this is the right moment to get familiar with git repositories as an easily updatable source for third-party libraries.

Supposed that you're on a GNU/Linux system with `git` installed, you would

```
cd /${HOME}/sketchbook/libraries
git clone https://github.com/thomasfredericks/Bounce-Arduino-Wiring.git

```

to obtain a clone of the necessary data.

If the name of the directory of the library contains dashes (`-`), you'll have to change this name: remove the dashes or replace them with underscores (`_`). Names with dashes aren't valid!

Once in a while, you would change to the directory of the respective library and simply run `git pull` to update your local copy to the latest version of the repository.

# Answer
> 1 votes
Depending on the switch type: -SPDT (SIngle Pole Double Throw) - You would use a Cross Coupled NAND Gates (Flip Flop, Set Reset) This will set true to the side it sees power at from the switch and if it bounces it can't change state until the switch touch the other contact.

-SPST (Single Pole Single Throw) - You can use a software debounce where you would detect a signal and then wait for 10ms then read again and if there is a signal still, it is a debounced signal. --OR-- You can use capacitors to help extend the life of a signal.

so debounce code

```
bool sw13=false;
bool sw12=false;
while(1){
if(digitalRead(13)==HIGH && !sw13){
  delay(20); //Delay For 20ms
  if(digitalRead(13)==HIGH){
    i=setCountPlus(i);
    sw13=true;
  }
}else{
    sw13=false;
}
if(digitalRead(12)==HIGH && !sw12){
  delay(20);
  if(digitalRead(12)==HIGH){
    i=setCountMinus(i);
    sw12=true;
  }
}else{
    sw12=false;
}
if(i==10){
  i=1;
}
//show(i);
delay(250);
}

```

---
Tags: library, debounce
---


# Question
Title: Going from one shift register to two shift registers
I am able to control one shift register with this shift function:

```
void shift (int pin) {
  shiftOut(ds,shcp,MSBFIRST,pin);
  digitalWrite(stcp,HIGH);
  delay(100);
  digitalWrite(stcp,LOW);
}

```

but when I move to 2 shift registers it does not add up.. how do I need to adapt this method to make it work with 2 shift registers when I am going from 8 leds to 16 leds?

My second register now just copies the first register.. I want the second register to continue instead of repeat

# Answer
> 5 votes
It sounds like the primary issue is how you've connected the two shift registers. You just need the bit shifting out of the first one to shift into the second one so they act, together, as one longer shift register.

The example pictured is described in full here, under the heading "Example 2": http://arduino.cc/en/tutorial/ShiftOut

As Klaus mentioned, you want to first `ShiftOut` the byte you intend to wind up in the second resister, then `ShiftOut` the byte for the first register. This will push your first byte through to the second register.

# Answer
> 1 votes
split the data into 2 bytes, and then send those, one after the other

```
void shift (int pin) {
  byte data1 = 0;//shift register 1
  byte data2 = 0;//shift register 2
  if( pin<8 )
    data1 = (1<<pin);
  else
    data2 = (1<<(pin-8));
  shiftOut(ds,shcp,MSBFIRST,data2);//note that you send the data for shift register 2 first
  shiftOut(ds,shcp,MSBFIRST,data1);
  digitalWrite(stcp,HIGH);
  delay(100);//why wait this long?
  digitalWrite(stcp,LOW);
}

```

# Answer
> 0 votes
* Configure SPI
* Hook up your shift registers
    + common `SS`
    + common `CLK`
    + `QH*` of the first shift register to `SER` of the next

In order to transfer the bytes

* Pull `SS` low
* `ShiftOut` first byte
* `ShiftOut` next byte
* Pull `SS` high again to finish the SPI transfer

---

**UPDATE**

*This is untested, just out of memory!*

```
#include<SPI.h>
// note that the pins for CLK and MOSI are defined here

unsigned int ledPattern = 0b1111000011110000;
// store the state for 16 LEDs here

void setup(void)
{
    pinMode(SS, OUTPUT);
    digitalWrite(SS, HIGH);
    SPI.setDataMode(3);
    SPI.setClockDivider(4);
    SPI.setBitOrder(MSBFIRST);

    // let's transfer 2 bytes
    digitalWrite(SS, LOW);
    SPI.transfer(ledPattern & 0xff00;) // high byte
    SPI.transfer(ledPattern & 0x00ff;) // low byte
    digitalWrite(SS, HIGH);
}

```

---

**UPDATE II**

You are by no means limited to 2 shift registers! In 2013, we did a 8x11 LED display for an upcycling art project. Eleven 74HC595 were chained to display some patterns. Each 'pixel' consisted of 3 12V SMD LEDs on a stripe. Consequently, each shift register was connected to an `ULN2803`.

I just uploaded a video from the construction phase, showing a test pattern.

# Answer
> 0 votes
```
void shift(int pin) {
  digitalWrite(stcp, LOW);

  // shift the bits out:
  shiftOut(ds, shcp, MSBFIRST, pin >> 8);
  shiftOut(ds, shcp, MSBFIRST, pin);
  // turn on the output so the LEDs can light up:
  digitalWrite(stcp, HIGH);

  delay(100);
}

```

---
Tags: arduino-uno, shift-register
---


title: Checking connection/ communication

text:
# Question
Title: Checking connection/ communication
Can I ping or “hello world” an Arduino.
Background: My son and I bought a 3-D printer kit. (EZ-3D)

We are having some issues talking with it. (Well we can't talk at all.) So we thought to upload the firmware,

It’s an Arduino Mega 2560, and when we upload the Arduino times out… but it takes a minute or two. Can I try some simpler program just to try and talk to the Arduino?

I’m almost a “virgin” Arduino user so be gentle.

# Answer
Adafruit has a good set of guides to getting started with arduino: https://learn.adafruit.com/series/learn-arduino

The "Blink" program is the equivalent of "hello world".

When testing you probably should disconnect the Arduino from the 3D printer.
> 1 votes

---
Tags: arduino-mega, communication
---


# Question
Title: Creating arduino library linking question
I know how to create my own arduino library and use it. I am using Xcode to create a c++ project. I have the arduino library files(Servo, Wire, Keypad, etc). If I want to include the Servo.h library file in my created library, how do I go about linking that? For some reason, I can't just add the Servo.h/.cpp files in my project because then I get other linking file problems that Servo.h references and are not linked in my project. Has anyone done this before?

# Answer
I can't speak for Xcode, but in general with Arduino IDEs (UECIDE excepting) if you use a library within another library, that library also has to be #included in the main sketch. That is the only way most IDEs determine which libraries need to be compiled into the finished program.

That's one of the first targets I had for UECIDE - to enable fully recursive library compilation. Any libraries found within the master header of a library will also be included for compilation - and any found in those libraries, etc. It took a lot of work (and it's by no means 100% perfect), which is why so few others do it and leave it up to the programmer to ensure the inclusion of the right sub-libraries in their sketch.
> 0 votes

---
Tags: c++
---


title: Arduino DUE and optocoupler 4N25

text:
# Question
Title: Arduino DUE and optocoupler 4N25
I'm using an Arduino Due board with an optocoupler 4N25 to simulate a button pressed. I have to open and close a circuit that drive an actuator. In that circuit, when connected, with the tester I'm measuring 6V.

I connect the anode to the pin 12 and the cathode in series with a 150-ohm resistor to ground, and Collector and Emitter from optocopupler to the circuit (and a normal Blink example with the pin 12).

When optocoupler is fired on and off respectively with a tester I measure 0V and 1.7V in the arduino part, and 4V and 6V.

This is not enough and the actuator is always run. I'd like to read 0-6V instad of 4V-6V. Does this depends on how much current goes to the anode/cathode of the optocoupler? Do I have to change the resistor in the arduino part? Any kind of advice? What can I do?

I don't want to use relay because I have read that in respect to a relay they are faster, smaller, longer-lived and quieter.

# Answer
> 2 votes
It sounds like the 4N25 opto-coupler on its own can't do what you need because it's not designed to directly make/break a connection between a power source and its load (i.e. it isn't functionally equivalent to a relay).

Internally, the switching functionality is provided by an NPN photo-transistor. A typical open collector usage would be something like this:

<sub>*(Image copyright Lewis Loflin: http://www.bristolwatch.com/ele/opto\_isolated.htm)*</sub>

The switch (`S1`) and the power source (`Vi`) on the left would be your Arduino. All the connections on the right would be part of your device (the actuator).

As you can see, you need 3 connections on the right: voltage source (`Vcc`), ground, and the output (`Vo`, which goes to your device). The circuit basically works by pulling the output (`Vo`) either up to `Vcc` to turn it on, or down to ground to turn it off.

It looks like all you have is `Vcc` and `Vo`, so this kind of configuration won't work. (Don't try to use the ground from your Arduino instead. That could cause various other problems.)

It should be possible to setup additional circuitry to act more like a Solid State Relay, but without a ground reference point it can be harder than it sounds. A mechanical relay might be the easiest option.

---
Tags: arduino-due, voltage-level, relay
---


# Question
Title: What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?
I have seen commercial Xbee / Zigbee clones using HC-05 integrated inside. Are they any different than regular HC-05 bluetooth modules?

* What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?

# Answer
Bluetooth and Zigbee are two different communication protocols. The Xbee clones you are talking about a called BTbee.

As far as im aware the BTbee modules are the same hardware/firmware wise as the hc05/hc06 modules. The only difference being the BTbee modules are in the Xbee footprint, allowing you to plug them into Xbee/Zigbee sockets.
> 3 votes

---
Tags: bluetooth, xbee
---


# Question
Title: What are the fundemental differences of different Bluetooth modules for beginners?
I'm a beginner to microcontrollers and electronics, albeit not really to computers and programming.

Starting out with the Arduino, I came to a point whereby I'm really interested in getting my prototype to talk to a mobile device or a computer to send and receive data (for example, send sensor data or receive commands).

Looking out, I've found out that there are different bluetooth modules with varying pricing points. Further research into differences did not reveal much to me as being a beginner, I am struggling to understand what to look out for or how to choose.

**My question here is:**

What are the fundemental differences of different Bluetooth modules for beginners, such as:

* HC-05
* HC-06
* HC-07

And what should one look for when buying a simple Bluetooth module for Arduino?

# Answer
> 9 votes
As far as simplicity is concerned, HC05 would be the way to go. It is by far the most popular and there are a tonne of tutorials on using it (just a quick google search). As for the differences:

* The HC-05 module can build a connection to other modules. E.g. a Robot being a master and connecting to slave bluetooth module. Or in slave mode to make a wireless bridge to a notebook.
* The HC-06 module only can be a slave. This makes it only useful for say connecting a notebook as a master to a robot with a slave module e.g. for a wireless serial bridge.
* As for the HC07, support seems low so I would recommend sticking with HC05 or HC06

At the end of the day it comes down to your requirements. If you are only wanting to talk between the phone and your arduino than the HC06 would work fine, however if at some point in time you want to talk to another arduino, than hc05 would be the way to go.

# Answer
> 2 votes
I don't really know the differences but I've used the HC-06 modules. They are slave-mode only but that is what you need to replace a hard-wired terminal to your Arduino, such as your PC and and a USB cable, with a Bluetooth terminal. That probably covers 99% of cases where an Arduino or other MCU-based device needs to communicate to a PC or tablet that already has Bluetooth built in. For device to device communication, one of them would have to be a master, and I think that requires an HC-05.

---
Tags: arduino-uno, arduino-mega, bluetooth, communication
---


# Question
Title: Why is this spitting giberish instead of serial numbers?
```
#include <TrueRandom.h>

void setup() {
  char* ss= (char*)TrueRandom.random(111111111,999999999);
  char* finalss;
  Serial.begin(9600);
  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

```

This is supposed to output a randomly generated number in this format nnn-nn-nnnn. Updated Code (Doesn't seem to output anything):

```
#include <TrueRandom.h>

void setup() {
  String ss;
  ss = (String)TrueRandom.random(111111111,999999999);
  String finalss;
  Serial.begin(9600);
  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

```

# Answer
> 4 votes
Casting a number to a `char*` doesn't convert the number to a string. Instead it converts the number to a pointer and starts reading `char`s from that location.

Either pass the number to a `String` constructor, or pass it through `ltoa()`.

**EDIT:**

```
String ss(...);

```

or

```
char ss[11];
ltoa(..., ss, 10);

```

Also, don't forget to allocate memory for `finalss` and NUL-terminate it.

```
char finalss[12];
 ...
finalss[11] = 0;

```

# Answer
> 1 votes
I am really assuming you are doing this on a arduino, do you have the serial terminal switched on, you are putting that entire code in setup, means it executes only once and that maybe before you can get your serial terminal on.

So if you are putting it on setup, you need to push the reset button to get a number.

check the code at - https://code.google.com/p/tinkerit/wiki/TrueRandom and see if that works

A better way to write your code may be -

```
#include <TrueRandom.h>

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

  Serial.print(TrueRandom.random(111,999));
  Serial.print('-');
  Serial.print(TrueRandom.random(11,99));
  Serial.print('-');
  Serial.println(TrueRandom.random(1111,9999));

}

void loop() {
  ; // Do nothing
}

```

# Answer
> 1 votes
```
void setup() {
  long longrand = TrueRandom.random(111111111,999999999);
  char ss[9+1], finalss[13+1];

  Serial.begin(9600);
  (void)ltoa(longrand, ss, 10);

  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  finalss[10] = '\0';

  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

```
* `TrueRandom.random()` returns a long, not a string, so you need to assign the value to a long variable while you translate it.
* Your code didn't allocate any memory for the arrays you tried to use, so the third statement does that. I made them larger than the number of characters you used because the range you gave to `TrueRandom.random()` is a set of 9-digit numbers. I don't know how you need to punctuate your numbers so I allocated `finalss[]` larger yet. You should confirm that the array sizes will be sufficient for your needs.
* The fifth statement, ltoa() converts a long to an ascii string in the `ss[]` array.
* I left your `finalss[x] = ss[x];' statements alone except to add the necessary NUL terminator at the end of`finalss\[\]\`.

I haven't tested this but it compiled with no errors other than my not having `TrueRandom.h`. But it should get you a lot closer to (what it looks to me as if) you intended.

---
Tags: debugging
---


# Question
Title: Did I accidentally short something? My Arduino UNO board does not communicate with the computer anymore
I had my sketch uplaoded and everything was working fine when I tried connecting one of the input pins(pre-configured as digital INPUT) to 12V, just to see if this was being read as a HIGH as well. It seems to have done something and the board stopped working. Moreover, all pins seem to be stuck at HIGH!

So far Ive tried the following:

* reset button: doesnt help
* re-upload: doesn't work - it says not in sync

Physically nothing seems to be burnt/blown. What am I missing? Have I fried my board? I hope not. PS: It was connected to a 12V external power source

Any thoughts?

# Answer
> 1 votes
Unfortunately, the arduino's input pins are not tolerant of 12 volts, You have likely caused permanent damage to the chip =(. There is a regulator that makes it capable of being *powered* by 12 volts, but the input pins are different.

If you look at table 30-1 on the datasheet for the Uno's controller here you can see the input characteristics. The arduino is powered at 5v, so the max digital input voltage is 5.5v

---
Tags: arduino-uno
---


title: Arduino Piccolo Example Script Error

text:
# Question
Title: Arduino Piccolo Example Script Error
So I am trying to make an audio visualizer from this tutorial listed here.

So I downloaded all the files needed, and downloaded the code. But when I try to verify it, I get this Error:

```
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp: In constructor 'RobotControl::RobotControl()':
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'LCD_CS' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'DC_LCD' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'RST_LCD' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp: In member function 'void RobotControl::begin()':
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXA' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXB' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXC' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXD' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:19: error: 'MUX_IN' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:22: error: 'BUZZ' was not declared in this scope
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:25: error: 'Serial1' was not declared in this scope
core.a(main.cpp.o): In function `main':
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\hardware\arduino\cores\arduino/main.cpp:11: undefined reference to `setup'
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\hardware\arduino\cores\arduino/main.cpp:14: undefined reference to `loop'

```

I've looked this up before, and couldn't find anything on it. So I came here for a last resort.

## Any ideas?

EDIT: So I reinstalled the folders, and renamed the LED folder but now I get a new error:

Piccolo:112: error: 'Adafruit\_BicolorMatrix' does not name a type Piccolo.pde: In function 'void setup()': Piccolo:130: error: 'matrix' was not declared in this scope Piccolo.pde: In function 'void loop()': Piccolo:168: error: 'matrix' was not declared in this scope Piccolo:168: error: 'LED\_RED' was not declared in this scope Piccolo:169: error: 'LED\_YELLOW' was not declared in this scope Piccolo:170: error: 'LED\_GREEN' was not declared in this scope Piccolo:207: error: 'LED\_OFF' was not declared in this scope Piccolo:210: error: 'LED\_OFF' was not declared in this scope

EDIT 2: Deleted Robot\_Control and got this error:

In file included from Piccolo.pde:34: C:\Users\ted\Desktop\Arduino\_Sandbox\_Windows\_01\Arduino\libraries\Adafruit\_LEDBackpack/Adafruit\_LEDBackpack.h:94: error: expected class-name before '{' token C:\Users\ted\Desktop\Arduino\_Sandbox\_Windows\_01\Arduino\libraries\Adafruit\_LEDBackpack/Adafruit\_LEDBackpack.h:103: error: expected class-name before '{' token C:\Users\ted\Desktop\Arduino\_Sandbox\_Windows\_01\Arduino\libraries\Adafruit\_LEDBackpack/Adafruit\_LEDBackpack.h:112: error: expected class-name before '{' token Piccolo.pde: In function 'void loop()': Piccolo:168: error: 'class Adafruit\_BicolorMatrix' has no member named 'fillRect' Piccolo:169: error: 'class Adafruit\_BicolorMatrix' has no member named 'fillRect' Piccolo:170: error: 'class Adafruit\_BicolorMatrix' has no member named 'fillRect' Piccolo:207: error: 'class Adafruit\_BicolorMatrix' has no member named 'drawLine' Piccolo:210: error: 'class Adafruit\_BicolorMatrix' has no member named 'drawLine'

# Answer
As I mentioned in the comments, reinstalling/updating all your 3rd party libraries to the latest versions is probably the first thing to try. Updating the IDE itself may also help.

If that hasn't worked then a forum topic here seems to describe the same kind of issue: http://forum.arduino.cc/index.php?topic=168854.0

One of the users seems to have tracked the problem down to a couple of Adafruit libraries. He suggests the following:

> 1) Delete the folder "Robot\_Control" from Program Files\Arduino\libraries\
>
> 2) Make sure, that the two Adafruit folders in the same folder are named Adafruit\_GFX and Adafruit\_ST7735. I had them named "AdafruitGFX" and "AdafruitST7735", but that was wrong.

Deleting the `Robot_Control` folder doesn't sound like an ideal solution to me, but perhaps there's an incompatibility which can't be easily fixed. Unfortunately, the Arduino IDE handles libraries in a slightly strange way, so weird problems can happen from time to time.
> 0 votes

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


# Question
Title: Arduino Uno to drive 2 unipolar stepper motors
I need to use two stepper motors to move microscope positioning knobs in the X/Y direction. The stepper motors I have are unipolar and are 6V rated (I think).

I know it's possible to drive a unipolar stepper motor via a ULN2003 using an Arduino Uno. I know I can wire it using the 2-wire or 4-wire method.

But my questions are:

Is it possible to drive 2 of them? What are the modifications I will need to make to the circuit? Will this harm my Arduino? Do I need a stepper motor shield?

# Answer
No problem. Just use two ULN2003 chips, one for each stepper.

No need for a motor/stepper shield on these unipolar steppers.

It will not harm the arduino (if wired correctly).
> 1 votes

# Answer
I'd suggest to have a look at the EasyDriver stepper motor drivers developed by Brian Schmalz. They are easy to set up and do support **microstepping**, which might be interesting for a more fine control of the microscope.
> 0 votes

---
Tags: arduino-uno, motor, shields
---


title: Using a web server with Arduino

text:
# Question
Title: Using a web server with Arduino
So I am not new to arduino, however, I am new with web servers. I am working on a project that can control a robotic arm that is at one location and I can be at my house. I know basic HTML, Basic CSS, Basic JavaScript, and a tiny bit of JQuery. Only reason I say basic is because I self taught all these languages to myself using codeacademy. So I have a few questions since I done research on the matter.

Can a project like this be done with just the languages I know? All the tutorials I have looked at say you have to know AJAX and JSON. I have no idea what these are.

Also, for the interface, I need to be able to take the value of the encoders on the robot and view them. I also need a button that will record the value at that point in time of the encoders so I can configure the points and maybe even name them. A box where I can see the points and their coordinates, and finally a box where i can place points in and then execute a sequence.

How tough should this be?

# Answer
You can use an Arduino Yun: it has a 32u4 microcontroller coupled with a cpu running linux. The linux side already has a webserver: together with the Bridge library, you can use REST-like APIs to control a sketch, or build a web app that uses that APIs.

One example of remotely control an Arduino (although using an Android app instead of html+js) is this. Here is its source code.
> 3 votes

# Answer
There is an example of using the ethernet shield as a simple web server on the arduino website: http://arduino.cc/en/Tutorial/WebServer

Adafruit has another tutorial using an SDCard to hold the web application's files: http://www.ladyada.net/learn/arduino/ethfiles.html

It would be possible to use the aforementioned techniques to host a simple web application. Since the browser only understands HTML, CSS and JavaScript (browser plugins not withstanding), the application will have to be written using these languages. The HTML file will describe the structure of the UI (text, buttons, etc.), the CSS will apply styles if necessary and the JavaScript will add the interaction code (e.g. what happens when you press a button). The JavaScript could request data from the arduino+ethernet shield using AJAX request and should be able to send data back the same way. Using jQuery, this should be pretty straightforward.

That said, it might be easier to use a full fledged network stack such as the one you can find on Linux (using a raspberry pi for example) and to communicate using the serial port with Linux. I have an example on GitHub (the documentation is lacking but I could update it if need be): https://github.com/ddm/arduino-express

But in that case you don't get to use the ethernet shield which you may have already bought...
> 1 votes

---
Tags: arduino-uno, ethernet, web-server
---


# Question
Title: How can I tell which pins I will have left available by looking at a shield?
I'm very new to Arduino and came to a point where I'm interested in playing with shields, such as LCDs.

For example, I really like the looks of "LCD 1602 with keypad" module, but it seems to be using a lot of pins.

* By looking at a module / shield, how can I tell (or at least estimate) which pins will be used and which ones I will have left if I stack them with my Uno or Mega without printed schematics?

# Answer
If you look in the 'Tutorials' section of this page you can see the pins used. All of the buttons come through in one analogue input and you'll need a further 7 digital I/O pins. So 8 in total which would leave 5 analogue and 4 digital (I think) pins on an Uno.

As for how to tell which ones, does it matter in advance? I would just map the I/O in the sketch to suit. If you need to plan that far in advance though, it seems that J5 in this schematic shows which pins travel through the shield (i.e. are available to use in conjunction with the shield). Also J6 shows the 5 remaining analogue pins.
> 1 votes

# Answer
why dont you use an i2c adapter for this type of display? search for i2c display module. i2c only needs 2 wires for data and clock and 2 for power. you can also easily locate the SDA and SCL pins on your arduino
> 1 votes

---
Tags: arduino-uno, arduino-mega, pins, shields
---


title: "void does not name a type"

text:
# Question
Title: "void does not name a type"
Hi I'm new at this and can't figure out why I get this error "void does not name a type" on lines 3,5,8,26

```
// _2-5 set Debounce Button
const int BUTTON=2;
const int LED=9;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

Void setup()
{
  pinMode (LED, OUTPUT);
  pinMode (BUTTON, INPUT);
}

boolean debounce(boolean last)

{
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(5);
    current = digitalRead(BUTTON);
  }
  return current;
}

Void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;
  }

  lastButton = currentButton;
  digitalWrite(LED, ledOn);

}

```

# Answer
I thing the problem is not "void does not name a type", but "Void does not name a type". Subtle difference:

```
Void setup()

```

should read:

```
void setup()

```

The same on

```
Void loop()

```

should be

```
void loop()

```

Watch those caps - C is case sensitive.
> 7 votes

---
Tags: programming
---


# Question
Title: Is the supply voltage made available anywhere on the Arduino Uno Board?
I need to power an OpAmp based circuit that will be connected to my Arduino Uno input. Since I have a 12V adapter for the Arduino board, I want to draw power from it for this opamp(LM358).

Does anybody know if there is any way I can do this from the Arduino board(pins?)is as opposed to having to solder wires directly to the bottom of the DC jack?

# Answer
> 2 votes
The `Vin` pin is available (next to `Gnd`) pins.

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


# Question
Title: What should the frequency reading of the SPI clock be with this code?
My Extech EX330 multimeter is reading 3.439Mhz on the pin 13 on my Arduino Uno running the following code. Is the reading correct? If the divider is 2, shouldn't I get 8 Mhz (16Mhz / 2)?

```
    #include <SPI.h>
void setup()
{
  pinMode(13, OUTPUT);

  digitalWrite(13, HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);

}
void loop()
{

  byte pot = B0;
  SPI.transfer(pot);                        //  Do SPI transfer of variable pot
}

```

# Answer
> 4 votes
Yes, the clock speed should be (and most probably is) 8 MHz. However, you're not generating an 8 MHz clock.

What you are in fact generating is 8 clock pulses of 8 MHz, then you have a delay while it deals with the rest of your code, and then it generates another 8 clock cycles of 8MHz.

The overall frequency is evidently sensed as 3.439 MHz.

To generate a pure 8 MHz clock you would have to use a different transfer method. I don't know if the 328P has DMA available, but if it does, that would give you much faster transfers. Also, you could write a more non-blocking version of SPI.transfer().

The normal SPI.transfer() first starts the transfer, then waits for the transfer to finish, and returns the results of the transfer. If you're only interested in transmitting, and not receiving, or the transmitted and received data don't need to c correlate completely, you can instead change the order of how it works:

1. Wait for there to be no transfer in operation
2. Store the result of the last transfer
3. Start the new transfer
4. Return the results of the last transfer.

That way it runs much smoother as it's doing the current transfer at the same time as running your other code.

# Answer
> 1 votes
No, because neither the allocation and assignment of `pot` nor the call to `SPI.transfer()` come for free. And the time taken by both slows the average frequency down to about the measured value.

---
Tags: spi
---


# Question
Title: Can I set the Arduino board type in code
When I've come back to Arduino programming after a spell doing other things, I keep forgetting that I last experimented with a different type of board and get a "avrdude: stk500\_getsync(): not in sync: resp=0x00" error.

I have one sketch which will always be compiled and uploaded against a specific piece of hardware. Therefore, I would like to specify the board type and preferably COM port as well, in my sketch.

Can it be done?

# Answer
> 3 votes
No, it cannot. Neither the compiler invocation nor the subsequent upload examine the code for the hardware in use, so there is no way of doing what you are asking.

What you can do is to create entries in a new `boards.txt` and `programmers.txt` using an existing core that specify all the parameters, and all you would have to do is select them in the IDE for everything to be set at once. See Google Code/Arduino/Platforms for more information.

# Answer
> 0 votes
Yes you could do this, but you won't get much support from the Arduino libraries. From what I have used, the board type is evaluated at library compile time.

But if you are willing to delve through the datasheets for all the boards you want to support, then writing a board-agnostic driver should not be impossible.

---
Tags: uploading
---


# Question
Title: Yun as a Conventional Wireless Access Point
I want my YUN to act as a server in a client/server architecture so students can control their wifi robots via their desktops. I can plug the YUN directly into an ethernet port on our network and want to have robots communicate with it through a client/server architecture. Can somebody steer me in the right direction?

# Answer
> 1 votes
Check out this project, made by @Vadorequest the early days of the Yun: he hacked a car to control it via his smartphone. There's a nice video on youtube.

---
Tags: wifi, arduino-yun
---


title: 4 bit to Decimal Converter IC

text:
# Question
Title: 4 bit to Decimal Converter IC
im using arduino and im out of pins.

I need something like a decoder but the problem is that the decoders only change one output pin I.E. for 0011 the output will be 0001000000000000 what i need is to have the first outputs on I.E for 1000 the output will be 111111111000000000 i basically need to light up to 16leds and im out of pins so i was wondering is there is any IC that does this for me if i have 1111 it will output 16 ones.

# Answer
> 6 votes
You can use one (or more, daisy-chained) **shift register** for that.

It will normally take you 3 pins and provide 8 outputs, or 8n where n is the number of chained shift registers still using only 3 Arduino pins.

One example of a shift register that fits your situation is the **74HC595**.

On Arduino, you can use `shiftOut` function to help handle those ICs.

# Answer
> 2 votes
You could use the MCP23017 an i2c 16 input/output port expander. (datasheet)

It allows you to control 16 I/O pins via a simple I2C interface (only 2 pins needed). And an Arduino library exists for it.

---
Tags: arduino-mega, led, pins
---


title: analog serial read values are not equal

text:
# Question
Title: analog serial read values are not equal
I have not used the Arduino in over 2 years and have forgotten a bunch of stuff I was wondering if someone could help me out. I have two analog sensors both the same connected to the appropriate analog pins. I am getting a read on the serial monitor and when i test the sensors the values are changing so i know the circuit is correct and everything is in the right place. I just have an issue with my code.

```
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);

  // print out the value you read:
  Serial.println(sensorValue1);
   //Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" ");

  delay(1000);        // delay in between reads for stability

   // read the input on analog pin 1:
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.println(sensorValue2);
  //Serial.print("val2 = " );
  Serial.print(sensorValue2);
  Serial.print(" ");
  delay(1000);        // delay in between reads for stability

 }

```

once i view this in the serial monitor it is not organized and the sensorvalue1 is skipping over to the next line. I would appreciate the help.

There are two sensors so there should be two values but in the picture the values are all messed up i would ideally like it to give me a two seperate values one for each sensor

val1= sensorvalue1 val2= sensorvalue2

# Answer
> 2 votes
Try something like this

```
void loop() {
  // read the input on analog pin 0 and 1 with delays for stability:
  delay(1000);
  int sensorValue1 = analogRead(A0);
  delay(1000);
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" val2 = " );
  Serial.println(sensorValue2);

 }

```

# Answer
> 0 votes
The problem here seems like you are writing the value with a println(), and then again the value without new line but space. Then you write value2 with an ending newline and again value2 without newline. In your output there is also a string that does not match up anywhere in the code you posted. Double check what you are uploading and check if it has error.

---
Tags: serial, analogread
---


# Question
Title: 4 channel relay module reversed? Or is it my code?
So I am designing a simple project where my Arduino reads analog values from a potentiometer, or rotation sensor, as it is called on EBay, and uses that value to determine how many relays to close. I am connecting 4 digital pins to the relay module, and powering it with a constant digital signal from pin 2.

Here is my code:

```
//set up the pins for activating each relay on the module
#define in1 13
#define in2 11
#define in3 10
#define in4 9
#define power 2      //set up the power pin for the module

void setup(){
 Serial.begin(9600);
 pinMode(in1, OUTPUT);
 pinMode(in2, OUTPUT);
 pinMode(in3, OUTPUT);
 pinMode(in4, OUTPUT);
 pinMode(power, OUTPUT);
 digitalWrite(power, HIGH);        //for power to the relay module
}

void loop(){
 float rotationValue = analogRead(A0);          //read raw value from potentiometer
 float percentValue = rotationValue / 10.23;       //convert the value to 0%-100%
 Serial.println(percentValue);                  //print it out on screen
 if(percentValue >= 0.00 && percentValue <= 1.00){         //all relays off
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 1.00 && percentValue <= 25.00){        //relay #1 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){           //relay #1, #2 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){     //relay #1, #2, #3 on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
 }
 else if(percentValue > 75.00){             //all relays on
  digitalWrite(in1, HIGH);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, HIGH);
 }
}

```

Ok, here's the problematic part. After I upload the program onto the board, when I set the potentiometer to the 0 position, all relays are on. And when I twist it to the 100 position, which is maximum, all relays are off. Although it is usable, what's weird is that when I start from 100 and twist it back toward 0, the relays will activate, but in the opposite order. So relay #4 will activate, then #3, then #2, and then #1, and all four are on when I reach 0. Is it something wrong with my code? I've checked and rechecked, and even checked with a different project where I connect the pins to LED's. And they work normally. But when I connect up the relay module, it's reversed. Any ideas?

Here is the relay module: http://www.miniinthebox.com/4-channel-relay-module-with-optocoupler-5v\_p903429.html?currency=USD&litb\_from=paid\_adwords\_shopping&gclid=Cj0KEQiAts-kBRCbgrXc1rnXw7MBEiQAnFqTdph\_qI5n7rrpW7gZaxafVVkeWitQlN8FUSUJzdsV2JwaAlBA8P8HAQ

And here is the potentiometer: http://www.ebay.com/itm/Potentiometer-Sensor-module-Rotation-Angle-Sensor-Arduino-competible-/251656942542

I mean, right now I'm even thinking that the relay module may be labeled incorrectly, that the numbers are printed the wrong way. But it could be my fault, most likely.

Thanks for any help.

# Answer
All the relay boards I've come across are 'active low' i.e. as you've discovered bringing the control pin down to earth activates the relay. As an aside just be careful that the arduino has enough juice to power the relays, a separate supply is normally required if these are coil rather than ssr type relays
> 3 votes

---
Tags: arduino-uno, analogread, relay, potentiometer, digital
---


title: Using PROGMEM to save RAM

text:
# Question
Title: Using PROGMEM to save RAM
I am successful putting and retrieving a char array into Arduino flash memory using PROGMEM char arrays.

I am building my application using header files with a class definition / implementation and would like to keep the strings in the same header file.

If I define another PROGMEM char array neither one can be executed. In other words, these PROGMEM are global arrays as far as the Arduino compiler is concerned. They compile, but they won't show up.

Here is my test code:

```
  lcd.clear();
  lcd.print(*strFlashDebug[0]);  // in CDebug
  lcd.setCursor(0,1);
  lcd.print(*strFlashTrack[0]);  // in CTrack

```

If I put both definitions in the same header file, it only works with only one *lcd.print* enabled, not commented out.

It appears that multiple PROGMEM arrays can be defined and compiled, but only one is actually usable. What is the explanation?

# Answer
The important thing to know for PROGMEM is that the AVR chip you’re using does not have a single flat address space. I.e., it does not use a von Neumann architecture; instead, it uses a specific version of what is known as a Harvard architecture: it has separate address spaces for RAM, program memory, and EEPROM. All of them start at 0. Which means that while dereferencing a null pointer is technically still undefined behavior in C++, it can be (and often is) perfectly valid in Arduino code.

The short version is: If you have a PROGMEM pointer, whatever function you pass it to must work on PROGMEM pointers. `lcd.print` does not, and as far as I can tell there isn't any way the function could possibly detect this is not a RAM pointer. You have to call a different function, assuming there is one in the first place.

See *PROGMEM* (Arduino reference) for examples on how to use PROGMEM data.
> 2 votes

# Answer
A PROGMEM variable definition (i.e., declaration) allocates memory in FLASH. You need use an *extern* clause in the header file and a physical declaration in the C code which is linked in your code. It's pays also for potential static class properties.

Also check if *lcd.print()* accepts a PROGMEM array, i.e., if the overloaded procedure is defined and called.

Just note I recommend using much more effective string formatting via file streams (FILE) and *fprintf\_P()*.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: PWM signaling with Arduinos: What is the reason for the ground connection?
*This may sound like a very dumb question and I apologise in advance.*

I've gone through reading about PWM and working on some example sketches to control PC fan speeds using PWM and Arduino.

In all documents I read, it is mentioned that "PWM is a signal".

**My questions:**

1. Is PWM **really** a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?
2. If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

# Answer
> 8 votes
> Is PWM **really** a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?

At the most basic, it is a signal because we call it such. Even a constant voltage can be a signal, signalling that e.g. a window has not been broken. A PWM signal indicates that we want to apply a certain fraction of full power to a load.

> If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

Because it is a voltage-based signal, and ground serves as the reference for this voltage. Voltage only exists *between* two points.

> This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

Radio signals are photon-based; the oscillation of photons at a given frequency being broadcast from a location are what define the signal. Since frequencies are absolute, they can be discriminated without a (relative) reference.

---
Tags: arduino-uno, arduino-mega, pwm, current, signal-processing
---


title: Using displays with Arduino Uno

text:
# Question
Title: Using displays with Arduino Uno
Does anybody know if there is any documentation available online on basic information about using displays with Arduino Uno? I've never used displays before and would very much appreciate some basic information on the different types etc..

Any information that can help me choose what display I want to buy for my next project will be helpful.

for ex: Right now I don't even know what a shield is in context to a display and whether or not I should look for one in my purchasing my display.

# Answer
> 1 votes
The Arduino website has a list of LCD displays and link with more information about each one. For controlling the display you may want to look at Arduino's LiquidCrystal Library.

If you are looking for a step by step guide for using a lcd display with the Arduino, there is a nice guide on Adafruit.

---
Tags: arduino-uno, display
---


title: Powering 5V Accesories

text:
# Question
Title: Powering 5V Accesories
I'm using an Uno to control NeoPixels LED strips (60 per metre). These are powered with a 5V DC supply. Now, when using USB to power the Arduino it works lovely. However I want to move the Arduino into a standalone "installation" where I'll only want one power supply.

I've already got a 5V DC supply which outputs about 5.2V. What is the best way to power both the Arduino and the LEDs? I understand the need for at least 7V at the Arduino's voltage regulator input. Would my best bet be to get a 12V supply (or similar) and use a buck converter to power the LEDs? The total current draw *could* reach 3.6A but will be 400mA for the majority of the time.

# Answer
> 3 votes
If your supply is regulated (put a 47ohm resistor across it and measure the AC voltage with a DMM; it should be almost nothing if properly regulated) then you can use it for both the Uno and the NeoPixels. The ATmega328P has a maximum input voltage of 5.5V, and the WS2812B has a maximum voltage of 5.3V, putting the supply within the proper range to run them.

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


title: Interrupts don't work

text:
# Question
Title: Interrupts don't work
I tried to run a sketch that tests my AVR's interrupts, I have an UNoriginal Arduino Uno, and I've checked pins 2 and 3 like the following:

```
- at void setup()
attachInterrupt(2, inter, CHANGE);
- at void inter()
Serial.println("Interrupt pin 2");

```

I did the same on pin 3, I checked them by attaching the pins to a button with a Pull-Up, When I click the button it goes from HIGH to LOW. But yet, the arduino doesn't run the 'inter'. Is it possible that because my Arduino is not original it won't work? And this type of interrupts are software not hardware right?

# Answer
On all Arduino boards except the DUE, `attachInterrupt()` does not use the pin number as first argument but the interrupt number, which is different:

```
void attachInterrupt(uint8_t interrupt, void (*ISR)(void), int mode);

```

As documented on Arduino reference, for an Arduino UNO, the mapping is as follows:

* Interrupt 0 -\> Pin 2
* Interrupt 1 -\> Pin 3

So just change the code in `setup()` to:

```
attachInterrupt(0, inter, CHANGE);

```

And that should work for pin 2.
> 2 votes

---
Tags: c++, sketch, interrupt, avr
---


# Question
Title: Can I drive this relay shield with an Arduino Due?
Sorry I'm new to electronics while I've some experience in coding. This let me very curious about the Arduino Due board: it is super powerful and I can run some C++ code that I can not with the normal Arduino Uno. But I lack in electronic theory, sorry if the question is a little bit dumb.

Can I drive this shield with an Arduino Due? The Due board is at 3.3V while the relays in the shield are at 5V.

What do I need to make them run smoothly?

Actually I'd like to run 5 of those shield with only one Arduino Due board. Do I have some problem with power supply?

# Answer
> 1 votes
You'd have to remove the yellow jumper. Connect 3.3v to the VCC and 5v to the JDVCC. But please double check that JDVCC is connected to one side of all the relays.

This way the opto-couplers are activated by 3.3v signals, which in turn activate the transistor (5v) used to engage the relay.

---
Tags: shields, arduino-due, relay
---


title: ATmega328P and other chip sharing clock

text:
# Question
Title: ATmega328P and other chip sharing clock
I am moving my Arduino project to another platform, operating at 3.3V. (5V from USB not useable due to some 3.3V-only chips in the design) Having read about this it seems that 12MHz is a good speed to use, and my stock USB to UART converter, CH340G does call for a 12MHz crystal.

Now what is the best way to share this 12MHz clock between CH340 and ATmega328P, eliminating an extra crystal? Can I tap off XO pin from CH340 with crystal attached, and carry it to the XTAL1 pin of the ATmega?

---

## EDIT

---

If sharing clock requires some fine tuning, what about building a reference clock out of `74LVC1G04` and `74LVC1G06` chips and clock both chips from this?

# Answer
> 4 votes
Sharing a crystal between multiple devices is a very bad idea. The crystal is only a piece of the oscillator, the rest of it being a small bit of circuitry within the IC itself. Having multiple ICs connected to the same crystal will cause them to fight over who is driving it.

The datasheet for the CH340T/R, which I was able to find in English, says the following:

> When CH340 chip is working normally, the outside must supply 12MHz clock signal to XI pin.

This seems to imply that you can feed an external 12MHz clock into the chip and it will work. So we take the clock from the '328P and pass it to the '340G.

Programming the CKOUT fuse on the '328P will cause the internal clock to be output on CLKO, which we then connect to XI of the '340G. This means that that you will lose PB0/D8, but no longer need a second crystal. This also means that you will be unable to use the prescaler since doing so will affect the clock output.

# Answer
> 1 votes
Often is is possible. The range of the crystals signals' max swing are small. Where the XI pin needs to accept these small AC signal. Hence on the FUSE on the ATmega. Which also enables the XO as a Hard clamp to excite the crystal. The crystal dominates the voltage making it small. Additionally, it is important to have the proper parallel capacitance on both the input and output of the crystal. When the XO(0) is tied to the XI(1) along with the crystal and its parallel capacitor, noting that it is in the range of 10-40pf, the total parallel capacitance will be significantly increased. Where it may be possible to reduce the XO(0)'s parallel capacitor, if XI(1) does not add too much.

Anyone attempting this should really inspect the signal on an Oscilloscope to ensure the nature of the wave form is stable and stress its tolerances. Likely by changing the parallel capacitors to find the min and max's before failure. And varying VCC of both chips across is allowed ranges. As to determine the ranges is not unacceptable.

That said the datasheets refer to a version with a suffix T that have an CKO or Clock output on pin 1. That would be best and change the ATmega's FUSE for TTL input. Where Ignacio's answer is very valid and stable. Just the opposite direction.

---

I would point out that you will have the issue that 12MgHz is not a typically supported F\_CPU speed in the code. I have toy'ed with changing the speed in the past, as to do just what you are attempting here, but with a different clock source. And found it requiring so many changes to the Arduino libraries, which are typically #IF'ed to either 8 or 16 so many places not using a nice formula, it was not worth its cost savings versus cost in maintenance. As a starter you may want to refer to SE: "Arduino at 11.0592MHz".

---
Tags: oscillator-clock
---


title: Serial: active low or active high?

text:
# Question
Title: Serial: active low or active high?
When I use the Mega 2560 additional serial ports, I realize that it is active low, active high. I know that TTL is active high and the serial port is obviously stated in arduino serial port page. I also found out that the receive pin flashed (put an LED) when I typed in to the serial monitor. Is this a mistake or problem?

# Answer
The Serial Class of the Arduino uses Typical usage of the Serial Ports is the USART in Async mode. Which is hard coded to IDLE state of HIGH or 1 or VCC.

http://midas.psi.ch/mscb/hardware/bits.gif (picture wont add - so here is a link to it)

If you need to drive the TTL inverted from its traditional values, the Serial Class can not do this. However, you can use the SoftwareSerial Class and enable the inversion in the constructor

```
SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

```

As for why would someone want to invert the TTL UART. In some cases it is possible to drive RS232 directly. As RS232 converters inverts the TTL to +12V/-12V. 5V = -12V and 0V = +12V. So depending upon the RS232 receiver, it may actually trip its TTL output at 2.5V and not 0V. If so then using the SoftwareSerial Class with inverse logic may drive the RS232 input of another device, without requiring a RS232 transmitter on the Arduino's TXout pin.
> 2 votes

---
Tags: serial
---


title: 74HC595N in series error

text:
# Question
Title: 74HC595N in series error
I want have 2 74HC595N shift registers in series.

I built this schematic

When I send a value to the first register, it is sent to the second one. I have same value on both. I change them (master/slave) but the result is the same.

I connected pin 9 on the first SR first with pin 14 on the second. I am using Johnny Five on Galileo Gen 1 with `shiftRegister.send(25)` to send the data.

What am I doing wrong because several days ago I made it and it worked?

# Answer
> 1 votes
If you had it working and it has changed, I would suggest trying a few changes to track down the issue. The schematic seems OK so assuming that all connections are sound, I would look towards proving the code. Maybe try a simple pure Arduino sketch designed for the 74HC595N and see if the results are the same. If not, the culprit is almost certainly Johnny Five.

Perhaps try this sketch which should work with your schematic (remap the I/O though to your 2,3,4 configuration). If the problem persists, throughly examine your connections because there is very little else which would prevent it from working - especially given that it did work a few days ago. Also, have you got another Leonardo to test with?

Finally, the schematic for the Arduino-only example shows a cap on the latch line - presumably for debouncing - which is missing from your schematic. I don't think you've damaged your registers but I wouldn't rule it out.

---
Tags: arduino-galileo, shift-register, johnny-five
---