title: How to program LCD shield?

text:
# Question
Title: How to program LCD shield?
So I'm using the DFRobot LCD Keypad shield to make a text-based game. Can someone give me an example? Let's just say i want to make the LCD display "text1" and then press up then select, it displays "text2". If I press down then press select, it displays "text3".

# Answer
Attach the shield to arduino then run the following code to check if everything is ok. Wiring is made default.

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){               // read the buttons
    adc_key_in = analogRead(0);       // read the value from the sensor

    // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
    // we add approx 50 to those values and check to see if we are close
    // We make this the 1st option for speed reasons since it will be the most likely result

    if (adc_key_in > 1000) return btnNONE;

    // For V1.1 us this threshold
    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 250)  return btnUP;
    if (adc_key_in < 450)  return btnDOWN;
    if (adc_key_in < 650)  return btnLEFT;
    if (adc_key_in < 850)  return btnSELECT;

   // For V1.0 comment the other threshold and use the one below:
   /*
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;
   */

    return btnNONE;                // when all others fail, return this.
}

void setup(){
   lcd.begin(16, 2);               // start the library
   lcd.setCursor(0,0);             // set the LCD cursor   position
   lcd.print("Push the buttons");  // print a simple message on the LCD
}

void loop(){
   lcd.setCursor(9,1);             // move cursor to second line "1" and 9 spaces over
   lcd.print(millis()/1000);       // display seconds elapsed since power-up

   lcd.setCursor(0,1);             // move to the begining of the second line
   lcd_key = read_LCD_buttons();   // read the buttons

   switch (lcd_key){               // depending on which button was pushed, we perform an action

       case btnRIGHT:{             //  push button "RIGHT" and show the word on the screen
            lcd.print("RIGHT ");
            break;
       }
       case btnLEFT:{
             lcd.print("LEFT   "); //  push button "LEFT" and show the word on the screen
             break;
       }
       case btnUP:{
             lcd.print("UP    ");  //  push button "UP" and show the word on the screen
             break;
       }
       case btnDOWN:{
             lcd.print("DOWN  ");  //  push button "DOWN" and show the word on the screen
             break;
       }
       case btnSELECT:{
             lcd.print("SELECT");  //  push button "SELECT" and show the word on the screen
             break;
       }
       case btnNONE:{
             lcd.print("NONE  ");  //  No action  will show "None" on the screen
             break;
       }
   }
}

```
> 0 votes

---
Tags: lcd
---


# Question
Title: Arduino serial communication synchronisation
i am trying to send data via Labview to my arduino board using serial communication.My problem is that the arduino reads only the first byte of sent data then when i change it ,it doesn't react.
For example when i start the communication i send '0' to arduino.I sees it.but while it is running i send '1' but it doesn't behave accordingly to it.
I noticed also that the board 'sees' sometime the new value after a random period of time.

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

char data = 'F';

void loop()
{
    data = Serial.read();
    delay(50);

    if (data == '0')
    {
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
    if (data == '1')
    {
        digitalWrite(13, HIGH);
        delay(4000);
        digitalWrite(13, LOW);
        delay(4000);
    }

    data = '4';
}

```

# Answer
I suspect you problem stems from the use of delay's in your code. for example,

```
if (data=='1')
 {
  digitalWrite(13,HIGH);
  delay(4000);
  digitalWrite(13,LOW);
  delay(4000);
 }

```

Those delays prevent any computations from happening for 4 seconds each. Your arduino will not read another character after it sees a `'1'` for 8 seconds. If you send too much data in that 8 seconds to fit in the serial buffer, the extra characters are lost.

The behavior you seem to want will require separating the code that reads serial from the code that runs the output, and making sure neither section ever stops execution with delays. Your blinks will need to be timed with something else, like frequent comparisons against the current time with `millis()`
> 1 votes

# Answer
JUST add the part ~ This flushes the serial buffer, which aids in error free data receiving. No need to implement the millis() protocol as you want the led to be active for that time so you do not want any data to enter the system, neither you are using interrupts service.

```
Serial.readString();

```
> -1 votes

---
Tags: arduino-uno
---


# Question
Title: Run Arduino on USB and at the same time BreadBoard on higher voltage?
I am trying to design a bicycle LED lighting system, and for that I bought an Arduino yesterday (so very beginner with Arduino).

My final system will operate at 6V, so I plan to put everything on a breadbord and tune everything (blinking times, resistor values, etc.) and for that I want to keep my Arduino plugged to USB during development.

So my question is:

How should I connect USB-powered Arduino to a higher-voltage-powered breadbord (between 6 and 12V) safely?

# Answer
I think as far as i understood the problem, the system or whatever you call is will run on what ever power as long that power is not fed to the arduino that will not be a problem, just connect the two grounds together and power the arduino through the computer and connect the pins to the system accordingly. i think this will solve thus the trivial problem.
> 2 votes

# Answer
Unless you intend to run both supplies simultaneously, there's no problem. Your ~ 6v input will need to be stepped down and regulated to 5v, and the USB provides a regulated 5v, so the system shouldn't care which one you are using.

If you need to run your system off the 6v during development and need USB communication, I'd suggest using a USB-to-TTL-Serial cable such as this one: https://www.sparkfun.com/products/9718. Connect its Tx & Rx pins to your Arduino's (Uno?) pins 1 and 0, respectively, and it's ground pin to the ground rail served by your battery supply.

Typical regulators will need more headroom above their output voltage to give you a steady, regulated output, and this includes the 5v regulators on Arduino boards which usually specify 7-12v at the Vin (unregulated) input. A 6v battery won't meet this spec so you'd need a buck/boost regulator that could provide a regulated 5v from "0+" to 6v input. Or you might move your system to a bare AtMega328p with a lower clock speed (see the data sheet for max clock speed vs. Vcc), and run it at 3v (for example) which would give a simpler regulator more headroom from its 6v input.
> 0 votes

# Answer
Datasheet can be found here: http://www.atmel.com/devices/atmega328.aspx?tab=parameters

From this, the absolute rated voltage on the ATMega (aka, the chip at the heart of the Arduino) is 6V. Above that... above that you risk magic smoke. But you can just, *maybe* get away with running your whole system on 6V.

Important point - do not rely on using 4 AA batteries for this. Regulate your 6Vish to *exactly* 6V. Just remember that this is at the extreme limit of the spec. If you try this, before you start repeat to yourself "I have just voided my warranty. It is now my fault when it dies."

Alternatively, why are you so wedded to 6V? What are you trying to achieve?
> 0 votes

---
Tags: power, voltage-level, usb, battery
---


# Question
Title: how to make transmitter and receiver for quad copter?
I want to make a transmitter and receiver for quad copter for that I am using two arduinos(UNO and nano).I am using 4 pots for controlling the brushless motors.For that I am sending 4 integer values of the pots and with that integer value PWM signals are generated at receiver by the arduino.Now I want to know how to send that 4 integer values of the pots serially using arduino.

# Answer
> 1 votes
The APC220 radio module provides a simple and economic solution to wireless data communications. Integrates an embedded high speed microprocessor and high performance IC that creates a transparent UART/TTL interface, and elminates any need for packetizing and data encoding. Use this module as this works as a pair and more intriguing part is that "it" can transmit over a km away.

link ~http://www.dfrobot.com/index.php?route=product/product&filter\_name=apc&product\_id=57#.VWeKIVWqqko

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


# Question
Title: Fingerprint sensor with external memory source
I am building a door lock that we will use at a local MakerSpace-club in my city, and we had this idea about building a fingerprint lock with parts compatible with Arduino.

What we are aiming to do is create a database that holds all our customers and their associated information. Fingerprint data being one of them.

So my question is: Is it possible to have a fingerprint sensor **store and compare fingerprint data** with an **external source** such as a **MySQL database**, instead of using the on-board memory?

So basically: When a customer puts his finger on the sensor, the Arduino board grabs the fingerprint data and queries our database for a match through its WiFi shield. If match is found: Log entry and unlock the door.

*Google is not helping me out here.*

# Answer
> 1 votes
Yes, all you need is a computer or another device that grabs the data via wifi and store it in a database.

You can simply send requests from arduino to computer and the PC does the search and returns the info back.

If you use XBees for communication, just install some serial communication with your preferred language and start sending and receiving data. The database will be accessed through that high level program and data will flow via XBees.

---
Tags: arduino-uno
---


title: Reading quadrature encoder

text:
# Question
Title: Reading quadrature encoder
I am using an encoder motor for one of my projects and i was reading encoder values manually through Arduino. It was working fine when i turned it slowly, but whenever i would rotate it at some higher speed, data input to the arduino would stop. I am using the encoder at 4 x.

Can somebody help me with some code to read the data from encoder faster.

