# Question
Title: How to calculate phase shift between two square waveforms with Arduino DUE
I have two square wave signals with the same frequency. I want to measure the phase shift between these two signals. There will be a small phase difference between two signals. (0-90 degree) and the frequency will vary in the range 100mHz - 50kHz. I am using an Arduino DUE (ATMEL ATSAM3X8E AU ,ARM)

I tried to use "micros()" for timer functionality to get 2 different times and then calculate the phase shift using the following code:

```
int led=47,count1=0,count2=0,temp=0;
int i=0,j=0;
float time1[3]={0,0};
float time2[3]={0,0};
float freq1=0,freq2=0;
float period1=0,period2=0;
float ps=0;

void setup()
{
      Serial.begin(9600);
      Serial.println();
       Serial.println();
      pinMode(31,INPUT);
      pinMode(33,INPUT);
      pinMode(led,OUTPUT);
      digitalWrite(led,HIGH);
      noInterrupts();
      attachInterrupt(31,in1,RISING);
      attachInterrupt(33,in2,RISING);
      interrupts();
}

void in1()
{      noInterrupts();
       switch(i){
           case 0 : time1[i]=micros(); i++;  break;
           case 1 : if(j==1){time1[i]=micros(); i++; break;}
       }
       interrupts();
}
void in2()
{      noInterrupts();
       switch(j){
            case 0 : if(i==1){time2[j]=micros(); j++; break;}
            case 1 : if(i==2){time2[j]=micros(); j++; break;}
       }
           if(j==2){
             period1 = (time1[1]-time1[0]);
             period2 = (time2[1]-time2[0]);
             freq1 = 1000.0/period1;
             freq2 = 1000.0/period2;
             ps = (((time2[1]-time1[1])*360.0)s/period1);
          if(freq1==freq2){
          Serial.println("");
          Serial.print("TIME1[0] = ");
          Serial.print(time1[0],6);
          Serial.print("\t TIME1[1] = ");
          Serial.print(time1[1],6);
          Serial.print("\t DEL1 = ");
          Serial.println(time1[1]-time1[0],6);
          Serial.print("TIME2[0] = ");
          Serial.print(time2[0],6);
          Serial.print("\t TIME2[1] = ");
          Serial.print(time2[1],6);
          Serial.print("\t DEL2 = ");
          Serial.println(time2[1]-time2[0],6);
          Serial.print("\t x = ");
          Serial.print(time2[0]-time1[0],6);
          Serial.print("period1(ms) = ");
          Serial.print(period1,6);
          Serial.print("\t period2(ms) = ");
          Serial.println(period2,6);
          Serial.print("freq1 = ");
          Serial.print(freq1,6);
          Serial.print("\t freq2 = ");
          Serial.print(freq2,6);
          Serial.print("\t Phase Shift = ");
          Serial.println(ps,6);
          }
          else {
          i=0;j=0;
          interrupts();
          }
       }
       interrupts();
}
void loop()
{
       ;
}

```

When I run this code I am not getting any errors, but in high frequency (above 400 Hz) Ihave a problem. When I tested at 0 degrees, this code produced this output:

```
400 Hz 1.152 degree
500 Hz 1.440 degree
600 Hz 1.727 degree
700 Hz 2.015 degree
800 Hz 2.304 degree
900 Hz 2.592 degree
1 kHz  2.880 degree
2 kHz  5.760 degree
3 kHz  8.649 degree
.
.
.
10 kHz 28.8 degree

```

Each frequency has lowest degree that this code can calculate.

How can I fix this code? Is it possible to calculate the phase shift between two square wave signals this way?

# Answer
With 0° you have two inputs triggering interrupts at the same time. That can't happen. You can't run two interrupts at the same time, so the second one gets queued up until the first has finished.

With all that serial printing in there there's going to be quite a delay between one interrupt triggering and the next one being allowed to trigger - giving you skewed results.

I would suggest passing your signal through an XOR gate so that you end up with a single small pulse that represents the phase shift between the two signals.
> 4 votes

# Answer
Even if your code worked perfectly, with zero processing latency, you still are working with a timer resolution of only 1 microsecond. If I did my math correctly, that means at 50 kHz, the smallest phase difference you can detect is around 18 degrees. At 100 MHz, 1 microsecond is 100 complete cycles. You probably want to look into hardware specifically designed for phase detection.
> 3 votes

# Answer
Connect the two signals to the TIOA pins of two different timer/counter channels on the same timer/counter block (either TIOA0 and TIOA1, which are Arduino pins 2 and A7, or any two of TIOA6, TIOA7, and TIOA8, which are Arduino pins 5, 3, and 11, respectively).