```
    int pulses, A_SIG=0, B_SIG=1;

void setup(){
  attachInterrupt(0, A_RISE, RISING);
  attachInterrupt(1, B_RISE, RISING);
  Serial.begin(115200);
}//setup

void loop(){

}

void A_RISE(){
 detachInterrupt(0);
 A_SIG=1;

 if(B_SIG==0)
  pulses++;//moving forward
 if(B_SIG==1)
  pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_FALL, FALLING);
}

void A_FALL(){
  detachInterrupt(0);
 A_SIG=0;

 if(B_SIG==1)
    pulses++;//moving forward
 if(B_SIG==0)
     pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_RISE, RISING);
}

void B_RISE(){
  detachInterrupt(1);
  B_SIG=1;

  if(A_SIG==1)
     pulses++;//moving forward
  if(A_SIG==0)
      pulses--;//moving reverse
  Serial.println(pulses);
  attachInterrupt(1, B_FALL, FALLING);
}

 void B_FALL(){
    detachInterrupt(1);
    B_SIG=0;

    if(A_SIG==0)
       pulses++;//moving forward
    if(A_SIG==1)
       pulses--;//moving reverse
    Serial.println(pulses);
    attachInterrupt(1, B_RISE, RISING);
}

```

# Answer
```
volatile long rawTacho[2];      // interrupt 0 & 1 tachometers

ISR(MotorISR1)
{
    int b = digitalReadFast(8);
    if (digitalReadFast(2))
        b ? rawTacho[0]-- : rawTacho[0]++;
    else
        b ? rawTacho[0]++ : rawTacho[0]--;
}

ISR(MotorISR2)
{
    int b = digitalReadFast(9);
    if (digitalReadFast(3))
        b ? rawTacho[1]-- : rawTacho[1]++;
    else
       b ? rawTacho[1]++ : rawTacho[1]--;
}

void setup()
{
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    pinMode(8, INPUT_PULLUP);
    pinMode(9, INPUT_PULLUP);

   attachInterrupt(PCINT0, MotorISR1, CHANGE);  // pin 2
   attachInterrupt(PCINT1, MotorISR2, CHANGE); // pin 3
}

```

something similar to that - it was extracted from bigger code so you will have read it and understand it as opposed to copy paste.

Update note: This is not complete in a pure form - the cpu doesnt tell you what pin had an interrupt - thus some underlying Arduino code figures that out for me, but it is fairly efficient, and I used it as is. Also if it is not obvious, this is reading encoders from 2 motors. 1 interrupt is assigned to each motor, the second phase of each is on a non-interrupt pin. Never lost a reading to my knowledge.

The problem with your code is probably the print in the interrupt as pointed out in a comment.
> 1 votes

# Answer
I built a measuring bench using a glass slide (intended for DRO) with quadrature output. I found the Arduino was easily overwhelmed and would miss beats. I also tried implementing a D flip flop to halve the resolution of the slide. Ultimately, I put a LS7166 IC in the prototyping area of the freeduino eleven I was using and then performed a PORT read on D0-D7.
> 0 votes

---
Tags: arduino-uno, motor, rotary-encoder
---


# Question
Title: Why can't I read anything but Pin 0 of PORTC?
So I am working on this lab for my Embedded Systems class, but I can't seem to read anything but the first bit of PORTC. What's even weirder is that if any of the pins go low the first bit will go to 0, while all the others stay at 0 no matter what.

Here is my code:

```
 /*
 * Lab_4A.c
 *
 *  Reads the value of one distance sensor
 *  and reports if light/dark to the LCD.
 *
 *  Created on: Sep 24, 2014
 *  Author: Austin R. Bartz
 *
 *  LCD Connections:
 *  E   - PB4 (Digital 12)
 *  RS  - PB5 (Digital 13)
 *  R/W - GND
 *  Data 4,5,6,7 - PD4,5,6,7 (Digital 4,5,6,7)
 *
 *  Sensor Connections:
 *  Sensor 8 - PC0 (Analog A0)
 *  Sensor 7 - PC1 (Analog A1)
 *  Sensor 6 - PC2 (Analog A2)
 *  Sensor 5 - PC3 (Analog A3)
 */

#include <avr/io.h>
#include <inttypes.h>
#include <MSOE/delay.c>
#include <MSOE/bit.c>
#include <MSOE/lcd.c>
#include <user/initPorts.c>
#include <user/readPorts.c>
#include <user/writePorts.c>

void printBinaryLCD(uint8_t);
uint8_t readSensors();

int main(void)
{
    lcd_init();
    lcd_clear();
    while(1)
    {
        uint8_t val = readSensors();
        printBinaryLCD(val);
    }
}

void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = ((PINC & (1<<3)) == (1<<3));
    lcd_print_uint8(A);
    lcd_goto_xy(1,0);
    uint8_t B = ((PINC & (1<<2)) == (1<<2));
    lcd_print_uint8(B);
    lcd_goto_xy(2,0);
    uint8_t C = ((PINC & (1<<1)) == (1<<1));
    lcd_print_uint8(C);
    lcd_goto_xy(3,0);
    uint8_t D = ((PINC & (1<<0)) == (1<<0));
    lcd_print_uint8(D);
}

uint8_t readSensors()
{
    DDRC = 1;
    PORTC = 1;
    delay_us(10);
    DDRC = 0;
    PORTC = 0;
    delay_ms(1);
    return PINC;
}

```

Any help would be much appreciated!

# Answer
`DDRx` is the Data-Direction-Register-x so this can be `DDRC` or `DDRD` or anything. One register has 8 bits, 1 bit for every pin. Making a bit 1 will result in the pin being an output. Making it 0 will result in the pin being an input.

Let's say we want to make pin 4 and 5 of port C an output. We simply do this in the setup:

```
       //76543210  Pin numbers.
       //IIOOIIII  Input/Output indicator
DDRC = 0b00110000;//Code that actually does it.

```

So this way we can read pin 4 & 5. But if we want to read the complete port, I suggest setting every pin of the port to input. `DDRC = 0b00000000;`

Then we can read the port as simply as `uint8_t portValueC = PORTC;`

portValueC will now have a value that represents the port's values. It'll be binary, but you read it as decimal. So it'll be:

```
0 for no inputs.
1 for only pin 0
2 for pin 1
3 for pin 0 & 1
4 for pin 2
5 for pin 2 & 0
6 for pin 2 & 1

```

Well. it's binary.

Let's say (pin 7,5,3,1 high)(pin 6,4,2,0 low).

This will result into the decimal value of 170.

The binary value, however, will be easier to read `0b10101010`

```
    //76543210
  //0b10101010 (Could be the value) (pin 7,5,3,1 high)(pin 6,4,2,0 low)
//^ is decimal: 170

```

You should add these macros to your project to make it easier to get single bits from this value:

```
#define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define bit_flip(p,m) ((p) ^= (m))
#define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
#define BIT(x) (0x01 << (x))

```

This way, now you can do:

```
if(bit_get(PINC, BIT(3)))
{
 //Do only this if PORTC pin 3 is high
}

```

Read this first:

Info on the registers

Info on bit fiddling
> 2 votes

# Answer
Judging from your `readSensors()` function, these seem to be capacitive sensors:

* you charge them to Vcc (`DDRC = 1; PORTC = 1;`)
* you wait until they are fully charged (`delay_us(10);`)
* you tri-state the pin (`DDRC = 0; PORTC = 0`)
* you wait for them to partially self-discharge (`delay_ms(1);`)
* you read the pin (`return PINC;`)

If my assumption is correct, and if *all* of those sensors are similar, then here is your first bug: you are only charging the sensor on PC0. If you want to charge the four sensors, you need to set bits 0 to 3 of the port to active high. Thus, the first two statements in `readSensors()` should be:

```
DDRC = 0x0f;   // bits 0 to 3...
PORTC = 0x0f;  // ...set to active high

```

Your second bug is in `printBinaryLCD()`. The function name, and the way you call it, implies it is meant to print on the LCD the value passed as a parameter. Instead, it is completely ignoring its parameter, and reading `PORTC` itself. This is bad because the reading of the capacitive sensors is time sensitive, so you should let `readSensors()` do the work. You should then change `printBinaryLCD()` so that it examines `val` instead of `PORTC`:

```
void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = (val & (1<<3)) != 0;
    ...etc...

```
> 2 votes

# Answer
i can't be certain, but i reckon it has something to do with

```
DDRC = 1;

```

this equates to b000001, meaning only pinC0 is an output. i think
> 0 votes

---
Tags: pins, lcd, c
---


title: bi-directional nrf24 communication

text:
# Question
Title: bi-directional nrf24 communication
The central arduino The 1st node The 2nd node

I want the central to send to the first node the rgb code like a string on the loop

> "rgb: 255000255"

but when it detects something to PIR to send a string to central. In addition every some seconds the 2nd node to send a string to the central the temperature.

As i mentioned in my previous questions i have some problems when it comes to the bi-directional comunication. I have tried a lot of code. Can someone show me how to achieve what i want to do if not with code, with steps. Please help me!!

# Answer
> 1 votes
**You *cannot* (easily) have all nodes on the network with the same address.**

There are ways of doing it but they aren't easy. They basically involve creating a "broadcast" facility in your network, and that has certain caveats involved with it.

The nRF24L01 modules have an "auto-ACK" mode to give reliable communications. *This only works with 1:1 addressing* and cannot work with broadcast. If you want to (as most people do) use the auto-ACK facility then you have to have each node with its own unique address. After all, if you're sending the *ACK* to a station, and there are multiple stations with that address, *which one will ACK?*

So you have to think about if what you are trying to achieve is really the right way of going about it. It sounds like you want to just program another node with the same code as an existing node without making any changes to that code and "just have it work". That's a very advanced topic and one that even I would spend quite some time implementing it. Yes, you can do unreliable communications (i.e., no auto-ACK) then you could have all the remote stations with the same address, but I would certainly keep the master as a unique address. Better would be for each node to start up with a pre-defined address which it then uses to ask the master for a unique address (a-la DHCP) and the master then keeps a list of what is connected on what address. From then on it can use reliable communications to send and receive data to each node as it needs to.

A system I wrote for the chipKIT boards gives each node two addresses - its own unique address which you have to provide manually, and a more global "broadcast" address. They are each on different pipes within the nRF24L01. To communicate with an individual node you send to its unique address. To broadcast to all nodes you send to the broadcast address. If you're sending to the unique address you can then turn on auto-ACK. If you're sending to the broadcast address you don't turn on auto-ACK.

Note that using auto-ACK is a whole topic in itself and requires careful design planning to get it to work properly.

Also you have to think about what happens when you send a broadcast packet out and it's received by other nodes - how do they handle that data? Sending temperature data out globally, it will be received by the RGB receiver, which may try and interpret it, causing problems. You need to come up with a way of identifying just what it is you're sending out and only having the right nodes responding to the right data. That means coming up with a strict packet format. Luckily the nRF24L01 chips communicate in fixed packet sizes (incidentally, all nodes on the network will have to be set to use the same packet size or it just won't work) up to 32 bytes, so implementing a packet structure over that is easy enough. Just sending strings of data is both hard to interpret and incredibly inefficient. You should be sending the data as actual data values in variables as part of the packet structure.

# Answer
> 0 votes
Try the `RF24Network` library from `maniacbug`. If you don't have too many nodes it's easy to use. It comes with examples easy to test and extend. It also uses different channels for sending and receiving so you should have no collisions.

---
Tags: c++, nrf24l01+, timing
---


# Question
Title: Arduino Mega2560 clone responding slowly
I am using an Arduino Mega2560. Using Arduino Mega as ISP to burn sketch, I had loaded the bootloader from Arduino IDE.

I uploaded the blink LED code to the Mega. But the LED is responding slowly. Same with Serial code. Delay of 0.1 second acting as 1 second on my board. In code serial communication baud-rate is 9600 but I am getting proper value when I set the baud-rate to 4800 in serial monitor.

Could anyone point out the problem?

# Answer
Either your fuses are wrong (set to 50% the real speed of your crystal / ceramic resonator), you're using the internal oscillator instead of the expected external one, or you have the wrong board with the wrong F\_CPU value selected in the IDE.

Check all of those carefully.
> 1 votes

---
Tags: arduino-mega, bootloader
---


title: MQTT Arduino add quality of service

text:
# Question
Title: MQTT Arduino add quality of service
I'm making a project with MQTT Arduino, but on publish messages i read that it's not possible to publish with qos 1 and 2? It is true? If is not, how can i put qos on publish messages?

# Answer
> 1 votes
What MQTT client are you using?

Paraphrased from the MQTT spec http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#\_Toc398718099

> The MQTT protocol provides three qualities of service for delivering messages between clients and servers: "at most once", QOS0; "at least once" QOS1; and "exactly once" QOS2. For QOS 1&2: The message must be stored locally at the publisher, until the publisher receives confirmation that the message has been delivered to the receiver. However, for QOS0 there is no storage requirement.

The problem with the Arduino is that there is no large quantity of storage available. If the client is disconnected from the broker while using a QOS of 1 or 2 the client must store the messages until a connection is reestablished and the message transfers are acknowledged. On an Arduino there is no guarantee all the messages can be saved. Consider a sensor node collecting 16-bits (int value) every second. Then supposed the broker goes down over the weekend and a repair person isn’t paid to work on the weekend. That’s two days’ worth of data or 172800 readings or about 1/3 MB (without overhead). The Arduino does not have that much storage.

---
Tags: arduino-uno, communication
---


# Question
Title: Beginner Arduino Project: Drumming Robot
So, I've got a music degree, 5 years programming with Ruby and 7 with Pure Data. I've also got hold of an Arduino and a Raspberry Pi.

Anyway, I've seen a number of Arduino projects which involve firing events which cause a stick to hit a drum, but I really don't know where to start.

I have a wicker penguin that I want to have play the drums:

* What components do I need to produce this kind of one-off percussive event?
* Can I trigger these events from Ruby?

# Answer
The approach I would take for the arms is to use a **servo motor** as these are fairly cheap and are **closed loop** so you don't have to add any extra sensors to check where the current position is.

### Types of Motors:

* **Stepper motors** are a type of motor with a special arrangement of coils that allows you to turn a fraction of a degree by sending pulses to the motor. For example, you can buy a 200 step stepper motor that turns in increments of 1.8 degrees. These are somewhat expensive and require somewhat expensive drivers (usually $5-10 per driver). Often used in CNC machines and 3D printers. Continuous rotation.
* **General DC motors** (two types: brushless and brushed, but I won't get into that in here) are a type of motor. Their drivers are often cheaper than one for a stepper motor, but you have little control over their rotation (instead of "take one step which is X degrees," you say , "turn at 25% power clockwise," where you don't know the actual speed). These are sometimes used with *rotary encoders* or *potentiometers* to control the speed and position of the spindle. Continuous rotation.
* **Servo motors** are actually not their own type of motors; they are DC motors (not steppers) with a potentiometer built in along with the driver. You send pulses to it (you can use the *Arduino servo library* for this) to tell it the exact degree to go to. Can only go a limited range: usually either 90 or 180 degree, although you can get special ones that can turn much longer ranges than that.

### Using a Servo Motor:

You can hook it up like this:

> *From this Arduino Tutorial*

And then some very simple code to use the motor:

```
#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(10);
  delay(500);
  myservo.write(0);
  delay(500);
}

```

### Talking with Ruby:

Your best option is to use the serial port on your computer. Figure out how to access a COM/serial port in Ruby. You can then send messages from your computer to the Arduino, but you'll have to figure out a way to structure the messages.
> 2 votes

# Answer
* to move the arms: look for tutorials about arduino controlling a motor (either step od DC).
* to control the arduino from a PC (or the PI) - that's what it means when you say Ruby - check how to remote control over serial port
> 1 votes

---
Tags: robotics
---


# Question
Title: How to measure whether air is flowing through a pipe?
I'm looking for a way to check the air-flow from an aquarium air pump. I need something that can test whether air is flowing or not and I'm not bothered about measuring flow speed. The air will be flowing through a pipe but if required I can have the sensor on the end of an additional pipe just used for measuring.

# Answer
Did you consider a barometric sensor deployed inside the pipe? The pressure should be higher when the pump is active.
> 2 votes

# Answer
Flow sensors tend to be expensive. However, there are many pressure sensors that provide a simple analog voltage input and others with easy to use digital interfaces. As Igor Stoppa points out, these can be used to infer flow. Some can be purchased with tube ports that allow the user to mount the hose directly to the sensor. This would only require a "T" connector and some additional hose to connect to the air pump.

Aquarium air pumps may be pulsatile. So be sure to use an average pressure.

Average Pressure:

* above a certain point may indicate blockage
* between certain values indicates correct flow
* below a certain value indicates no flow

.
> 1 votes

# Answer
Grab yourself something like this

Butcher it to get inside it, and add three small magnets to the fins (should be simple enough - just keep it balanced). Then glue it all back together again.

Add a hall effect sensor to the outside, and Bob's your uncle.

Or, since the principle of that unit is so simple, you could make your own from scratch.
> 1 votes

---
Tags: sensors
---


# Question
Title: What is the type parameter on the NRF24NetworkHeader member
Link of the member What is the character parameter in the above member of the class NRF24Network I cannot understand the use of it.

# Answer
It's to identify the type of packet. Apparently that code supports types of 0-127, and I guess (impossible to tell without digging into the code) that what you use them for is entirely up to you. Basically it would typically define what is in the rest of the packet - again something which is up to you.
> 1 votes

---
Tags: library, nrf24l01+
---


title: DC Motor not behaving reliably

text:
# Question
Title: DC Motor not behaving reliably
Using an Arduino Mega. I have a motor hooked up exactly like the picture below. Using a BC548B transistor, 1N4001 diode, 220 ohm resistor and a 9V battery. I'm driving the motor in code by using PWM analogWrite to value 255. Weird thing is, if hooked up to USB (5V), the motor will only start to move after a certain amount of time, seems like it needs some initial "drive" to get started. If using the 9V battery it starts up quicker, but still not directly, as I would expect. Also, if I set analogWrite to some value less than 255, it will not move at all - is the transistor limiting? Can I change the resistor value to compensate? Thanks for any advice.

```
int motorPin = 3;
int interval = 10;
int walkingTime = 7.5;
bool walking = false;

void setup() {
  pinMode(motorPin, OUTPUT);
}

void loop() {
  delay(interval * 1000);
  if (!walking) {
    startWalk();
    delay(walkingTime * 1000);
    stopWalk();
  }
}

void startWalk() {
  walking = true;
  analogWrite(motorPin, 255);
}

void stopWalk() {
  walking = false;
  analogWrite(motorPin, 0);
}

```

# Answer
**Summary:**

Your transistor is the wrong way round.
Rotate it 180 degree (so that collector and emitter are swapped) and it should work.

There are much better transistors available for this job, but this one should work when correctly connected.

Swap, test, report back.

The blue wire goes from emitter (right hand lead) to Arduino ground.

**Longer:**

The transistor is almost certainly "backwards" as above. More on that below, but first some comment on the actual transistor used and a superior alternative.

While it should work better than you describe, the BC548 is not a very good transistor for motor driving. It's maximum collector current is 100 mA. While you do not state the required motor current, within sensible limits a good guide is that the more a transistor can handle the better it will work, all else being equal. A 500 mA rated part would work better. An excellent pair of small transistor for "playing" are the BC327-40 (PNP) and the complementary BC337-40 (NPN). These have guaranteed current gains (effectively current amplification factor) of 250 and typically of 400. They are typically rated at 45V and 500 mA. The Fairchild versions data sheet here from Digikey have an absolute maximum 800 mA rating. While the part was originally a European one it is widely available in the US and Asia and is usually about the same price as transistors with substantially inferior specs. eg see Digikey pricing below for BC548B and BC337-40 in 1, 10 and 100 quantity. The BC337 costs 1 cent more per transistor in each case. The BC337 comes in 3 versions with suffixes -16, -25 and -40. This relates to the current gain. The -40 part has an average Beta or current gain of 400. This is better (higher) than most alternatives and costs little or no more than the lower gain -16 and -25 parts.

BC548B datasheet here
BC337-40 datasheet here

BC548B pricing
1 10 100 prices are 22 / 20 / 11 cents each.

BC337-40 pricing
1 10 100 prices are 23 / 21 / 12 cents each.

According to that the pinout is CBE (collector base emitter) left to right looking at flat front with pins down. There are occasionally variations between manufacturers (but should not be) but if the datasheet matches your transistor it is "in backwards".

Swap C & E by rotating 180 degrees and report back.
With C&E swapped it acts like an NPN withj very low current gain.

Note: Presumable where you saay digitalWrite you meant analogWrite?
> 1 votes

---
Tags: arduino-mega, motor, transistor
---


# Question
Title: Smallest package possible reading microSD
I have a project running on an arduino nano, and as part of it, I'd like to read from and write to a microSD card. My problem is that the microSD shield for it doesn't fit my form factor (think slightly larger than a pen; definitely handheld).

I've purchased a PJS008-2003-0, and I'm wondering, assuming I have the soldering chops, is there any real reason I can't connect this directly? What does the breakout board get me other than nicer connection points and a blinking light? Do the example SD sketches rely on anything the shield provides, or will they work for me?

# Answer
> 1 votes
SD card need 3.3v for power and logic level. So most breakouts have a buffer chip to convert the logic levels from 5v to 3.3v.

PS, you could use an microSD to SD adapter, and solder some wires to its pads, if you are unable to solder the tiny pins on the part you ordered.

# Answer
> 1 votes
If your willing to be adventurous and step away from Arduino (as in AVR chips) and try out some of the myriad of other offerings there are around now, then you may find a better board that fits your needs.

One popular example is the Fubarino SD:

It gives you a PIC32 chip (128KB RAM, 512MB Flash, 80MHz) with a microSD card slot already on the board. And it measures just 2.5cm x 7cm.

Of course, you may need to tweak your programming a little to get it working as you want - the IDE (MPIDE) is a bit old and the Arduino API compatibility is slightly behind the times (but catching up gradually). It's also fully supported by my UECIDE programming environment.

# Answer
> 0 votes
Most likely you will have to add at least some pullup/pulldown resistor. I would recommend having a look at the schematics of the shield. For example this shield: http://freematics.com/store/index.php?route=product/product&product\_id=74

And it depends on which mode you want to use (SPI?): http://en.wikipedia.org/wiki/Secure\_Digital#Transfer\_modes

---
Tags: shields, arduino-nano, sd-card
---


title: DHT22 Does not update

text:
# Question
Title: DHT22 Does not update
Good evening :)