Set the two timer channels to capture mode, "up" counting, and internal clocking at the fastest rate that seems appropriate (I don't see any reason not to use `TIMER_CLOCK1` = 42MHz on the Due). Set them both to load RA on rising edge of TIOA, and RB on falling edge. Assuming TIOA0 and 1:

```
pmc_enable_periph_clk(ID_TC0);
TC_Configure(TC0, 0,
    TC_CMR_TCCLKS_TIMER1 |
    TC_CMR_WAVSEL_UP |
    TC_CMR_LDRA_RISING |
    TC_CMR_LDRB_FALLING
);

pmc_enable_periph_clk(ID_TC1);
TC_Configure(TC0, 1,
    TC_CMR_TCCLKS_TIMER1 |
    TC_CMR_WAVSEL_UP |
    TC_CMR_LDRA_RISING |
    TC_CMR_LDRB_FALLING
);

```

Set them both to generate interrupts on RA load:

```
TC0->TC_CHANNEL[0].TC_IER = TC_IER_LDRAS;
NVIC_EnableIRQ(TC0_IRQn);
TC0->TC_CHANNEL[1].TC_IER = TC_IER_LDRAS;
NVIC_EnableIRQ(TC1_IRQn);

```

Enable both clocks, and synchronize them so that they're both 0 at the same moment:

```
TC0->TC_CHANNEL[0].TC_CCR = TC_CCR_CLKEN;
TC0->TC_CHANNEL[1].TC_CCR = TC_CCR_CLKEN;
TC0->TC_BCR = TC_BCR_SYNC;

```

And handle the interrupts:

```
void TC0_Handler() {
    uint32_t status = TC0->TC_CHANNEL[0].TC_SR;
    if (status & TC_SR_LDRAS) {
        uint32_t tm = TC0->TC_CHANNEL[0].TC_RA;
        // rising edge of TIOA0 happened at "tm",
        // do something here to deal with it...
    }
}

void TC1_Handler() {
    uint32_t status = TC0->TC_CHANNEL[1].TC_SR;
    if (status & TC_SR_LDRAS) {
        uint32_t tm = TC0->TC_CHANNEL[1].TC_RA;
        // rising edge of TIOA1 happened at "tm",
        // do something here to deal with it...
    }
}

```

(Just defining functions with those names registers them as interrupt handlers, using weak-symbol magic).

If you choose to use TIOA6/7/8, the clock will be `ID_TC6`/`ID_TC7`/`ID_TC8`, and the `EnableIRQ` will be `TC6_IRQn`/`TC7_IRQn`/`TC8_IRQn`, but the `TC_Configure` calls will be `TC2, 0` / `TC2, 1` / `TC2, 2`, the `SYNC` will be issued to `TC2`, and the register accesses will be to `TC2->TC_CHANNEL[0]` / `TC2->TC_CHANNEL[1]` / `TC2->TC_CHANNEL[2]`. This is due to the way that the channels are grouped into blocks of three in the hardware. This is also why you have to use 0 and 1, or two of 6, 7, and 8; in order to sync the timers they have to be on the same block (and TIOA2 through TIOA5 aren't routed on the Due).

Because the clocks run at MClk/2 = 42MHz, the times you get will be in units of 1/42 microsecond, 42 times better than you get from `micros()`. Because the timer values are latched into the timer hardware *before* the interrupt is set, there isn't a problem if the two events come close to each other in time; you'll get the second interrupt after you finish handling the first, and the value in the register will still be valid (as long as you don't take so long that you miss more than one edge).

If you're interested in the falling edges, you can get those as well by setting the `TC_IER_LDRBS` bits and checking for `status & TC_SR_LDRBS` in your interrupt handlers.

Final advice: set your serial baud rate higher than 9600 if you can, you'll greatly decrease the amount of time you spend in `Serial.print`!
> 3 votes

---
Tags: c, programming
---


title: Problem Bootloading AVR328P-PU

text:
# Question
Title: Problem Bootloading AVR328P-PU
I executed the following steps in order to burn a bootloader into an AVR328P-PU chip I acquired on ebay.

1. I have set up AVR328P-PU on a breadboard as described here: http://arduino.cc/en/main/standalone
2. I have uploaded the ArduinoISP sketch into Arduion Uno.
3. Connected the wires in a way described here http://arduino.cc/en/Tutorial/ArduinoToBreadboard ( the setup with external clock)
4. Chose "Tools -\> Programmer -\> Arduion as ISP" in the IDE.
5. Chose "Burn Bootloader" from the IDE.
6. Got and error `avrdude: Yikes! Invalid device signature.`, noticed that I connected the wires in the wrong order.
7. Fixed the wired, but still got the error:

avrdude: Version 6.0.1

```
     System wide configuration file is "C:\Program Files\Arduino/hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.07s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

```

# My questions

1. I understand that this can be caused by poor breadboard quality. How can I test this hypothesis before buying new breadboard?
2. Could the wrong wiring from step 5 ruin the chip?

# Answer
Being from eBay, I would assume the seller "bricked" the chip beyond his/her capability to fix. Fortunately, you know about stack exchange!

My immediate suggestion is to find, borrow or build a high-voltage programmer. This is a special programmer that can un-brick the chip no matter what's been done to it. The concept is easy, but you need to protect the programmer's pins from the 12v reset signal.

Googling "avr high voltage programmer" gives several useful links. I'll get the actual links when I get back to a real computer.

Ok, so life got in the way, sorry about that. This is the one I built which worked perfectly: MightyOhm

However hooking up the AVR to a "high voltage programmer" is well documented in the data sheets. These should be very much similar circuits on Google.
> 1 votes

# Answer
I had this exact same problem. It turned out that my atmega328p had the wrong fuses. I am not sure how to solve the problem using the default ardiuino ide, however I was able to plug my ArduinoISP into a linux machine (just plug in the usb) and correctly profram the fuses on a slave atmega328p to solve the problem:

The guide here gets you started, however it missing some of the fuses: http://heliosoph.mit-links.info/arduinoisp-reading-writing-fuses-atmega328p/

The full command to set the default fuses is something like this:

```
avrdude -P /dev/ttyACM0 -b 19200 -c arduino -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m

```
> 1 votes

---
Tags: bootloader, avrdude
---


title: MCP7940 RTC Library

text:
# Question
Title: MCP7940 RTC Library
I am looking to implement a Microchip MCP7940 real time clock into my sensor data logging circuit that I have based on the Uno. Would the most logical solution be to attempt at changing an existing library to work with this clock (ie RTClib), or to begin from scratch and do the configuration directly in my program?

# Answer
In case anyone comes looking for an answer to this question, here is my solution:

I started with the excellent library by jeelabs (link: https://github.com/jcw/rtclib)

To create my new library, I changed a few of the register addresses, and added the few functions that I wanted it to do (set alarm, create an ordinal date, manually adjust the time with user input)

I posted my code to a Git project: https://github.com/crako1t/MCP7940-library-for-logger.git
> 1 votes

---
Tags: arduino-uno, programming, i2c
---


# Question
Title: How can I communicate from Arduino to MATLAB
I want to use sensors on an Arduino to control values in a MATLAB program. What are my options for communicating?

I've used Processing to receive data sent via the serial cable, and that strategy has worked pretty well. Is there something similar I can do using MATLAB? I'm somewhat new to MATLAB, so gentle guidance would be great.

I'm not really looking for something like the ArduinoIO package -- I want to have separate computation executing on the Arduino and occasionally informing my MATLAB program (which will occasionally poll the serial line, I suppose).

# Answer
> 5 votes
MATLAB Support Package for Arduino (aka ArduinoIO Package) allows you to do it fairly easily.

> Sample usage:
>
> %-- connect to the board
>
> `a = arduino('COM9')`
>
> %-- specify pin mode
>
> `a.pinMode(4,'input');`
>
> `a.pinMode(13,'output');`
>
> %-- digital i/o
>
> `a.digitalRead(4) % read pin 4`
>
> `a.digitalWrite(13,0) % write 0 to pin 13`
>
> %-- analog i/o
>
> `a.analogRead(5) % read analog pin 5`
>
> `a.analogWrite(9, 155) % write 155 to analog pin 9`

# Answer
> 3 votes
I don't know a whole lot about MATLAB, but I found some tutorials about reading and writing from the serial port:

```
s = serial('COM1');
fopen(s)
fprintf(s, 'Your serial data goes here')
out = fscanf(s)

```

`out` is now your received data, and you can do whatever you want with it.

To close:

```
fclose(s)
delete(s)
clear s

```

It is from *Writing and Reading Data* (*MATLAB*/ *Data and File Management*/ *Serial Port Devices*).

From your question I assume you know about the Arduino side of things (using `Serial`).

# Answer
> 0 votes
I've established a connection, sending numbers. By just changing Serial.write to Serial.print and fread to fscanf you can send/receive clear ASCII text instead of binary data.

Both matlab and arduino code can be found at this question:

https://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously

# Answer
> -1 votes
clc clear all global value global value1 global val5 global val6 global val7 global val8 global val9 a=arduino('COM4'); value = zeros(); value1 = zeros(); val5 = zeros(); val6 = zeros(); val7 = zeros(); val8 = zeros(); val9 = zeros(); for i=1:1000

val1(i)=analogRead(a,0)/2; %incomming

val2(i)=analogRead(a,1)/2; %heater

val3(i)=analogRead(a,2)/2; %heat sink

val4(i)=analogRead(a,5)/2; %atmsphr

val8(i)=analogRead(a,6)/2; %pressure

val9(i)=analogRead(a,7)/2; %pressure

val(i)=analogRead(a,0)/2;

value(i)= (val1(i)+val4(i)+val3(i))/3;

value1(i) =(val8(i)-val9(i)); %pressure

val5(i)=analogRead(a,0)/2 %incoming

val6(i)=analogRead(a,4)/2 %outgoing

val7(i) = value(i)-val6(i) plot(value, 'r'); title('heat sink temprature');

```
hold on

plot(val5, 'k');

title('incoming air temprature');
plot(val6, 'g');

title('outgoing air temprature');

 plot(val4, 'k');
 title('atmospheric temperature');

plot(val7,  'c');
title('change in temprature');

pause(6)

figure
plot(value1,  'r');
title('change in pressure');

pause(6)

```

end

---
Tags: serial, matlab
---


# Question
Title: Question regarding powering Arduino through the USB Port
If powering the Arduino (Mega) through the USB port, is a voltage of 5.19VDC acceptable?

# Answer
Yes, the ATMEGA328 processor will work without any problem, in fact if you go in the power informations section on the datasheet, you will find that the processor can run from a little less of 3V to a maximum of 5.5V.

Just be careful, because *the processor* works at that power, but *the board* will need from 5 to 5.5V.
> 1 votes

# Answer
That's the approximate expected voltage. The Arduino devices are typically powered at 5V, but the chips themselves are rated to work at values lower and higher than 5V.
> 0 votes

# Answer
The 5.19V you see, I guess you expect 5.00V, is a combination of power supply tolerance and the tolerance of your voltmeter.

Your voltmeter also has some error, we tend to forget that sometimes.
> 0 votes

---
Tags: arduino-mega, power, usb
---


title: Wifi module for arduino shield

text:
# Question
Title: Wifi module for arduino shield
Recently I bought a B006RATC2E wireless shield for my Arduino One, but didn't notice that I had to buy a wifi module as well to let it work (bad surprise as the shield already cost me $30 + travel expenses to CR). Could someone be so kind to suggest me some compatible wifi modules for the shield?

I'm kind of newbie in this and when I search specs for Adafruit and XBee modules, the documentation is not explicit about the compatibility with Arduino shields, so I'm stuck.

I don't want to buy components that would't work together (my budget is limited). Is XBee XB24 a good module for the shield? Any other alternative?

Thanks in advance for any help!

# Answer
> 2 votes
Wireless doesn't necessarily mean it's WiFi. You should get an XBee module that explicitly states that it's a WiFi module.

For a cheaper alternative you can check ESP8266 WiFi modules, which you can get for $5.

---
Tags: arduino-uno, shields, wifi
---


# Question
Title: Is it possible to use two encoders with Arduino Uno?
I would like to control 2 motors with the Arduino Uno board, which provides only two interrupt pins on digital 2 and 3.

I've set one encoder using these pins, and it works. What do you think about the following approaches:

* Timer Interrupt:

Create a Timer Interrupt. Connect the seconder encoder to an analog pin. Set an analog read function in the interrupt service routine. Change the prescaler of the ADC and increase the acquisition time.

* PinChangeInt

Use PinChangeInt to capture the pin change interrupt rather than an external interrupt.

> This should allow you to use almost any I/O pins on the Uno for the encoder.
>
> as Ignacio Vazquez-Abrams suggested here

# Answer
> 1 votes
It is very possible. use a separate interrupt pin for Phase A of both motors, then read phase B from a non interrupt pin in the interrupt handler. http://www.spiked3.com/?p=5501

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


# Question
Title: How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?
How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?

# Answer
> 6 votes
Android devices usually don't have a USB host: they expect to be connected to some smarter device like your computer. Same goes with Arduino. For this reason Arduino made the Mega ADK (that means Accessory Development Kit).

Mega ADK and Due act as USB hosts and can be connected directly to your Android phone. If you already have a board, another option is to get a USB host shield to add USB host capababilities.

Your sketch will tell the phone what kind of accessory application it is and your phone will download the appropriate application from the store.

There is a book about connecting Arduino to Android.

# Answer
> 3 votes
## You never mentioned your tablet model... or Arduino model

There are some tablets designed to work with USB flash drives and printers. This is called OTG (on the go.

**You need:**

* A tablet supporting OTG
* An OTG adapter that fits into your tablets USB slot and is compatible
* The Arduino Uno Communicator App
* Arduino Uno (or clone) \[Note: It says that it works with Atmega16U2 or Atmega8U2 programmed as a USB-to-serial converter so I would assume that that would cover a few boards more than the Uno.)

Another alternitive is to look into Bluetooth (Note: I just picked a random link but there are hundreds of similar BT adapters)

# Answer
> 2 votes
The USB protocol requires one end to be a "host" and the other end to be a "peripheral", and it doesn't work if the devices at both ends of the cable are "peripherals". Alas, most Arduinos and many early Android devices are "peripherals", so connecting such devices with a standard USB cable doesn't work.

Some modern Android devices support "OTG", so in theory one could make the Android end of the cable the "host". Has anyone gotten this to work?

Another approach is to somehow make the Arduino end of the cable the "host", and the Android end of the cable the "peripheral". That's the approach taken by

* Microbridge (a) (b)
* The IOIO board (a) (b)
* The Android Accessory Development Kit (ADK) (a) (b) (c)

(The Amarino (a) and Cellbots (a) (b) take yet another completely different approach).

# Answer
> 2 votes
Processing is a great place to get started with device to device communication.

The interface and language are very similar to Arduino and there are many examples to get you started.

http://playground.arduino.cc/Interfacing/Processing

# Answer
> 0 votes
You can connect Android and Arduino with usb and use the easy tool App inventor 2 for android

Did you try this new application : https://play.google.com/store/apps/details?id=bp.usbbridge.appinvDemo and full version : https://play.google.com/store/apps/details?id=bp.usbbridge.appinv

Find Videos about Explications : USB OTG Bridge Serial UART for APP Inventor 2 and ARDUBLOCK on youtube

---
Tags: android
---


# Question
Title: How to connect Android phone to Arduino?
Is it possible to connect an Arduino to an Android Phone and use it for input/output? Are connections possible over USB? Or do I need to have a wifi or Bluetooth shield?

# Answer
You bet it's possible. I used a pretty cheap bluetooth module that I got from Amazon, and wrote an app using the information on the official Android Developers page to connect to the Arduino. There are many guides online telling you how to hook up a module to the pins of the duino.

You can probably get a cheaper module if you look on eBay and don't care how long it takes to arrive, and I think there's at least one app on the Play store for controlling an Arduino if you can make it work for your purpose.

USB connections are probably possible, though I haven't done any of that.
> 3 votes

# Answer
The Arduino ADK is meant for that. It combines an Arduino Mega with a USB host chip and port. If you don't want to buy a full Arduino, you can buy a USB host shield. Excellent tutorial for it here.

What those do is convert high speed USB signals to SPI, which is readable by a microcontroller. Android has libraries known as the Accessory Development Protocol, which can bridge communication from a phone to the USB and then to a microcontroller.
> 1 votes

# Answer
I already had this answer typed up on another question so I thought I'd post it here to help you. I've replaced "tablet" with "phone" for easy reading.

> ## You never mentioned your phone model... or Arduino model
>
> There are some phones designed to work with USB flash drives and printers. This is called OTG (on the go.
>
> **You need:**
>
> * A phone supporting OTG
> * An OTG adapter that fits into your phone's USB slot and is compatible
> * The Arduino Uno Communicator App
> * Arduino Uno (or clone) \[Note: It says that it works with Atmega16U2 or Atmega8U2 programmed as a USB-to-serial converter so I would assume that that would cover a few boards more than the Uno.)
>
> Another alternitive is to look into Bluetooth (Note: I just picked a random link but there are hundreds of similar BT adapters)

*From my answer on a similar question*
> 1 votes

# Answer
You can connect Android and Arduino with usb and use the easy tool App inventor 2 for android

Did you try this new application : https://play.google.com/store/apps/details?id=bp.usbbridge.appinvDemo and full version : https://play.google.com/store/apps/details?id=bp.usbbridge.appinv

Find Videos about Explications : USB OTG Bridge Serial UART for APP Inventor 2 and ARDUBLOCK on youtube
> 1 votes

---
Tags: serial, android
---


# Question
Title: Can I damage an arduino by setting pins high with no load
I have an Arduino project that has 15 different output pins set. Some are currently attached to devices and others are not. Will testing my program cause a problem / damage if it sets pints to HIGH that do not have anything connected to them?

# Answer
Nope, you should be just fine.

Having a pin set to any state while unplugged will not cause any problems with your microcontroller.
> 8 votes

---
Tags: pins
---


# Question
Title: RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?
I'm trying to implement a card reader (i.e. credit cards) for shopping purposes, and AFAIK those cards are ISO 14443-A compliant (Mifare Classic 1K). I already made an Android app that can send custom APDU to read specific sectors by using raw SendBytes().

Since I need to build a circuit with a custom antenna, I chose Arduino-uno with a NFC module (was thinking about StrongLink SL013), I wanted to know if it's possible to send raw bytes and receive the response from the tag. I only found some higher-level implementation (readSector, writeSector and so on).

# Answer
> 1 votes
RFID protocols require either passive or active tags. Depending on which you use, either the tag or reader regularly transmits pulses. Check www.rfidreader.com for more info. https://www.rfidjournal.com provides valuable resources as well.

Many companies invest heavily in developing RFID technology. You would be well advised not to reinvent wheels without reeeeally deeeeeep pockets.

# Answer
> 1 votes
This would differ per device/reader. Currently, I'm in a project with a TRF7970a RFID reader. I've seen it it's datasheet that it does have options to send RAW values as it does not support every protocol (NXP has patent on one?) thus the chip doesn,t parse it, but can send it to the mcu completely. In short, yes this is possible. But using a reader that is compliant with your protocol might supress your development cost/time

---
Tags: arduino-uno, rf, rfid
---


# Question
Title: Using arduino mega with linear encoder to control movement of dispenser
My goal is to deliver very small quantities (100 microliters) of fluid to the (approximate) center of a 25mm x 75mm surface. My first idea was to repurpose an old inkjet printer for the project. I thought I'd load the fluid dispensers (probably 3ml syringes) into the unit where the ink cartridges would go and use an arduino to manipulate the linear encoder used by the printer to tell the dispenser unit where to go.

Main problem at the moment is that I'm having trouble getting the dispenser unit to go exactly where I want it to. I've tried incorporating the PID library into my code to get the head to oscillate around the desired position until it stops at the right location. However the oscillation never stops and the head always moves beyond the desired position.

I'm trying to figure out the easiest way to get this done. Maybe that'll mean moving away from using the inkjet printer but I'd like to get some feedback here before I make any decisions.

Code:

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
#include <PID_v1.h>

//
//// Interrupt information
//// Int 0 on pin 2
//// Int 1 on pin 3 Not used
//
#define encoderI 2  // Interrupt 0 is use
#define encoderQ 4 // Only use one interrupt in this example
#define maxPos   3733 // left hand side
#define minPos   0    // right hand side
#define maxSpeed 150
#define minSpeed 0
#define Freq     1600
#define maxWait  500 //12 millisec before stopping the motor
#define maxPositionError 10 //max error from actual desired position. It is approximately 0.032 of an inch
#define PIDsampleTime 25

//
//// Tuning parameters
double kP=0.37; //Initial Proportional Gain
double kI=2; //Initial Integral Gain
double kD=0.020; //Initial Differential Gain
double Drive = 0;

int outputSign;
//
double Setpoint, Input, Output;

PID myPID(&Input, &Output, &Setpoint,kP,kI,kD, DIRECT);

volatile int ActualHeadPosition; //current position will be modified with each interrupt
volatile int PreviousHeadPosition; //Previous position will be modified with each interrupt
volatile uint8_t Speed = maxSpeed;                      //Speed for the dispenser head
volatile unsigned long lastPositionTime;
volatile int setPoint;
volatile int Err;
volatile int lastError;
volatile int Integral;

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
//
//// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *dispenserDCMotor = AFMS.getMotor(1);
//
void setup() {
     Serial.begin(9600);           // set up Serial library at 9600 bps also this is the baud rate per second for the input?
     pinMode(encoderI, INPUT); //pin #2 is assigned as an input
     pinMode(encoderQ, INPUT);
     attachInterrupt(0, handleEncoder, CHANGE);
//
     AFMS.begin(Freq);
//
//    // Set the speed to start, from 0 (off) to 255 (max speed)
    dispenserDCMotor->setSpeed(Speed);
    dispenserDCMotor->run(FORWARD);
//    // turn on motor
    dispenserDCMotor->run(RELEASE);
//
  Setpoint = 1800;
  myPID.SetSampleTime(PIDsampleTime);
  myPID.SetOutputLimits(minSpeed, maxSpeed);

    //turn the PID on
    myPID.SetMode(AUTOMATIC);

     //Initialize procedure should be the first thing
    Initialize();
}

void loop() {
  Serial.print(", ActualHeadPosition: ");Serial.print(ActualHeadPosition);Serial.print(", SetPoint: ");Serial.println(setPoint);

  setPoint = 1800;
  Input = ActualHeadPosition;
  outputSign = myPID.Compute();
  Err = setPoint - ActualHeadPosition;
  Serial.print("PID Output");Serial.print(Output);Serial.print(" Error: ");Serial.println(Err);
  Speed = Output;
  if (Err > 0){
    moveLeft();
    Serial.println("moveLeft");
  }
   else if (Err < 0){
     moveRight();
     Serial.println("moveRight");
  }

};
//
void handleEncoder(){
  lastPositionTime = millis();
   PreviousHeadPosition = ActualHeadPosition;
   if(digitalRead(encoderI) == digitalRead(encoderQ)){
     //dispenser is moving to the left
     ActualHeadPosition++;
   }
   else {
     //dispenser is moving to the right
     ActualHeadPosition--;
}

 }

void moveLeft(){
  uint8_t i;
  dispenserDCMotor->run(FORWARD);
  dispenserDCMotor->setSpeed(Speed);
}

void moveRight(){
  uint8_t i;

  dispenserDCMotor->run(BACKWARD);
  dispenserDCMotor->setSpeed(Speed);
}

boolean isMotorMoving(){
  if (((millis() - lastPositionTime) > maxWait))
    return false;
  else
    return true;
}

void Initialize(){
    //Move to origin
    moveRight();
    while (isMotorMoving()){
  //    Serial.println("MOVING!");
  delay(10);
    }
    ActualHeadPosition = 0;
    PreviousHeadPosition = 0;
    dispenserDCMotor->setSpeed(0);
    dispenserDCMotor->run(RELEASE);

}

```

# Answer
The easiest option, using the code you have, is to spend a little time tuning the PID algorithm. The lines you are interested in are these

```
double kP=0.37; //Initial Proportional Gain
double kI=2; //Initial Integral Gain
double kD=0.020; //Initial Differential Gain

```

PID takes a setpoint and a current location, calculates error, and uses it to make a new output that should sent the location to the setpoint. It does this by adding

P\*(error)+I\*(all historic error added together)+D\*(recent change in error)

By changing the multipliers P, I, and D, you change how it reacts to different situations. In your system, the D value will have very little effect (at least in my experience). You should probably keep that where it is, or even just set it to 0.

The P value controls direct response to error, and should be the main component in your setup. Try increasing this to make it move faster, and mildly decrease the oscillations.

The I value controls how much all historic error affects output. It is the factor leading to all the oscillations. Lowering it will make your output settle sooner. It also assists when fighting other constant forces, or if static friction keeps the head locked in one position too close for the P term to overpower. My guess is in your isolated and low friction system, it should be very low.

Increment these values slowly (.05 at a time maybe) and experiment, you should be able to fix your oscillations and make the system behave how you want.
> 1 votes

# Answer
The reason why your slide/microarray microdispenser continually oscillates about a point rather than dispense the fluid containing your cells/DNA sample specifically at a particular specified/designated point on your slide/microarray is due to your code below:

```
if(digitalRead(encoderI) == digitalRead(encoderQ)){
     //dispenser is moving to the left
     ActualHeadPosition++;
   }

   else {
     //dispenser is moving to the right
     ActualHeadPosition--;
}

```

which tells the Arduino to actuate the motor regardless of the values stored in the vars encoderI & encoderQ.
> 0 votes

---
Tags: arduino-mega, pid
---


# Question
Title: Is it problematic to 'check an input pin' or 'set an output pin' each step?
I am using an Arduino in an automation project which will be using a state machine to conduct a one-hour scenario. Currently, the Arduino reads each input pin, runs its state update script, then sets each update pin. 99.99% of the time, each output pin will be set to the same state that it had in the last step. Although it is better (in my opinion) to only set the pin when a setting changes, I was wondering if constantly checking and setting pins would have a big negative impact on the hardware?

Would checking a pin's current state (digitalRead or other method) before setting the pin improve anything?

# Answer
It does not hurt the Arduino to set an output pin to high if it was already set to high. If you are concerned about performance, it is more efficient to just set the output pin compared to reading the pin and then setting it only if it's different
> 4 votes

# Answer
> Would checking a pin's current state (digitalRead or other method) before setting the pin improve anything?

So instead of:

```
SetPin(OUTPUTPIN,true);

```

You want to do:

```
if(!PinIsSet(OUTPUTPIN)){
 SetPin(OUTPUTPIN,true):
}

```

To avoid writing to a pin (making it high) when it's already high/enabled?

Well doing so will waste a little amount of your programs' speed (it'll need to check each pin before setting it). But when you set a pin, when it's already high, it simply doesn't even change. And even then it's not required to check it first, Microcontrollers are basically made for this.
> 1 votes

---
Tags: pins
---


title: Which Microcontroller to use

text:
# Question
Title: Which Microcontroller to use
I want to use a wifi shield, as well as a 2.8 inch touch LCD shield; both would fit the arduino uno V3 nicely. Is that the best microcontroller to use

# Answer
> 1 votes
To answer your first question, regarding stacking a WiFi Arduino Shield on top of a LCD Shield:

> can I stack them simultaneously

The obvious answer is - **it depends on the shields**. Each shield might use a different set of Arduino I/O pins, making them unavailable to the next shield stacked on top of it.

for example, this formal Arduino WiFi shield makes **I/O pins 10, 11, 12, 13 and 7** (on Arduino Uno) unavailable to the next top shield.

Unfortunately, this LCD KeyPad shield needs pins 7 and 10 available (among others) in order to function properly. This makes it incompatible for stacking on top of the WiFi shield mentioned above (or vice versa).

It doesn't mean that there is no way that **any** LCD shield could be stacked on top of a WiFi shield, but to be honest, I couldn't easily find any LCD shield that won't collide with a WiFI shield pins. You might want to change approach and send the WiFi data using the built-in Serial to a computer.

> Is that the best microcontroller to use

If there would have been a manifest to this website, I'm sure that "The best product is the one that meet your needs best" would be it's first sentence. In order for someone with experience to answer what is best, (s)he would need to know your exact needs. Since you are still not sure what they are, and just want to play around a bit, I imagine that the classic Arduino Uno R3 could help you find your way, especially if you are doing your first steps with Arduino.

# Answer
> 0 votes
I'll have to chime in with the others and say "It depends." The Uno, or more precisely its Atmega328p microcontroller, is rather memory limited, especially the RAM memory needed for data buffers, stack-frames, and tables such as the character-generator for the LCD. That last one can usually be kept in program memory, but note that if you're having to plan memory assignment before you even start the project, it's a pretty good sign that you should consider something more capable.

An Arduino Mega 2560 is about twice the price of the Uno (in the US, US$50 vs. US$25) but gives you 4 times the RAM memory, 8 times the flash (program) memory, and a bunch more (sorry to get all technical :) I/O pins. Of these, the RAM is likely to be your most stringent limit with the UNO.

I keep one Arduino Mega around for prototyping or when don't want to build another board for an experiment, and a handful of AtMega328p chips to build into "Arduin-ettes" for my more permanent gadgets. Most of my toys will fit on the '328 chip but it's awfully nice to be able to shove a ton of code, libraries, debugging statements, logging buffers and what have you, into the larger processor without having to think about what will fit. Or, what's worse, if I cause a stack crash by stuffing all of that into too-little memory, I could waste a lot of time debugging a presumed coding error when it was really an out-of-memory problem.

---
Tags: shields, wifi, lcd, sd-card
---


# Question
Title: How to read info from an Xbee Pro S2B to an Arduino with a Xbee Pro S2B
I am using two XBee Pro S2B modules. One (Router) connected to the laptop via a UART cable. The other (Coordinator) connected to an Arduino Mega with the sketch below. All I need it to do is turn a LED on and off and display the status in the IDE serial monitor. I am using Arduino IDE (v1.6.0).

Arduino sketch:

```
#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (Serial.available())
    {
         int myData = Serial.read();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData, DEC);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData, DEC);
         }
     }
 }

```

Where did I go wrong?

# Answer
You have two serial connections. One for the main USB of the board and one for the XBee.

So you need to read from the XBee and write to the serial USB?

I don't know what speed you have configured for your XBee so I have set it to 9600.

This example reads from the XBee and writes to the Serial/USB port

```
#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (xbee.available())
    {

         int myData = xbee.read();

         Serial.print("Data has arrived on the Arduino");
         Serial.write(myData);
         Serial.println();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData);
         }
     }
 }