I am fairily new to coding the fabulous Arduino UNO. My project right now are consisting of reading Temperature from a DHT22 (AM2302) and writing to a 4-digit 7-segment display. I have got the display to work, but the system does not update the temperature at all. Just the first reading are displayed

```
#include <DHT.h>
  #include <TimerOne.h>
  #include <SevenSeg.h>

  #define DHTPIN 4    //Defines the temp-pin

  /* DHT22- Pin1 (left) - 5V/3.3V
  Pin2- DATA
    Connect a 10K res from pin1 to pin2
  Pin3 - NC
  Pin4 - GND
  */

  //#define DHTTYPE DHT11   // DHT 11
  #define DHTTYPE DHT22   // DHT 22  (AM2302)
  //#define DHTTYPE DHT21   // DHT 21 (AM2301)

  DHT dht(DHTPIN, DHTTYPE);

  SevenSeg disp (13 ,2 ,3 ,8 ,5 ,6 ,7);
  //            (11, 7, 4, 2, 1, 10, 5)
  const int numOfDigits =4;
  int digitPins [ numOfDigits ]={9,10,11,12};  // uten transistorer
  //                            (12,9,8,6) Alle med 220 Ohm seriemotstand
  //int digitPins [ numOfDigits ]={12,11,10,9};  // med transistorer

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

    disp . setCommonCathode();  // uten transistorer
    //disp . setActivePinState(HIGH,HIGH);  // med transistoere
    disp . setDigitPins ( numOfDigits , digitPins );

    Timer1.initialize(15);   // 0.015 sek
    Timer1.attachInterrupt(loop);
  }

  void loop() {

    dht.begin();

    delay(300);
    float t = dht.readTemperature();

    disp.writeFloat(t);
    Serial.println(t);

  }

```

How do I get the Sensor to update regularly?

# Answer
> 3 votes
Try moving `dht.begin();` to `setup()`.

The DHTs are pretty slow and need some time (of the order of seconds!) between consecutive reads. In `dht.begin()` an internal timer is reset that is used in `readTemperature()` to ensure that reading data from the DHT is not attempted in shorter intervals than supported. By calling `dht.begin()` every 300 ms you're making this meachanism inoperative. You're supposed to call `dht.begin()` only once at start-up.

**Edit**: And please also remove the `Timer1` that calls `loop`. `loop` is already an infinite loop, so no good in calling it additionally from an interrupt...

# Answer
> 0 votes
Try this in your loop method The while loop will read the temperature, write to the display and write to the console.

```
void loop() {
  dht.begin();
  float t;
  while(1)
  {
    t = dht.readTemperature();
    disp.writeFloat(t);
    Serial.println(t);
  }
  delay(300);

```

}

---
Tags: arduino-uno
---


title: Relay feedback control

text:
# Question
Title: Relay feedback control
I have a two-relay system set up to a DC motor. So, if I close one relay, the motor moves on one way and if I close the second relay (and open the first) the motor goes on the other direction.

I compare two variables (target inclination and real inclination) if they are not the same I would like to open one of the two relays UNTIL the are the same value.

Both variables are calculated based on inclinometer input and some aritmethics.

I do know how to calculate the variables, how to close the relay based in the comparation of variables and which relay open.

But I don´t know how I can tell to open the relay because the motor has reached target inclination.

How I can recalculate and compare constantly target inclination and real inclination when the relay is closed and the motor moving? Is this posible on Arduino? Is this multithreading?

Thank you very much, any ideas are welcome!

# Answer
> 1 votes
This is a classic system where PID will really pay off. Basically this will allow you to tune your system so that if you are off by 5 degree it will open the relays for 3 seconds. But if you are off by 1 degree it will open them for half a second. (Or whatever works for you). It might be tricky for you to get right but it will give you the smooth response that looks really good and feels natural.

Take a look here http://playground.arduino.cc/Code/PIDLibrary

# Answer
> 2 votes
Answering my own question, I think I found some way to get the solar panel face the sun.

As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:

```
void lookforsun() {
  while ((targetElevation + 3) < realElevation | (targetElevation - 3) > realElevation) {

    Serial.println("Elevation is not correct");

    while (realElevation < targetElevation)
    { Serial.println("Moving to south");
      digitalWrite(south, LOW);
      lookposition();
    }
    digitalWrite(south, HIGH);

    while (realElevation > targetElevation)
    { Serial.println("Moving to north");
      digitalWrite(north, LOW);
      lookposition();
    }
    digitalWrite(north, HIGH);
  }

  while ((targetHourangle+3) < realHourangle |  (targetHourangle-3) > realHourangle  ) {

    Serial.print("Hour angle is not correct");
    while (realHourangle > targetHourangle)
    { Serial.println("Moving to east");
      digitalWrite(east, LOW);
      lookposition();
    }
    digitalWrite(east, HIGH);

    while (realHourangle < targetHourangle)
    { Serial.println("Moving to west");
      digitalWrite(west, LOW);
      lookposition();
    }
    digitalWrite(west, HIGH);
  }

```

As you can see I took the frightening way of nested while loops, but appears to work.

The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.

I included the +-3 because the sensor is so very sensible.

Thank you very much Russell McMahon and portforwardpodcast for your ideas!

---
Tags: arduino-mega, motor, relay, solar
---