```

Note: Your example also used `Serial.write()` with the wrong argument `DEC` which applies to `Serial.print()`. X-CTU and Arduino both send ascii which is also what the `Serial.print()` does. However the `Serial.read()` just reads the byte so we need to use `Serial.write()` to send the same bytes back to the other end.

You can also make life a bit easier by replacing `xbee.available()` with `Serial.available()`. Then use the Arduino IDE serial monitor to both send and receive. This means that you just use the one USB connection to prove the code.
> 1 votes

---
Tags: serial, xbee, softwareserial
---


title: millis() function with a button press

text:
# Question
Title: millis() function with a button press
I am trying to use the `millis()` function to turn on a pin for a specified interval then turn off and turn on a second pin. It is intended to power a relay and offer a visual cue to when the cycle is over. Several of these need to eventually be running, most likely three, so using `delay()` won't work. I plan to add additional "button pins" for each input. The LED lights up but gets stuck in the loop and doesn't cycle out. It seemed like a simple program but I can't crack it for some reason.

Is there a much better method to do this? There will be two optical sensors and one pushbutton switch attached to an air driven crushing machine. The two optical sensors will be used only as time indicators with LEDs and the pushbutton will power the relay. Forgive my shortcomings as a programmer, I am learning the programming language still.

```
const int ledPin =  2;      // the number of the LED pin
const int buttonPin = 3;    // Button pin number
// Variables will change:
long previousMillis = 0;        // will store last time LED was updated
int buttonState = 0;            // Checks if button is pushed
int buttonPush = 0;             // Toggles between 0 to hold state
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
// set the digital pin as output:
   pinMode(ledPin, OUTPUT);
   pinMode(buttonPin, INPUT);
}
void loop()
{
   unsigned long currentMillis = millis();
   buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH) {
      buttonPush = 1;
      if (buttonPush == 1){
         if(currentMillis - previousMillis > interval) {
            previousMillis = millis();
            digitalWrite(ledPin, HIGH);
         }
         else {
            buttonPush = 0;
         }
      }
      else {
         digitalWrite(ledPin, LOW);
      }
   }
}

```

Edit: Thank you for looking over the code, you guys are awesome. There were a couple questions regarding clarity of the final application so I will elaborate. I am going to attempt to clean it up. I had a feeling something was wrong with:

```
if (buttonState == HIGH) {
   buttonPush = 1;

```

but I couldn't put my finger on it.

Eventually the system will function with two heating elements to soften plastic, which I will either add an optical sensor to since it will probably get triggered a few hundred times a day, or just a pushbutton to start a timer so the plastic isn't left in too long. A green LED will be illuminated to indicate the system is on. When the plastic object is placed in the heating element it triggers the optical sensor (or the operator pushes a pushbutton to start the timer) that will then illuminate a red LED to indicate heating. When the specified time interval has expired, the LED will revert back to green to show the cycle is complete. The plastic object is then removed and placed in a pneumatic crushing device with a green system on LED. The operator then pushes a pushbutton which turns on a red indicator LED and a relay to power the solenoid on the pneumatic press for a specified amount of time to allow the plastic to cool and crystallise. When that interval has expired, the system will revert back to illuminating the green LED and will end power to the relay allowing the press to release.

The pneumatic press and the heating system works awesome, I just need better control of the time intervals used. The end result needs to be consistent.

I am going to try all suggestions and will post what ended up working if I reach that point or find an answer that functions.

# Answer
Some code is shown below to illustrate a method for treating three events independently.

This code might not be completely applicable as-is, because the problem description isn't clear about what should happen when a button is pressed and about whether other events to be added to the code are like the one shown there now. However, if you understand how it works you probably can adjust it to meet any special requirements of your application.

During each pass through the `loop()` routine, the code does the following for each type of event:

> If the event is not currently active (as denoted by `states[i] < debounced`), the code checks whether the event's button has been pressed (or, if its sensor has turned on). If so, the code increments a debounce counter. If the event's counter gets up to `debounced`, then the output for the event is turned on, and the event's end-time is stored in an array entry.
>
> If the event *is* currently active (as denoted by `states[i] >= debounced`), the code tests if the event's end-time has arrived; if so, it turns off the event's output bit and resets its state to 0.

The last statement in `loop()` busy-waits until `milliseconds()` returns a different value than before. This is done so that switch-debouncing samples are taken at least a millisecond apart. If your inputs don't need debouncing, you can remove debounce code .

```
/* Process three asynchronous activities: Upon a given input going
true, activate its associated output(s) for specified lengths of time.
*/

enum { nkinds=3, debounced=5 }; // # of activity kinds;  debounce-criterion
const byte outPins[nkinds] = {2, 4, 6}; // Output pin numbers
const byte inPins[nkinds]  = {3, 5, 7}; // Input pin numbers
const unsigned int actLens[nkinds] = {345, 678, 323}; // Activity lengths, ms
byte states[nkinds] = {0, 0, 0};
unsigned long actEnds[nkinds] = {0, 0, 0};

void setup() {
// Set input/output modes of pins
  for (byte i=0; i<nkinds; ++i) {
    pinMode(outPins[i], OUTPUT);
    pinMode(inPins[i], INPUT);
  }
}

// Once per millisecond, for each kind of activity
// check for new beginning or deal with ongoing action
void loop() {
  unsigned long now = millis();
  for (byte i=0; i<nkinds; ++i) {
    if (states[i] < debounced) {  // Is activity off?
      // It's off, look for a turnon
      if (digitalRead(inPins[i])) {
        ++states[i];        // Button is closed at the moment
        // See if button has been debounced
        if (states[i] >= debounced) { // If so, start its action
          digitalWrite(outPins[i], HIGH);
          actEnds[i] = now + actLens[i];
        }
      }
      else {
        states[i] = 0;      // Button is not closed at moment
      }
    }
    else { // It's on, see if end-time has arrived
      if (now >= actEnds[i]) {
        digitalWrite(outPins[i], LOW); // Clear output when done
        states[i] = 0;        // Return to button-seeking state
      }
    }
  }
  while (now == millis()) {};       // Finish current millisecond
}

```

The code above compiles ok in the Arduino IDE but I haven't tested it on an Arduino device.

Note, larger systems with numerous events will use priority queues to implement lower-overhead versions of the same ideas.
> 2 votes

# Answer
Summary:

A fatal problem is caused by the two lines of code below.
A variable is set and then the same variable is immediately tested to see if it is set. This means that the IF test always passes and the ELSE never happens. As the LED is cleared only when the else occurs, the LED stays lit.

Code:

> ```
>   buttonPush = 1;
>   if (buttonPush == 1){ ...
>
> ```

When the button is pressed you set buttonPush and then immediately test to see if it is set.

As it always is set, the LED never gets turned off as the "else" condition is never met.

Even when that is fixed you have other issues.
I suggest that "expanding" the code along the lines I have shown in (3) below will help you immensely with visualising what your code does.

There are a large number of editors which handle this task in various ways, but just plain tabbing and white space with a basic editor helps muchly.

---

It seems almost certain that your code will NOT do what you intend when it does work "properly", but there are several issues below that need addressing (one fatal, others less so) - see "ISSUES" below.

Apart from those issues, it's not 100% clear how this is intended to be used.
Options include:

* Switch is pressed and released quickly (say 100 mS) - LED lights for one second and then goes out.
* Switch is pressed and held - LED lights for one second then turns off even when switch is held on.
* Other variants are possible.

At present it will not do any of these.

---

## ISSUES:

(1) You have assigned

> long previousMillis = 0;

This should be

> unsigned long previousMillis = 0;

Mixing the two types gives an uncertain result. At best, an error will occur when the value returned by millis() exceeds the length of a "long" data type and when types are mixed there is no guarantee that the result will be valid.

---

(2) I have not checked it, but I'd be wary of the line

> if(currentMillis - previousMillis \> interval)

as it depend on operator precedence of the "-" being implemented prior to the "\>" comparison.
ie this could potentially evaluate as either

" (A-B) \> C " .... which is what you intend,
or
" A - (B \> C) " .... which, while it is not what is intended, does have a valid if not useful result.

You can rely on operator precedence if you have confidence in yourself and the system or make it explicit as in eg

> if( (currentMillis - previousMillis) \> interval)

---

**Making things easier for yourself:**

This has been edited to match my main conclusion which was already covered above (the problem was not nesting but a test that can never fail - as covered above) but the formatting comments are relevant.

Your code is written in a standard (or usual) manner. Some are able to handle such without problem, but I (and many others) find such layout hard to read and, importantly, easy to bury errors in. The following is overdone - I used existing tabs and expanded it in Word :-) - but to me the following makes it immensely more readable. Layout and style are a matter of personal preference, and there are many opinions re what is "best", but something which allows ease of visualisation of program structure is liable to be useful.

The two adjacent lines

> ```
>   buttonPush = 1;
>   if (buttonPush == 1){ ...
>
> ```

are logically grouped together when indented like this at make it clearer that the "set then test" arrangement can never fail so the subsequent "else" where the LED is turned off is never implemented. So the LED must stay on.

buttonPush = 0; is bolded for unrelated reasons.
> 0 votes

# Answer
The direct answer to your first question (LED gets stuck) after formatting and summarizing a section of your code:

```
  buttonPush = 1;
  if (buttonPush == 1){
     ...
  }
  else {
     digitalWrite(ledPin, LOW);
  }

```

is that there's a logic error. You can see that the else clause, turning off the LED, will never be executed because buttonPush is always 1 before you enter this section. I think this is the point @RussellMcMahon was trying to make.

The answer to your second question, needing several of these running at once, is: Get the first one to work first. Then simplify it as much as you can. Then you can choose between using polling loop (repeatedly reading the clock and deciding whether it's time to do something) or setting interrupts (making the clock interrupt your main program to run the routine that does the "something").
> 0 votes

# Answer
The simplest way I can think of is something like this:

```
unsigned long lastPress = 0;
unsigned long stateOneTime = 2000; //runs until two seconds elapse
unsigned long stateTwoTime = 4000; //runs after state one until 4 seconds from first press
...
if(/*input is active*/) lastPress = millis();
...
if(millis() - lastPress < stateOneTime){
    //set output for first state
    //active for 2 seconds
} else if (millis() - lastPress < stateTwoTime){
    //set output for second state
    //active an additional 2 seconds
} else {
    //set output to the "off" state
}

```

Many improvments could be made, like going more of a state machine route (separating the time checks from the branches) or paramaterizing the state lengths better (durations would make more sense than total time from start, but be slightly more complicated to code).

I think the key to making your life easier while working on this code will be separating the input segment from the output segment. It will help keep the code easy to read and modular.
> 0 votes

---
Tags: millis
---


# Question
Title: How to compile and upload the specific (.cpp + .h) code?
I have a specific arduino code (no .ino files) https://github.com/justintconroy/MdbBillValidator , which can't be opened by arduino IDE. How can I make & upload this code? I have an arduino 2560 mega.

I've created an empty `MdbBillValidator.ino` file and added these lines:

```
#include "MdbBillValidator.h"

void setup() {

}

void loop() {

}

```

Here is the error message

```
MdbSerial.cpp: In function ‘void __vector_37()’:
MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_52()’:
MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_55()’:
MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: At global scope:
MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
MdbSerial.cpp:554:189: note: candidates are:
MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
In file included from MdbSerial.cpp:38:0:
MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

```

# Answer
The problem is that I need to import this code just a simple usual library.
> 0 votes

---
Tags: arduino-mega, arduino-ide, compile
---


title: mega include a library

text:
# Question
Title: mega include a library
This question is a little related to this one: How to compile and upload the specific (.cpp + .h) code?

I've installed MdbBillValidator to my arduino libraries collection. I tried both on ubuntu & windows.

How can I include it? Default inclusion, by arduino ide, was:

```
#include <MdbSerial.h>
#include <wiring_private.h>
#include <MdbBillValidator.h>
#include <MdbMaster.h>
#include <Arduino.h>

void loop() {

}

void setup() {

}

```

And here is error comes in:

```
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_37()’:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
       UCSR1B |= (1 << TXB8);
                       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
       UCSR1B &= ~(1 << TXB8);
                        ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_52()’:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
       UCSR2B |= (1 << TXB8);
                       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
       UCSR2B &= ~(1 << TXB8);
                        ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_55()’:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
       UCSR3B |= (1 << TXB8);
                       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
       UCSR3B &= ~(1 << TXB8);
                        ^
In file included from /usr/lib/avr/include/avr/iom2560.h:38:0,
                 from /usr/lib/avr/include/avr/io.h:160,
                 from /usr/lib/avr/include/avr/pgmspace.h:88,
                 from /home/asiniy/sketchbook/libraries/MdbBillValidator/Arduino.h:8,
                 from /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:31:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: At global scope:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
   MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);
                                                                                ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
   MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);
                                                                                ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:189: note: candidates are:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
 MdbSerial::MdbSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
 ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
In file included from /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:38:0:
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
 class MdbSerial
       ^
/home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

```

What I need to do to avoid this error and get the code worked?

# Answer
Could you try adding this to your program?

```
#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)

```

I found someone with similar code, who had these defines and as your code seems to miss/cannot find something, this might fix it. Though I'm not sure if these defines apply in your specific implementation. For that I should have to see the code where the error is pointing at.
> 1 votes

---
Tags: library
---


# Question
Title: How to send 1 byte from android to arduino
My idea is Arduino sensor will read and pass the values read on android. Then android will calculate and send the control value (PWM) to the Arduino. but android can only get the value from the Arduino but can not send them back to the Arduino ... Can someone please help? This my code:

java code:

+MainActivity

```
package com.example.tut1;

import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.example.tut1.Bluetooth;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphView.LegendAlign;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewStyle;
import com.jjoe64.graphview.LineGraphView;

public class MainActivity extends Activity implements View.OnClickListener {

    // private StringBuilder recDataString = new StringBuilder();

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    if (Bluetooth.connectedThread != null) {
        Bluetooth.connectedThread.write("Q");
    }// Stop streaming
    super.onBackPressed();
}

// khai bao bien
String x, x1;
int u,u1,adc,adc1;
public String sensor, sensor1;
static boolean f=false;
// toggle Button
static boolean Lock;// whether lock the x-axis to 0-5
static boolean AutoScrollX;// auto scroll to the last x value
static boolean Stream;// Start or stop streaming
// Button init
Button bXminus;
Button bXplus;
Button bConnect, bDisconnect;
Button bStart,bStop;
TextView tvBluetooth, tvpid;
ToggleButton tbLock;
ToggleButton tbScroll;
ToggleButton tbStream;
// GraphView init
static LinearLayout GraphView, GraphView1;
static GraphView graphView, graphView1;
static GraphViewSeries Series, Series1;
// graph value
private static double graph2LastXValue = 0, graph2LastXValue1 = 0;
private static int Xview = 10, Xview1 = 10;

// khai bao bien timer
final Handler thandler = new Handler();
Timer t = new Timer();
TimerTask mTimerTask;

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch (msg.what) {
        case Bluetooth.SUCCESS_CONNECT:
            Bluetooth.connectedThread = new Bluetooth.ConnectedThread(
                    (BluetoothSocket) msg.obj);
            Toast.makeText(getApplicationContext(), "Connected!", 0).show();
            String s = "successfully connected";
            Bluetooth.connectedThread.start();
            break;
        case Bluetooth.MESSAGE_READ:

            byte[] readBuf = (byte[]) msg.obj;
            String strIncom = new String(readBuf); // create string from
                                                    // bytes array

            // if(strIncom.indexOf('s')==0){
            // strIncom = strIncom.replace("s", "");
            // }
            int a = strIncom.indexOf("c");
            int b = 4;
            int c = 4;
            int d = 8;
            sensor = (String) strIncom.subSequence(1, 5);
            sensor1 = (String) strIncom.subSequence(5, 9);
            tvBluetooth.setText(strIncom);
//              Bluetooth.connectedThread.write("E");
//              adc=Integer.parseInt(sensor);
//              adc1=Integer.parseInt(sensor1);
            tvpid.setText(sensor + "-" + sensor1+"-"+u+"-"+u1);
            // String readMessage = (String)msg.obj;
            // recDataString.append(readMessage);
            // sensor = recDataString.substring(0, 4);
            Log.d("strIncom", sensor);
            // if (strIncom.indexOf('.')==2 && strIncom.indexOf('s')==0){
            // strIncom = strIncom.replace("s", "");
            if((strIncom.indexOf("X")==9)&&(strIncom.indexOf("Y")==0)){
            if (isFloatNumber(sensor) && isFloatNumber(sensor1)) {
                Series.appendData(new GraphViewData(graph2LastXValue,
                        Double.parseDouble(sensor)), AutoScrollX);
                Series1.appendData(new GraphViewData(graph2LastXValue1,
                        Double.parseDouble(sensor1)), AutoScrollX);

                // X-axis control
                if (graph2LastXValue >= Xview && Lock == true) {
                    Series.resetData(new GraphViewData[] {});
                    graph2LastXValue = 0;
                } else
                    graph2LastXValue += 0.1;

                if (Lock == true)
                    graphView.setViewPort(0, Xview);
                else
                    graphView.setViewPort(graph2LastXValue - Xview, Xview);

                // grap1
                if (graph2LastXValue1 >= Xview1 && Lock == true) {
                    Series1.resetData(new GraphViewData[] {});
                    graph2LastXValue1 = 0;
                } else
                    graph2LastXValue1 += 0.1;

                if (Lock == true)
                    graphView1.setViewPort(0, Xview1);
                else
                    graphView1.setViewPort(graph2LastXValue1 - Xview1,
                            Xview1);

                // refresh
                GraphView.removeView(graphView);
                GraphView1.removeView(graphView1);
                GraphView.addView(graphView);
                GraphView1.addView(graphView1);
                dieukhienPPM();
                dieukhienPH();
            }
             }
//              if(f)
//              t.schedule(mTimerTask, 60, 60);

//              u = (int) adc/4;
//              u1=(int) adc1/4;
//              f=true;
            break;
        }
    }

    public boolean isFloatNumber(String num) {
        // Log.d("checkfloatNum", num);
        try {
            Double.parseDouble(num);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    requestWindowFeature(Window.FEATURE_NO_TITLE);// Hide title
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);// Hide Status bar
    setContentView(R.layout.activity_main);
    // set background color
    LinearLayout background = (LinearLayout) findViewById(R.id.bg);
    background.setBackgroundColor(Color.BLACK);
    init();
    ButtonInit();
}