# Question
Title: Arduino resets when I call network.begin()
I have included the **RF24Network** library in my project. I tried to use the Simple Transmit/Receive example from here but when it calls the **network.begin()** my arduino restarts. I placed some **Serial.println()** in order to understand where is the problem. This problem appears only in my Arduino Mega 1280. I tried the same code on my Arduino Pro mini and it works like a charm. What causes this? How to fix that? It is very important to use the specific library. Thanks in advance.

# Answer
> 2 votes
The problem was that the RF24Network library is **not compatible** with the version of Arduino IDE I have. I downloaded Arduino IDE v1.0 and now it works like a charm. I will send an email to maniacbug to tell him about the problem.

---
Tags: arduino-mega, nrf24l01+, networking, rf
---


# Question
Title: Connecting GSM Dongle to Intel Galileo-Gen 2
I have tried to connect a GSM dongle to a Intel Galileo Gen2 board and test the functionality of sending and receiving SMS through it.I know that it is easier to use a GSM shield to do above, but I'm currently doing a project in the way i mentioned above.Basically in Linux, we should know the serial port(like `ttyACM0` in `/dev` directory) correspond to the device to communicate with it(Using AT commands).

but when i tried it in Galileo board it doesn't show such a serial port.but it detect device because `lsusb` command shows the device.

does anyone can help me to solve this matter?

# Answer
Try updating the firmware. I'm not sure if this affects also ACM type serial ports, but the initial version of the firmware was not even creating standard /dev/ttySx, rather some weird proprietary interface. Luckily this was fixed later on. So, in case you are still running the FW that the board came with, chances are you are having these weird serial ports.
> 1 votes

---
Tags: serial, gsm, arduino-galileo
---


# Question
Title: Arduino UNO/ZERO PRO, enough computing power for PID-controller?
I am currently working on a project, where I design a PID-Controller for a 2-axis stabilization with brushless-propeller-motors.

My question is: Does an Arduino UNO have enough computing power to perform this task in a useful manner? Arduino UNO Specs

And secondly: If the UNO was really too slow for this task, would the newly released Arduino ZERO PRO perform at an acceptable rate? Arduino ZERO PRO Specs

Thanks for your help and inputs in advance!

# Answer
> 5 votes
Assuming you're not doing anything too fancy, yes, it should be fine.

There's even a library to do all the work for you: http://playground.arduino.cc/Code/PIDLibrary

---
Tags: power
---


# Question
Title: Arduino 1.6.4 not showing any /tty/ options in Serial ports
hej guys,

recently I upgraded to Arduino's 1.6.4 IDE just to find out, that I can't seem to upload anything to my board. More specifically: The 1.6.4 IDE is not giving me the option to select the /tty/ board from the serial port list. I am avid Sublime Text 2 user, so obviously I tried to select the port in Stino and voilá: I was **able** to upload it to my boards.

Since I wanted to sort out if this is a software or hardware problem, I started to experiment with all my boards:

(all of them official boards, no clones)

* 2 x Arduino Micro
* 1 x Arduino Uno r3
* 1 x Arduino Duemillanove
* 1 x Arduino Mega 2560 r3
* 12 x Teensy 3.1
* a bunch of different USB cables.

none of these boards were registered by the Arduino 1.6.4 IDE, even after restarting the software and the computer several times. i'd only get this in my port selection:

funny enough, my terminal told me the /tty/ device was there. here with the uno connected:

```
Dash:~ julianh$    ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodemfa131

```

I also tried to re-install FTDI drivers, with no results.

only when I installed the old (trusty) 1.6.1 version, I was able to upload again.

all of the boards are also working fine. I just used my uno and mega another machine a few days ago for some side projects.

can someone confirm this problem with the new IDE 1.6.4 on OSX Yosemite 10.10.3? or is there any solution available online?

thanks!

# Answer
I had the same problem when updated to 1.6.4, but with a Spark fun Pro micro. Did a "reset to bootloader" on the pro micro, and hit upload, and it worked out nice and it still does!
> -1 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide
---


# Question
Title: Change code so motion sensor prints time instead of a button
I have the code below. At the moment there is a proximity sensor that makes a speaker play happy birthday when it is set off. I also have an LCD shield attached and when one of the buttons on LCD screens interface is pressed, the time that it was when the button was pressed prints on the screen. I need to get it so that when the proximity sensor is set off it plays the sound on the speaker and then prints the time which is was set off on the screen.

```
/*--------------------------------------------------------------------------------------
 Includes
 --------------------------------------------------------------------------------------*/
#include <Wire.h>
#include <LiquidCrystal.h>   // include LCD library

int timer = 1000;
int C = 262;
int D = 294;
int E = 330;
int F = 349;
int G = 392;
int A = 440;
int B = 494;
int Bflat = 466;
int Chigh = 523;

const int analogPin = A1;    // pin that the sensor is attached to
const int threshold = 400;

/*--------------------------------------------------------------------------------------
 Defines
 --------------------------------------------------------------------------------------*/
// Pins in use
#define MILLIS_OVERFLOW 34359738
#define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
#define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
// ADC readings expected for the 5 buttons on the ADC input
#define RIGHT_10BIT_ADC           0  // right
#define UP_10BIT_ADC            145  // up
#define DOWN_10BIT_ADC          329  // down
#define LEFT_10BIT_ADC          505  // left
#define SELECT_10BIT_ADC        741  // right
#define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing     window
//return values for ReadButtons()
#define BUTTON_NONE               0  //
#define BUTTON_RIGHT              1  //
#define BUTTON_UP                 2  //
#define BUTTON_DOWN               3  //
#define BUTTON_LEFT               4  //
#define BUTTON_SELECT             5  //
//some example macros with friendly labels for LCD backlight/pin control,     tested and can be swapped into the example code as you like
#define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
#define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
#define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
/*--------------------------------------------------------------------------------------
 Variables
 --------------------------------------------------------------------------------------*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 34, hours = 8;

byte buttonJustPressed  = false;         //this will be true after a        ReadButtons() call if triggered
byte buttonJustReleased = false;         //this will be true after a     ReadButtons() call if triggered
byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for detection of button events
/*--------------------------------------------------------------------------------------
 Init the LCD library with the LCD pins to be used
 --------------------------------------------------------------------------------------*/
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2     LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
 setup()
 Called by the Arduino framework once, before the main loop begins
 --------------------------------------------------------------------------------------*/
void setup()
{
  //button adc input
  pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
  digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
  //lcd backlight control
  digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is     high (on)
  pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
  //set up the LCD number of columns and rows:
   pinMode(13, OUTPUT);
  lcd.begin( 16, 2 );

  //Print some initial text to the LCD.
  Serial.begin(9600);
  lcd.begin( 16, 2 );

}
/*--------------------------------------------------------------------------------------
 loop()
 Arduino main loop
 --------------------------------------------------------------------------------------*/
void loop()
{

  setClock();
  byte button;

  button = ReadButtons();

  /**
   * After set clock now you have 3 int variables with the current time
   */
  //seconds
  //minutes
  //hours
  lcd.setCursor ( 0, 1);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.print(":");
  lcd.print(elapsedMillis);

  //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

  //blank the demo text line if a new button is pressed or released, ready for a new label to be written

  //show text label for the button pressed
   if(buttonJustPressed || buttonJustReleased)
  switch( button )
  {

  case BUTTON_LEFT:
    {
      lcd.setCursor( 0, 0 );
               lcd.print(hours);
               lcd.print(":");
               lcd.print(minutes);
               lcd.print(":");
               lcd.print(seconds);
               lcd.print(":");
               lcd.print(elapsedMillis);

      break;

    }
  default:
    {
      break;
    }
  }

  if( buttonJustPressed )
    buttonJustPressed = false;
  if( buttonJustReleased )
    buttonJustReleased = false;
}
/*--------------------------------------------------------------------------------------
 ReadButtons()
 Detect the button pressed and return the value
 Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
 --------------------------------------------------------------------------------------*/
byte ReadButtons()
{
  unsigned int buttonVoltage;
  byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn

  //read the button ADC pin voltage
  buttonVoltage = analogRead( BUTTON_ADC_PIN );
  //sense if the voltage falls within valid voltage windows
  if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_RIGHT;
  }
  else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_UP;
  }
  else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_DOWN;
  }
  else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_LEFT;
  }
  else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_SELECT;
  }
  //handle button flags for just pressed and just released events
  if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
  {
    //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
    //it's the duty of the receiver to clear these flags if it wants to detect a new button change event
    buttonJustPressed  = true;
    buttonJustReleased = false;
  }
  if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
  {
    buttonJustPressed  = false;
    buttonJustReleased = true;
  }

  //save the latest button value, for change event detection next time round
  buttonWas = button;

  return( button );
}
void setClock()
{
  currentMillis = millis();
  /**
   * The only moment when currentMillis will be smaller than previousMillis
   * will be when millis() oveflows
   */
  if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
  }
  else {
    elapsedMillis += currentMillis - previousMillis;
  }

  /**
   * If we use equals 1000 its possible that because of the mentioned loop limitation
   * you check the difference when its value is (999) and on the next loop     its value is (1001)
   */
  while (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
  }

  if (seconds == 60){
    minutes++;
    seconds = 0;
  }
  if (minutes == 60){
    hours++;
    minutes = 0;
  }
  if (hours == 24){
    hours = 0;
  }

  previousMillis = currentMillis;

 int analogValue = analogRead(analogPin);
  if (analogValue > threshold) {

tone(13,C,timer/2);// Happy Bday to You
delay(200);
tone(13,C,timer/2);
delay(200);
tone(13,D,timer/2);
delay(400);
tone(13,C,timer/2);
delay(400);
tone(13,F,timer/2);
delay(400);
tone(13,E,timer);
delay(750);
 }
else {

}
}

```