void init() {
    Bluetooth.gethandler(mHandler);

    // init graphview
    GraphView = (LinearLayout) findViewById(R.id.Graph);
    // init example series data-------------------
    Series = new GraphViewSeries("Signal", new GraphViewStyle(Color.YELLOW,
            2),// color and thickness of the line
            new GraphViewData[] { new GraphViewData(0, 0) });
    graphView = new LineGraphView(this // context
            , "Graph" // heading
    );
    graphView.setViewPort(0, Xview);
    graphView.setScrollable(true);
    graphView.setScalable(true);
    graphView.setShowLegend(true);
    graphView.setLegendAlign(LegendAlign.BOTTOM);
    graphView.setManualYAxis(true);
    graphView.setManualYAxisBounds(1024, 0);
    graphView.addSeries(Series); // data
    GraphView.addView(graphView);

    GraphView1 = (LinearLayout) findViewById(R.id.Graph1);
    // init example series data-------------------
    Series1 = new GraphViewSeries("Signal", new GraphViewStyle(
            Color.YELLOW, 2),// color and thickness of the line
            new GraphViewData[] { new GraphViewData(0, 0) });
    graphView1 = new LineGraphView(this // context
            , "Graph1" // heading
    );
    graphView1.setViewPort(0, Xview1);
    graphView1.setScrollable(true);
    graphView1.setScalable(true);
    graphView1.setShowLegend(true);
    graphView1.setLegendAlign(LegendAlign.BOTTOM);
    graphView1.setManualYAxis(true);
    graphView1.setManualYAxisBounds(1024, 0);
    graphView1.addSeries(Series1); // data
    GraphView1.addView(graphView1);
}

void ButtonInit() {
    bConnect = (Button) findViewById(R.id.bConnect);
    bConnect.setOnClickListener(this);
    bDisconnect = (Button) findViewById(R.id.bDisconnect);
    bDisconnect.setOnClickListener(this);
    bStart = (Button) findViewById(R.id.bStart);
    bStart.setOnClickListener(this);
    bStop = (Button) findViewById(R.id.bStop);
    bStop.setOnClickListener(this);
    // X-axis control button
    // bXminus = (Button)findViewById(R.id.bXminus);
    // bXminus.setOnClickListener(this);
    // bXplus = (Button)findViewById(R.id.bXplus);
    // bXplus.setOnClickListener(this);
    // //
    // tbLock = (ToggleButton)findViewById(R.id.tbLock);
    // tbLock.setOnClickListener(this);
    // tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
    // tbScroll.setOnClickListener(this);
//      tbStream = (ToggleButton) findViewById(R.id.tbStream);
//      tbStream.setOnClickListener(this);
    tvBluetooth = (TextView) findViewById(R.id.tvBluetooth);
    tvpid = (TextView) findViewById(R.id.tvpid);
    // init toggleButton
    Lock = true;
    AutoScrollX = true;
    Stream = false;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bConnect:
        startActivity(new Intent("android.intent.action.BT1"));
        break;
    case R.id.bDisconnect:
        Bluetooth.disconnect();
        break;
    case R.id.bStart:
        if (Bluetooth.connectedThread != null)
            Bluetooth.connectedThread.write("E");
            doTimerTask();
        break;
    case R.id.bStop:
        if (Bluetooth.connectedThread != null)
            Bluetooth.connectedThread.write("Q");
        stopTask();
        break;
    // case R.id.bXminus:
    // if (Xview>1) Xview--;
    // break;
    // case R.id.bXplus:
    // if (Xview<30) Xview++;
    // break;
    // case R.id.tbLock:
    // if (tbLock.isChecked()){
    // Lock = true;
    // }else{
    // Lock = false;
    // }
    // break;
    // case R.id.tbScroll:
    // if (tbScroll.isChecked()){
    // AutoScrollX = true;
    // }else{
    // AutoScrollX = false;
    // }
    // break;
//      case R.id.tbStream:
//          if (tbStream.isChecked()) {
//              if (Bluetooth.connectedThread != null)
//                  Bluetooth.connectedThread.write("E");
//          } else {
//              if (Bluetooth.connectedThread != null)
//                  Bluetooth.connectedThread.write("Q");
//          }
//          break;
    }
}