# Answer
The code seems a little hotchpotch; is the code for reading the sensor supposed to be within the `setClock()` function? It would be better to put the following within `loop()`:

```
if(analogRead(analogPin) > threshold)
{
    playMelody();
    printTriggerTime();
}

```

And create two new functions that handle the playing of 'Happy Birthday' and the printing of the time:

```
void playMelody()
{
    tone(13, C, timer / 2);// Happy Bday to you
    ...
    delay(750);
}

```

...which is just a cut-paste of what you've got in the `setClock()` function, and:

```
void printTriggerTime()
{
    lcd.setCursor(0, 0);
    ...
    lcd.print(elapsedMillis);
}

```

...which is a copy-paste of the code from within `case BUTTON_LEFT:`.

This will now play 'Happy Birthday' and print the time whenever the proximity sensor is triggered, AND it will print the time when the left-button is pressed (unless you remove that part of the code).

On a separate point, it's bad coding practice to use `#define` for a function, as you have done with `#define LCD_BACKLIGHT(state) { if ( state )...` \- it makes it quite difficult to read the code, and can't conceive any reason why this isn't its own function. However, a nice trick in C is the following 'shortcut' statement:

```
( CONDITION ? DO_IF_TRUE : DO_IF_FALSE )

```

Thus you should change that line to:

```
#define LCD_BACKLIGHT(state) ( state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW))

```

That being said, "LCD\_BACKLIGHT(state)" isn't actually used anywhere in the program!
> 2 votes

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


title: Incremental encoder code

text:
# Question
Title: Incremental encoder code
can somebody tell me what\`s wrong with my code, i am using it to calculate rpm using incremental encoder

```
long counter=0;
 long  rpm = 0, z =0;
 long  ini_time = 0;
long  end_time=0;

void setup(){
  attachInterrupt(0, A_RISE, RISING);

  Serial.begin(115200);
}//setup

void loop(){

    Serial.println(rpm);
}

void A_RISE(){
  counter ++;
  if (counter == 1)
    ini_time = micros();
  else if (counter>470){ //470 is ticks per revolution
    z = counter;
    rpm_counter(z);

    counter =0;
  }
}

void rpm_counter(int x){

  end_time=micros()-ini_time;
  rpm=(60*10^6)/end_time;

}

```

# Answer
**Volatile**.

Essentially any variable declared within global scope (anything you declare before you get to `setup()`) MUST have the `volatile` qualifier if you want to use it within an interrupt service routine otherwise it will not be correctly utilised/implemented/instantiated.

As your code stands, you need to add `voltatile` to all four of your global variables:

```
volatile int counter = 0;     // if you're stopping at 470, int is all you need
volatile long rpm = 0;
volatile long z = 0;          // this isn't necessary, see below!
volatile long ini_time = 0;
voltaile long end_time = 0;

```

Your ISR includes some wasteful instructions, which will increase the time it takes for the routine to complete. As @jfpoilpret suggested, you may be constantly interrupting `loop()`. Cutting the time down may solve this:

Firstly, `z = counter; rpm_counter(z);` . Pointless, if I'm honest. Why not just call rpm\_counter with counter?

Secondly, `rpm_counter()` function... it doesn't use the arguement you sent! "`x`" is not used anywhere within the function, so why are you sending it?

Thirdly, even if my second point wasn't valid `rpm_counter()` doesn't really need to be a function in its own right. Unless you're going to be calling it from lots of different places, just inline the contents of the function to into `A_RISE()`:

```
else if (counter>470)
{ //470 is ticks per revolution
    end_time = micros() - ini_time;
    rpm = (60*10^6) / end_time;
    counter = 0;
}

```

That could save a great deal of execute cycles.
> 0 votes

---
Tags: arduino-uno, rotary-encoder
---


# Question
Title: SPI Arduino Due conflict with pinMode(), bug?
Consider the following minimal example, where I set `pinMode` before calling SPI functions:

```
#include <SPI.h>

void setup() {
  pinMode(10, OUTPUT);
  SPI.begin(10);
  SPI.setDataMode(10,SPI_MODE1);
}

void loop() {
  delay(1000);
  SPI.transfer(10,1);
}

```

Now when `SPI.transfer(10,1)` is called in `loop()`, I always see that the slave selected pin goes down to 1.65V, but not 0 as it should! (see image below)

If we don't call `pinMode()`, like this:

```
#include <SPI.h>

void setup() {
  SPI.begin(10);
  SPI.setDataMode(10,SPI_MODE1);
}

void loop() {
  delay(1000);
  SPI.transfer(10,1);
}

```

We get what we would expect when calling `SPI.transfer`:

Is that a bug or do you have an explanation for that behaviour?

Thank you very much in advance for your time and interest!

# Answer
> 1 votes
It might have something to do with the internal pull up resistor. According to the SAM3X/A datasheet,

> Control of the pull-up resistor is possible regardless of the configuration of the I/O line.
>
> After reset, all of the pull-ups are enabled.

If you dig through all the include files you find:

```
../Arduino/hardware/arduino/samd/cores/arduino/wiring_digtal.c

```

Line 124 defines the `pinMode(uint32_t ulPin, uint32_t ulMode)` function. Examining the switch/case statement for INPUT vs INPUT\_PULLUP vs OUTPUT you see the following:

1. INPUT sets a register to `reg = PORT_PINCFG_INEN`.
2. INPUT\_PULLUP sets a register to  `reg = (PORT_PINCFG_INEN | PORT_PINCFG_PULLEN)`
3. OUTPUT sets a register to `reg &= ~PORT_PINCFG_INEN`.

The 'register' in each case is the same. I cannot for the life of me find what value PORT\_PINCFG\_INEN or PORT\_PINCFG\_PULLEN are defined as, but they're no doubt just 8-bit masks (they're cast to uint8\_t when they're assigned to the 'register'). Thus, we can assume that whichever bit controls input/output is active when asserted, as is the pullup bit. For example:

```
 PORT_PINCFG_INEN   = b'00000001';
 PORT_PINCFG_PULLEN = b'00000010';
~PORT_PINCFG_INEN   = b'11111110';

```

If pull-ups are enabled after reset, we can say that on reset:

```
 reg = b'xxxxxx1x';

```

Point (3) above strongly implies that the instruction is:

```
 reg = b'xxxxxx1x' & 'b11111110';
   so
 reg = b'xxxxxx10'; // pull-up is enabled!

```

Therefore, *if you call pinMode(X, OUTPUT) before anything else* you will end up with the pullup resistor enabled. Setting the pin to an input will clear the pullup enable bit, after which you can set the pin to an output and the bit will remain clear.

However, the whole arguement falls down with the simple fact that if you don't call pinMode() **at all**, the problem doesn't occur...

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


title: RF network using Arduino

text:
# Question
Title: RF network using Arduino
I am working on home automation project. A network consists of one master device and many (maybe 10-20) slave devices, all communicating via these RF modules. I am using arduino in slave devices. Master will be based on raspberry Pi (most probably). Slave nodes can be sensors or switches(to control household electronics). To and fro communication will include data such as : a) Turn off bulb 1, b) Turn on TV, c) Set the bulb brightness to 34%, d) Temperature reading is 23 degree Celsius etc.

From security point of view, imagine there are similar other networks in the range and one network must not interfere with another. As such, I need to implement some sort of authentication whenever each data transfer takes place between master \<---\> slave. **What logic do you suggest for this process?**

There can be cases when data has not been received successfully by the receiving end. In such cases, I am planning to use some sort of checksum and acknowledgement system. If acknowledgement is not received, data will be resend in time intervals of 1s, 5s, 10s, 30s, 30s. If these 5 resends fail, the slave/master will be considered as unavailable/powered down. **Your opinions/suggestions on this?**

Slave arduino will be busy controlling appliances/sensors connected to it (real busy when controlling appliances). As such, it won't have much time for communication. Less time required for communication == Awesome. **How much time do you think the arduino will take to complete one such data transfer?**

Another solution I could think of was using two arduinos connected via i2c in each slave module. One arduino will be busy controlling the lights/sensors. Other one will take care of RF communication. If it receives some valuable info which was meant for this particular module, it will transfer the same to the other one using i2c bus. **Is this a feasible backup plan?**

**Am I doing wrong by selecting RF modules for this purpose? Should I switch to Zigbees?**

Thanks guys for reading. Any constructive suggestions from your side will be very helpful.

# Answer
> 1 votes
The NRF24s are great, but limited to communication only.

Digi's XBee 2mW module has got great indoor range, but more to the point **it's got 8 I/O lines and 6 10-bit ADCs on board**. It's also built for mesh networks (or you can get star-network equivalents) and has security encryption to boot. This means that, for some of your nodes, you don't need any other hardware to have a fully functioning control point (not including relays and sensors of course), so you can ditch having arduinos at every node.

They're so easy to use, very low power, and have plenty of support and documentation available online.

Do it!

---
Tags: arduino-uno, rf, networking
---


# Question
Title: How shiftOut function works internally? (explanation on source code)
I were examining `shiftOut()` function code in `wiring_shift.c` and I didn't quite understand what is going in digitalWrite function. I see `!!(val & (1 << i))` is taking the bit value from `val` but how exactly it works?

The whole function is below.

```
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