public void doTimerTask() {
    mTimerTask = new TimerTask() {
        public void run() {
            thandler.post(new Runnable() {
                public void run() {
                    // TODO Auto-generated method stub
 //                     dieukhienPPM();
//                      dieukhienPH();
                    Bluetooth.connectedThread.write("A");
                    x = Integer.toString(u);
                    Bluetooth.connectedThread.write(x);
                    Bluetooth.connectedThread.write("B");
                    x1=Integer.toString(u1);
                    Bluetooth.connectedThread.write(x1);
                    Bluetooth.connectedThread.write("S");
                }
            });
        }
    };

    // public void schedule (TimerTask task, long delay, long period)
     t.schedule(mTimerTask, 500, 500); // Thoi gian delay va thoi gian lap
    // tinh
    // bang mili giay
}

public void stopTask() {
    if (mTimerTask != null)
        mTimerTask.cancel();
}

public void dieukhienPPM() {
    u= (Integer.parseInt(sensor)/4);
}

public void dieukhienPH() {
    u1 = (Integer.parseInt(sensor1)/4);
}

public static byte[] toByteArray(double value) {
    byte[] bytes = new byte[8];
    ByteBuffer.wrap(bytes).putDouble(value);
    return bytes;
}
}

```

+Bluetooth

```
package com.example.tut1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Bluetooth extends Activity implements OnItemClickListener{

public static void disconnect(){
    if (connectedThread != null) {
        connectedThread.cancel();
        connectedThread = null;
    }
}

public static void gethandler(Handler handler){//Bluetooth handler
    mHandler = handler;
}
static Handler mHandler = new Handler();

static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-           00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    init();
    if (btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }else{
        if (!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }

}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if (devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}

private void init(){
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int a=0;a<pairedDevices.size();a++){
                    if (device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if (btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }
        }

    };

    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if (btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("(Paired)")){

        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
    }else {
        Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    }
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            //connectedThread = new ConnectedThread(mmSocket);
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

static class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    StringBuffer sbb = new StringBuffer();
    public void run() {

        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String income) {

        try {
            mmOutStream.write(income.getBytes());
            for(int i=0;i<income.getBytes().length;i++)
            Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    public void write_1(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
            try{
                Thread.sleep(20);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

}

```

code arduino

```
float nhietdo,doam,nhietdotb,doamtb;
float t,p;
char re;
char p1,p2;
int chanlaynhiet=0;
int pwm,pwm1;
String nhan,nhan1;
boolean batdau = false;
void setup()
{
 Serial.begin(9600);
 pinMode(10,OUTPUT);
 pinMode(11,OUTPUT);
 pinMode(8,OUTPUT);
 }

void loop()
{
if(Serial.available()>0){
 re = Serial.read();
 switch(re){
 case 'S':
 Send();
 digitalWrite(8,LOW);
 break;

  case 'A':
  nhan=Serial.read();
  //digitalWrite(8,LOW);
  break;

  case 'B':
  nhan1=Serial.read();
  //digitalWrite(8,LOW);
   break;

  case 'E' :
  batdau = true;
  break;

  case 'Q':
  batdau = false;
  break;
 }
  if(batdau){
   start();
   }
}

void start()
{
 while(1)
 {//doc ppm
   for(int i=0;i<10;i++)
   {
   nhietdotb=nhietdotb+analogRead(A0);
   delay(1);
   }
   nhietdo=nhietdotb/10;
   nhietdotb=0;
   //doc ph
   for(int j=0;j<10;j++)
   {
  doamtb=doamtb+analogRead(A1);
  delay(1);
   }
  doam=doamtb/10;
  doamtb=0;
 //if (isDigit(pwm1))
 //analogWrite(10,pwm1);
 //if (isDigit(pwm2))
 //analogWrite(11,pwm2);
 analogWrite(11,nhan1.toInt);
 analogWrite(10,nhan.toInt);
 digitalWrite(8,HIGH);

 if(Serial.available()>0)
 return;
}
}

void Send()
 {
  Serial.print('s');
  Serial.print('Y');
   if((nhietdo<1000)&&(nhietdo>=100)){
   Serial.print("0");
   }else if((nhietdo<100)&&(nhietdo>=10)){
   Serial.print("00");
   }else if(nhietdo<10){
   Serial.print("000");
  }
   Serial.print(nhietdo,0);

if((doam<1000)&&(doam>=100)){
  Serial.print("0");
  }else if((doam<100)&&(doam>=10)){
  Serial.print("00");
  }else if(doam<10){
  Serial.print("000");
 }
 Serial.print(doam,0);
 Serial.print('X');
 Serial.print(nhan);
 Serial.print(nhan1);
}

```

# Answer
> 2 votes
Your issue is probably this code (and similar) in the Android MainActivity:

```
x = Integer.toString(u);
Bluetooth.connectedThread.write(x);

```

Remember that you are sending *bytes*, not ascii representations of them. For example, if the variable 'u' is 9, you would be sending the value 57. The larger problem is that if 'u' is 10 or higher, you are sending more than one byte, and the code below...

```
case 'A':
    nhan=Serial.read();
    //digitalWrite(8,LOW);
    break;

```

...only reads one byte of the number. A better way to approach this is to always send your data in a packet - start each packet with a control or attention byte (255 is a good one), a command for your select, and as many bytes as you need for the data. Then *always* send and read a complete packet.

## Arduino code:

```
//Defines make your code more readable.
#define PACKET_SIZE 3
#define CONTROL_BYTE 255
#define WHATEVER_A_MEANS 65
#define WHATEVER_B_MEANS 66

//...

void loop()
{
    byte buffer[PACKET_SIZE];

    if (Serial.available() >= PACKET_SIZE)
    {
        // Read the first byte
        buffer[0] = Serial.read();
        // If it's really the start byte (255) ...
        if (buffer[0] == CONTROL_BYTE)
        {
            // ... then get the next two bytes
            for (i = 1; i < PACKET_SIZE; i++) buffer[i] = Serial.read();
        }
        else
        {
            //Otherwise it isn't a good packet.
            return;
        }

        switch (buffer[1])
        {
            case WHATEVER_A_MEANS:
                nhan = buffer[2];
                break;
            case WHATEVER_B_MEANS:
                nhan1 = buffer[2];
                    break;
            //etc.
        }

        //...

```

## Android code:

```
//Class level scope. Note that these don't have to be 'letters' unless you
//need them to be for some other reason.
public static final byte CONTROL_BYTE = (byte)255;
public static final byte WHATEVER_A_MEANS = (byte)65;
public static final byte WHATEVER_B_MEANS = (byte)66;

//...
public void doTimerTask() {
    mTimerTask = new TimerTask() {
        public void run() {
            thandler.post(new Runnable() {
                public void run() {
                    Bluetooth.connectedThread.write(CONTROL_BYTE);
                    Bluetooth.connectedThread.write(WHATEVER_A_MEANS);
                    //Note that this is a narrowing cast of u.
                    Bluetooth.connectedThread.write((byte)u);

```

If 'u' needs to hold values bigger than 8 bits (you have it declared as an int), you'll need to split it into bytes and then recombine them in the Arduino code.

# Answer
> 0 votes
sr, Arduino code

```
float nhietdo,doam,nhietdotb,doamtb;
float t,p;
char re;
char p1,p2;
int chanlaynhiet=0;
int pwm,pwm1;
String nhan,nhan1;
boolean batdau = false;
void setup()
{
  Serial.begin(9600);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(8,OUTPUT);
}
void loop()
{
if(Serial.available()>0){
re = Serial.read();
switch(re){
  case 'S':
  Send();
  digitalWrite(8,LOW);
  break;

  case 'A':
  nhan=Serial.read();
//      digitalWrite(8,LOW);
      break;

      case 'B':
      nhan1=Serial.read();
//      digitalWrite(8,LOW);
       break;

      case 'E' :
      batdau = true;
      break;

      case 'Q':
      batdau = false;
      break;
    }
    if(batdau){
     start();
    }
  }

void start()
{
  while(1)
  {//doc ppm
    for(int i=0;i<10;i++)
    {
    nhietdotb=nhietdotb+analogRead(A0);
    delay(1);
    }
    nhietdo=nhietdotb/10;
    nhietdotb=0;
    //doc ph
    for(int j=0;j<10;j++)
    {
   doamtb=doamtb+analogRead(A1);
   delay(1);
    }
   doam=doamtb/10;
   doamtb=0;
//    if (isDigit(pwm1))
//   analogWrite(10,pwm1);
//   if (isDigit(pwm2))
//   analogWrite(11,pwm2);
   analogWrite(11,nhan1.toInt);
   analogWrite(10,nhan.toInt);
   digitalWrite(8,HIGH);

   if(Serial.available()>0)
   return;
}
}

void Send()
{
   Serial.print('s');
   Serial.print('Y');
   if((nhietdo<1000)&&(nhietdo>=100)){
   Serial.print("0");
   }else if((nhietdo<100)&&(nhietdo>=10)){
   Serial.print("00");
   }else if(nhietdo<10){
   Serial.print("000");
  }
   Serial.print(nhietdo,0);

   if((doam<1000)&&(doam>=100)){
  Serial.print("0");
  }else if((doam<100)&&(doam>=10)){
  Serial.print("00");
  }else if(doam<10){
  Serial.print("000");
 }
 Serial.print(doam,0);
 Serial.print('X');
 Serial.print(nhan);
 Serial.print(nhan1);
}

```

# Answer
> 0 votes
As Cominterm said, you are doing a lot of mistakes. I would use start and end bytes like:

```
HEX       ASCII

31 3B  |  "1;" -start of the message

3F 30  |  "?0" - end of message

```

And in arduino check for them.

Also a tip, if you read bytes i would get rid of those 'A', 'S' and so on. These are ascii codes. You can easily do a mistake and this will be pain in the ass. Send byte `10` from Android and read as byte `138` in Arduino, because in Java byte is `-127 : 128` and Arduino `0 : 255`

I would do in hex representation, this helps in troubleshooting. For ex.: byte `1C` hex in Android is `1C` hex in Arduino.

Also get rid of those byte to string, int to string conversations. They add more points to mistake :) Also check if string is terminated with `\0` and it will be 2 bytes instead of 1.

---
Tags: arduino-uno, android
---


title: How are PCB's programmed?

text:
# Question
Title: How are PCB's programmed?
So recently I have been looking into prototyping my arduino project and there are a lot of tutorials online on how to take your Arduino and using a software such as Eagle to make a PCB layout but I was wondering how you would get the Arduino program onto that PCB. Surely in large scale circuit manufacturing they wouldn't have a usb attached so that they upload a program into each and every one of their circuits?

# Answer
why not?

Well ok ... they might not connect a USB to each one as there are faster ways - flyingProbe/PogoPins on a "bed of nails"

http://en.wikipedia.org/wiki/In-circuit\_test

This type of temporary connection speeds up testing & pre-programming considerably.

Each card that is made has to go through some form of test process at the end (flying probe or manual).

https://learn.sparkfun.com/tutorials/electronics-assembly

> On boards that require programming or calibration, additional steps are taken to load code and verify the output.
> 5 votes

# Answer
For commercial products where very large quantities are produced, a microcontroller will be "mask programmed" - the (well-debugged) program will be built into the microcontroller as part of the IC production process.

For smaller quantities, the microcontroller may be programmed in a special fixture before being installed on the PC board. Also, most current microcontrollers have "In System Programming (ISP)" capability, which typically requires a 6 - 10 pin connector on the board, and a special programmer to plug into that board.

I think it is highly unlikely that an Arduino-based program would be used in any commercial product.
> 2 votes

# Answer
Actually, they generally do load a program into each and every one of their devices individually. They can do a lot more than that as well. Ever heard of something called JTAG? For large circuit boards, most of the large ICs are connected to a JTAG scan chain. Once the board is assembled, they connect a JTAG cable to the scan chain. Special test software controls the scan chain through the JTAG cable, possibly connected to the control computer via USB. The software can take control over the I/O pins on the ICs on the scan chain and set test patterns to check for opens or shorts. It can also perform more complex testing in concert with external test equipment, even including temporarily loading special diagnostic firmware. Once the test passes, the computer can then initialize ROMs, load firmware, set serial numbers, etc.

This is done one board at a time. Often, special test and/or programming jigs are built that allow boards to be connected and disconnected quickly, and usually multiple jigs are used in parallel for higher throughput.

For some chips, they can be programmed before installation either with mask ROM or with a standalone programmer. This is done when volumes are large and testing is not required, or if the devices must be programmed for the automated testing to work correctly.
> 2 votes

# Answer
cheers Brandan :)

I would suggest for you to make your own programmer. Then you will know a lot about programming and so on. If you want to program a chip on pcb, you have to have output pins of ISP. Throw these pins you will pump your code to Atmega chip.

Software Khazama is "old" and tested one. It really works :) AVR studio is also good one

Hardware USBasp There are ready pcb layouts in eagle. Building your own HW will be a bit more expensive than buying one, but if we count in experience it will be priceless :)

Also you can use bootloader. Check in google there are plenty of tutorials.
> 0 votes

---
Tags: prototype
---


# Question
Title: Interfacing a CCTV camera (AV output) with Arduino Uno
I have to use a camera to take picture in my major project. I want to use this camera, which has AV output. Please tell me how to interface this camera with my Arduino Uno and use the data from camera and send it to my PC using a Wi-fi Module?

P.S. Please do not suggest me to use wireless camera because firstly they are expensive and secondly I require a board in my project anyway.

# Answer
Unfortunately, I have to tell you that a UNO isn't enough powerful to work with any type of camera: it hasn't got enough ram and processing power to elaborate your camera's data. (see atmega328P's specs)

I'm not sure you can work with that camera, unless it is digital and has integrated RAM to keep the frames.

A good project which I suggest you to see is arducam.
> 2 votes

---
Tags: arduino-uno
---


title: I2C or SPI to control 6 motors?

text:
# Question
Title: I2C or SPI to control 6 motors?
I am a hobbyist & know little about electronics.

I am making a robot arm, like this one. For which I will need 2 stepper motors (for elbow & shoulder joint) & 4 simple DC motors.

Which means I will need to allocate a lot of pins on my board (Uno).

So I was just reading about I2C & then eventually SPI. My question is:

1. Is it possible to control 6 motors (or atleast 2 steppers) with I2C or SPI (assuming the motors are powered by seperate source), if so can you point me to someone's example code.
2. If not possible, how do I overcome the shortage of pins, because I have already dedicated them to many sensors.

# Answer
For the stepper motors, the easiest way to work with them is by using a very common A4988 board which is widely used with 3D printers. The controls are very easy and for them I send you this question which I answered some time ago.

Then, you say that you haven't got a lot of connections left on your UNO board, so I think that SPI would't be very useful, as it takes 3 pins for the data transmission (SCLK, MOSI, MISO) plus one pin for every device you connect.

The best way (even if it is a little slower that SPI) is to use I2C, which needs that you leave unused analog input pins A4 and A5, as they are the I2C BUS. Unfortunately I haven't any knowledge about I2C DC motor drivers.

For the steppers, I suggest to take a look at this, but it depends by your budget for what you can buy.

You could fix the pin shortage problem by adding some 74HC595 shift registers. They aren't very expensive (less than a dollar, or if you live in europe, .5€) and they can be daisy-chained. To control them, see the Arduino website tutorial.

Finally, if the pins that you use are inputs, use a 74HC165, which is the opposite of a 595. As always, see the Arduino website tutorial.
> 2 votes

---
Tags: pins, motor, i2c, spi
---