```

# Answer
> 9 votes
I'll assume `bitOrder == LSBFIRST`.

* `i` is the bit number, i.e. the “index” of the next bit to write
* `1` is `00000001` in binary
* `<<` is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
* `1<<i` is binary `00000001` shifted left by `i` positions, i.e. something like `0...010...0`, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
* `&` is the “bitwise and operator”, where `any_bit & 0` is zero and `any_bit & 1` is `any_bit`
* `val & (1 << i)` is `0...0(i-th bit of val)0...0` in binary, where the i-th bit of val is in the i-th position of the result
* `!!` is a double negation: it converts zero to zero and any non-zero value to one
* `!!(val & (1 << i))` is either 0 or 1, and is exactly the i-th bit of val

---
Tags: c++, arduino-ide, core-libraries
---


title: Can I use an arduino as a ground short?

text:
# Question
Title: Can I use an arduino as a ground short?
I have a little personal project involving an Arduino Uno and an amp board from Sure Electronics. The amp has contacts for a mute function that involves shorting the contact to ground. I would like to control this muting with the Arduino which I was planning to do with a relay. However I think I might be complicating things and I thought it might be possible to do it directly with the pins.

Can I use the Arduino to directly short a circuit to ground? Or would I need something more complicated to be safe?

# Answer
> 2 votes
Depends on the voltage that is on that mute pin. If it's below 5 volt, you could use the arduino pin. You can measure the voltage using a multimeter.

If it's more than 5v you can use a NPN transistor and resistor combination.

Current isn't a problem with these kinds of "settings" pins, as there is just a pull-up resistor that by default (unconnected) sets the pin to HIGH. By connecting the pin to ground you set the pin to LOW.

# Answer
> 1 votes
I can't see how much current the amp board will sink into the Arduino so like FuaZe I would recommend using your Arduino to drive an external component that you know can take the current. This isn't really complicating the design too much, use an NPN transistor, with the P connected to the Arduino and just write High to the pin when you want to apply the mute. If you blow the transistor then its going to cost you a few pence for a new one, if you blow your Arduino you are down £20!

---
Tags: arduino-uno
---


# Question
Title: Serial communication stops when I connect the tx cable
I'm using the apc220 rf modules. Now I'm having the following problem:

My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.

Is my rf module broken, or can someone help me with this?

# Answer
> 1 votes
To have two serial ports on Arduino board like Uno use `SoftwareSerial.h`.

Example

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("Hello!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

```

Now after opening `Serial monitor` you should see Hello! and then you can test `SoftwareSerial`.

**DO NOT FORGET!!!**

When you connect to pins 2,3 or etc, this is **TTL** voltage level. You **can't** connect direct to RS232.

---
Tags: serial, rf
---


title: DHT11 with Mysql

text:
# Question
Title: DHT11 with Mysql
I need help to record databаse from dht11 sensor to mysql server. this is my code:

```
#include <DHT.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
EthernetClient client;

IPAddress server(192,168,0,102); // IP Adres (or name) of server to dump data to

#define DHTPIN 2 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

float temperature = 0;  // TEMPERATURE VAR
float humidity = 0; // HUMIDITY VAR
String data;

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

    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
    }

    dht.begin();
    delay(10000); // GIVE THE SENSOR SOME TIME TO START

       temperature = (float) dht.readTemperature();
       humidity = (float) dht.readHumidity();

}

void loop(){

    currentMillis = millis();
    if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
        previousMillis = currentMillis;
        temperature = (float) dht.readTemperature();
                humidity = (float) dht.readHumidity();
    }

    if (client.connect(server, 3306)) {
          Serial.print("temperature=" );
          Serial.println( temperature );
          Serial.print("humidity=" );
          Serial.println( humidity );
          Serial.println("-> Connected");
            if(client.connected()){
            // Make a HTTP request:
            client.print( "GET /add_data.php?");
            client.print("temperature=");
            client.print( temperature);
            client.print("humidity=");
            client.print( humidity);
            client.println( " HTTP/1.1");
            client.println( "Host: 192.168.0.102" );
            //client.println(server);
            client.println( "Connection: close" );
            client.println();
            client.println();
            client.stop();
          }
        }
    if (client.connected()) {
        client.stop();  // DISCONNECT FROM THE SERVER
    }

    delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

```

I connected to database but can't make records. this is output on serial monitor: temperature=21.00 humidity=73.00 -\> Connected

this is my php:add\_data.php

```
<?php
    // Connect to MySQL
    include("dbconnect.php");

    // Prepare the SQL statement
    $SQL = "INSERT INTO test.test.temperature (temperature ,humidity) VALUES ('".$_GET["temperature"]."', '".$_GET["humidity="]."')";

    // Execute SQL statement
    mysql_query($SQL);

    // Go to the review_data.php (optional)
    header("Location: review_data.php");
?>

```

dbconnect.php=\>

```
<?php
$MyUsername = "root";  // enter your username for mysql
$MyPassword = "fifa2005";  // enter your password for mysql
$MyHostname = "localhost";      // this is usually "localhost" unless your database resides on a different server

$dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
$selected = mysql_select_db("test",$dbh);
?>

```

review\_data.php=\>

```
<html>
<head>
    <title>Arduino Temperature Log</title>
    <style type="text/css">
        .table_titles, .table_cells_odd, .table_cells_even {
            padding-right: 20px;
            padding-left: 20px;
            color: #000;
        }
        .table_titles {
            color: #FFF;
            background-color: #666;
        }
        .table_cells_odd {
            background-color: #CCC;
        }
        .table_cells_even {
            background-color: #FAFAFA;
        }
        table {
            border: 2px solid #333;
        }
        body { font-family: "Trebuchet MS", Arial; }
    </style>
</head>

<body>
<h1>Arduino Temperature Log</h1>
<table border="0" cellspacing="0" cellpadding="4">
    <tr>
        <td class="table_titles">ID</td>
        <td class="table_titles">Date and Time</td>
        <td class="table_titles">Temperature</td>
        <td class="table_titles">Humidity</td>
    </tr>
    <?php
    // Retrieve all records and display them
    $result = mysql_query("SELECT * FROM temperature ORDER BY id ASC");

    // Used for row color toggle
    $oddrow = true;

    // process every record
    while( $row = mysql_fetch_array($result) )
    {
        if ($oddrow)
        {
            $css_class=' class="table_cells_odd"';
        }
        else
        {
            $css_class=' class="table_cells_even"';
        }

        $oddrow = !$oddrow;

        echo '<tr>';
        echo '   <td'.$css_class.'>'.$row["id"].'</td>';
        echo '   <td'.$css_class.'>'.$row["timestamp"].'</td>';
        echo '   <td'.$css_class.'>'.$row["temperature"].'</td>';
        echo '   <td'.$css_class.'>'.$row["humidity"].'</td>';
        echo '</tr>';
    }
    ?>
</table>
</body>
</html>

```

# Answer
i'm not sure why my old code doesn't work, but this is my new one and it is working fine. Maybe it will help someone.

```
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>
EthernetClient client;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192.168.0.101";
dht DHT;
int interval = 5000; // Wait between dumps
#define DHT11_PIN 2
void setup()
{
  Ethernet.begin(mac);
  Serial.begin(115200);

  //Serial.println("Humidity (%),\tTemperature (C)");
}
void loop()
{
  Serial.print("Temperature2 = ");
    Serial.print(DHT.temperature);
    Serial.println(" *C");

    Serial.print("Humidity = ");
    Serial.print(DHT.humidity);
    Serial.println(" ");

  // READ DATA
  //Serial.print("DHT11, \t");
  int chk = DHT.read11(DHT11_PIN);

  if (client.connect(server, 80)) {

    client.print( "GET /diplomna/Arduino/add_data.php?");
    client.print("temperature=");;
    client.print( DHT.temperature );
    client.print("&&");
    client.print("humidity=");
    client.println( DHT.humidity );
    client.println( "HTTP/1.1");
    client.println( "Connection: close" );
    client.stop();
    Serial.println("CONNECTED");
  }
  else {
    // you didn’t get a connection to the server:
    Serial.println("–> connection failed/n");
  }
  delay(interval);
}

```
> 1 votes

# Answer
You can break down testing in steps.

Call your PHP page from the browser with some dummy parameters and see if it saves them in the DB.

If that part works use a network sniffer, like WireShark to sniff the TCP connection and make sure the correct data is sent to the PHP server from the Arduino.

Depending on which part is not working you can ask the question in the appropriate stack exchange.
> 1 votes

# Answer
You have one problem in the construction of your HTTP GET request on Arduino side:

```
        // Make a HTTP request:
        client.print( "GET /add_data.php?");
        client.print("temperature=");
        client.print( temperature);
        client.print("humidity=");
        client.print( humidity);

```

You forgot to separate both request arguments with an ampersand. It should be:

```
        // Make a HTTP request:
        client.print( "GET /add_data.php?");
        client.print("temperature=");
        client.print( temperature);
        client.print("&humidity=");
        client.print( humidity);

```

Note the `"&humidity"` instead of just `"humidity"`.
> 1 votes

---
Tags: arduino-uno, ethernet, temperature-sensor
---


# Question
Title: Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop
I have this:

```
class Person{
public:
    int age;
};

Person p;
p.age;

void setup() { ... }

void loop() { ... }

```

And I got this error:

```
Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
MyProgram.ino:18:1: error: 'p' does not name a type
Error compiling

```

But is I use the Person instance inside setup or loop functions it compiles find.

```
void setup() {
    // initialize digital pin 13 as an output.
    Person p;
    p.age;
}

```

I got this:

```
Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs)
Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum)

```

What is the different? Why the instance only can be used into the blocks?

I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?

# Answer
As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it). More specifically, you can only perform "programatical" operations from within a *function*. Anything outside a function (known as the *global scope*) is purely for declaration and initialization of variables and types, etc.

Any class variables declared in the *global scope* have their *constructor* executed before the rest of the program (even before `setup`) gets run. However, `setup` is not the first function to be called at startup.

Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used. Things like `pinMode` and `digitalWrite` are unsafe to use in a constructor, since there is a chance they may be negated during the startup. That is why the majority of Arduino classes have a `.begin()` method which is called from `setup()`.

The proper method for using classes with pin control and similar operations is:

1. The constructor takes the pins to use
2. The constructor saves those pins in variables
3. The begin() method is called in setup()
4. The pins are configured appropriately.

For example:

```
class myClass {
    private:
        int _myPin;
    public:
        myClass(int pin) : _myPin(pin) {}

       void begin() {
            pinMode(_myPin, OUTPUT);
            digitalWrite(_myPin, HIGH);
        }
};

myClass p(4);

void setup() {
    p.begin();
}

void loop() {
}

```

The object instance `p` is in the *global scope* and can be referenced from any function. The pin is configured only when setup() is run.

The startup sequence, more specifically, is typically this:

1. The memory used by global and static variables is "zeroed".
2. Any pre-defined variable values (*BSS*) are copied from flash into RAM.
3. Any object constructors are called.
4. The main() function is called (main startup function).
5. The init() function is called which configures the Arduino platform.
6. The initVariant() function is called which performs any board specific setup routines.
7. USB is configured on the boards that have it
8. Your setup() function is called.
9. Your loop() function is called.
10. The serialEvent() system runs if defined.
11. Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be. Some boards may do nothing more than configure interrupts and enable timers (for things like `delay` and `millis`), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself. Anything outside the scope of the class could be changed before you come to use it.
> 3 votes

# Answer
All code intended to be executed must be inside a function block in C++.
> 2 votes

---
Tags: arduino-mega, variables, class
---


title: FTDI Adjustable 3v3/5v only outputs 5v

text:
# Question
Title: FTDI Adjustable 3v3/5v only outputs 5v
I bought the below FTDI programmer for use with my 3v3 arduino pro mini. But even when the switch is set to 3v3 it is powering the board with 5v, (hence the IO voltage is also 5v). Note that when the pro mini is powered by batteries on the RAW input the IO voltage is 3v3 as expected. The problem is that when programming at 5v, any 3v3 peripherals (such as the BMP180) will be surely damaged.

http://www.ebay.co.uk/itm/301597777458?\_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

Now on the eBay description it says:

> This board ship default to 5V, but you can cut the default trace and add a solder jumper if you need to switch to 3.3V

Which trace needs to be cut, and where does the jumper need to connect to/from?

# Answer
The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else. The 5V pin of the header is connected straight through to the USB port's 5V pin.

You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins). It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch. That should make the output power switchable between 5V and 3.3V.
> 1 votes

---
Tags: power, voltage-level, arduino-pro-mini, ftdi
---


title: Stop at the end of a track

text:
# Question
Title: Stop at the end of a track
I would like to create a camera dolly for capturing timelapse movies.

i.e. something like this: http://youtu.be/Qce1f6SKEMU

Whats a reliable way to detect the end of the track and stop the stepper motor moving the camera? In other words how is it possible to get the current position of the camera and stop the motor before the track ends to prevent crashing into the bumpers?

# Answer
The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.

Printers have been doing it that way with their print heads for decades.

http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/
> 1 votes

# Answer
I find a mechanical switch the simplest and cheapest. But technically it is the same as an opto switch. These are often refered to as limit switches.

You tie the switch to a pin with the normally closed (NC) pin, set it to pinMode(pullup), and check it each each loop. When the read value goes low (0), you stop moving your motor.
> 1 votes

# Answer
Many methods exist:

References to unpowered means the switch does not draw power when not operated. When a motor is activated it will draw power.

* Mechanical switch- microswitch is the most common (as per Spiked3's suggestion). Contamination and weather may be issues (depending on how waterproof your camera is). No power needed for actual switch.
* Optical (a la Majenko). Some environmental issues. Effect of ambient light needs to be considered.
* Capacitive. Can be fully sealed. Need to be powered.
* Magnetic - Hall (powered) and Reed (unpowered).

Whatever is used, the current and voltage ratings need to be compatible with the load. In many cases the actual switch will need a transistor or relay or similar to provide the power drive to the dolly motor. This is not hard to do but needs to be noted.

---

An end of track signalling method that is relatively unaffected by environmental issues is to use a magnet and magnet detector. The most common detectors are either a "Hall sensor" IC or a reed switch.

Reed switches are mechanical and more fragile than Hall sensors but need no power when unoperated and can be bought in ready made encapsulations that are robust enough to be reliable. Properly implemented a reed switch can be essentially indestructible.

Hall sensors need to be powered but power levels are small compared to eg dolly motor current and low current versions are available.

Both Hall sensors and reed switches have a degree of "hysteresis" - the point in the travel where they operate is past the point where they release again, but this is easily allowed for in practice.

---

Reed switch demonstration \- 38 seconds video - simple and obvious.

Instructables DIY powered dolly wity reed swithes

Sparkfun magnetic door switch set and encapsulated reed switch and magnet.

Hall sensor theory of operation

Many ideas here for using hall sensors.

Reed switches
> 1 votes

---
Tags: motor
---


# Question
Title: Is arduino suitable for high frequency application?
Can I use the arduino for an application with a frequency of 4 MHz?

I need to create a clk with this frequency and send and receive data on the rising and falling edges. and it is not a normal SPI interface I have my own conditions so I need to do it manually.

If it is not suitable, is it technically possible?

# Answer
Most Arduinos are based on AVR chips clocked at 16 MHz. On those, you *can* generate a 4 MHz clock using hardware timers. Bit-banging data at this speed would be difficult though. It *may* be possible, using unrolled loops and hand-crafted assembly... or not, depending on the specifics of your application. Even if possible, it would be a nice challenge for an assembly programmer.

The Arduino Due is based on an ARM chip clocked at 84 MHz. This gives you more leeway to bit-bang at 4 MHz. But even on the Due you would certainly need hand-crafted assembly.
> 1 votes

# Answer
No, it's not suitable due to the inherent maximum pin output frequencies in relation to the clock divider setting.

Yes, it's technically possible. Edit the divider to a value that sets the output to close to what you need. However this is annoying to do, and has serious repercussions in your code. (i.e. having to multiply every timing/bit value by 16, 8, 4, 2 or whatever you choose)

A clock of that high of a frequency would have to be some crystal to set the base time, and then a comparator circuit that could vary fast enough to push data into the edges.

You could, however, simply note the absence of the 4MHz signal as 0, and it's presence as 1, sending binary data that way it probably a lot easier than encoding it between each individual edge.
> 0 votes

---
Tags: serial
---


title: Leonardo broken?

text:
# Question
Title: Leonardo broken?
My leonardo was working fine until today, when I plug it to my computer all led (RX/TX/L/ON) stays on (Green for on, amber for others) and my computer no longer see a com port. (by the way, do you know what the L led mean ?) If I add external power, TX goes off then after few seconds RX goes off too then back on. With external power, the atmega goes very hot (I can't touch it). RESET button do nothing.

Is my Leonardo dead ? Any idea what could have cause that ? The fact that the atmega is so hot when the board is powered up with 12V let me think that the voltage regulators is no longer working. Good guess ?

# Answer
By your description, I'd say:

> Quite Probably.

You should check what the 5V and 3.3V voltages are using a DMM.
> 1 votes

---
Tags: power, arduino-leonardo
---


title: Motorcycle Battery Powering Arduino UNO

text:
# Question
Title: Motorcycle Battery Powering Arduino UNO
Folks

I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.

I am wondering if this circuit will work fine.

C1 - 1000uF 50V; C2 - 1000uF 25V; D1 - 1N4001 ;

# Answer
Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

* The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.
* Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
*Rin* should be V/I = V\_drop\_max/I\_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
If you use the 6V output system I recommend below then you could allow closer to 3V drop in *Rin*.
If *Imax* is 100mA then *Rin* = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

* Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if *Rin* is used. Without *Rin* the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.

The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.

9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).

Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.

One superb version of this regulator is the LM2931-N \[**Data sheet here**\] \- this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.

The datasheet description states:

> Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
>
> During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
>
> The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.
> 4 votes

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