title: Two Arduinos Send data via Analog Pin?

text:
# Question
Title: Two Arduinos Send data via Analog Pin?
What I want to do is allow **Arduino A** to send some constant value to **Arduino B**.

I sense something inherently wrong with my approach, but I cant figure out what it is.

So in the diagram below you will see **Arduino A** setting its Analog Pin 0 as *OUTPUT* and write a value 2 every 500ms. On **Arduino B** we have Analog Pin 0 set as *INPUT* to receive and print data to Serial. The *GND* pins of both Arduinos are also connected.

When this setup is executed, **Arduino B** is constantly receiving data in the form of a 3 digit number starting with 3XX. I am starting to believe this is voltage value?

***What is inherently wrong with this idea?***

# Answer
> 10 votes
This answer provides both Arduino specific knowledge and general electrical knowledge - both are necessary for a good solution (unfortunately).

---

Summary

## To carry out Arduino analog to analog transfer:

* Use analogWrite(pin, value) on a valid **digital** pin (see below)
* Use analogRead(pin) on a valid analog input pin.
* Connect a series resistor between the two pins - say 10k.
Place a capacitor from the analog input to ground, say 100 nF to 10 uF.

The R & C act as a low pass filter to convert the PWM to DC.
Details below.

---

Arduino analog pins are ONLY for analog input, not for analog output.
So trying to do analog out on an analog pin dooms your attempt to failure.

Arduino analogWrite(pin, value) only works on DIGITAL pins and then only on the subset of digital pins that have PWM capability. This is typically digital pins 3 5 6 9 10 11.

"analogWrite(pin, value) produces as others have said - a PWM signal - rail to rail square waves with mark space ratio that varies so the mean DC value changes. For a 5V system =
V\_DC\_mean ~~= value/256 x 5V.
Where 'value' comes from analogWrite(pin, value)

To convert the PWM to good-enough DC a low pass filter with a cutoff somewhat below the PWM frame rate is needed. AFAIK Arduino PWM frame rate is about 800 Hz - so components are usually higher than that. A simple RC filter where R x C is usefully more than about 0.001S will start to work . Larger RC is smoother but with secondary effects. Using a 10 uF ceramic cap and a 10k resistor is probably OK. 10 uF x 10k = 0.1S. 1uF and 1k = 0.001 s = marginal. An electrolytic cap can be used but leakage current may slightly affect accuracy. So -

---

From somewhere in Arduino land (unknown) I copied the material below.
This is NOT in the basic reference, but should be.

* Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.

# Answer
> 3 votes
`analogWrite()` on the Uno doesn't actually output an analog value. It outputs a PWM wave whose *average* is equivalent to that value. If you want to turn it into a true analog value then you need to put it through a low-pass filter in order to remove the components that make it a PWM wave instead.

# Answer
> 3 votes
If your aim is to send a constant value from Arduino A to Arduino B, then a really easy way is to use SoftwareSerial.

Let's say you are using Arduino Uno - you can use pins 2 and 3 for SoftwareSerial (see which pins are supported for which device at http://arduino.cc/en/Reference/SoftwareSerial)

Cross connect pin 2 and 3 from Arduino A to pin 3 and 2 of Arduino B. You can send any random data between the two Arduinos by uploading a sketch like the following on to each. You can use a program like CoolTerm to have a "SerialMonitor" open to each Arduino (using the Arduino IDE, you can open only one monitor at a time)

The advantage of this approach over using AnalogWrite/AnalogRead is that with AnalogRead, you can only get 1024 values, which is based on the voltage. With SoftwareSerial, you can send any arbitrary data.

```
// include the SoftwareSerial library so you can use its functions:
#include <SoftwareSerial.h>

#define rxPin 2
#define txPin 3

SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

void setup() {
    pinMode(rxPin, INPUT);
    pinMode(txPin, OUTPUT);

    mySerial.begin(9600);

    Serial.begin(9600);
 }

void loop() {

    if ( mySerial.available() )
    {
         while ( mySerial.available() )
             Serial.write(mySerial.read());

         Serial.println();
    }

    if ( Serial.available() )
    {
        delay(5);

        while ( Serial.available() )
            mySerial.write( Serial.read() );
    }

}

```

# Answer
> 0 votes
As has been mentioned above, using analogWrite won't work. (I suppose you could sample the supposed analogue signal with a fast loop and measure the duty cycle...)

Why not use `SoftwareSerial` to send data between the two Arduinos?

It's a library which creates another serial port, entirely in software, so it's independent of the main UART on the USB port.

It's already part of the IDE and it's easy to use - in fact the demo code on the help page will already work for you, transferring any characters from the USB serial port to the software serial port.

# Answer
> 0 votes
As others have pointed out, your original suggestion will not work.

You could use PWM output and a filter which may work (you will need quite a large capacitor and/or resistor). The input at the other end would only be an approximation of the output (you could calculate based on detailed knowledge of component values and frequencies). Depending on the rate at which the value changes you may get different values on each read.

There are better ways. As suggested, serial will work (either hardware or software depending on other factors), and is probably easiest. You could use any of the common communication protocols (I²C or SPI) or even send values via IP.

# Answer
> 0 votes
The Analog In does exactly what it says - it only reads (samples) analog voltage levels.

Using AnalogWrite(0,2) does not make pin A0 in Analog In to output the voltage of 2\*AVCC/1024, but instead makes the pin D0 to do that instead. (Most D0 pins on Arduino boards do not have a PWM output associated with them, so the behaviour would be undefined.) In the mean time, your A0 is doing nothing. (I suspect it's floating / not connected, hence the 3xx value. Could check the datasheet to be sure.)

So what should we do instead? For a start, connect Arduino B's A0 to Arduino A's pwm pin. If you're using Uno, you can connect to any of the pins 11,10,9,6,5,3. Then you can use the code:

int PWMPin = 11; int SignalLvl = 2; analogWrite(PWMPin,SignalLvl);

Give that a try. And you'll see that it works... sort of.

But then there's a problem. your readings will be close to what you want, but quite erratic. The reason is partly because analog signals are super unreliable and is filled with noise. But the main reason is really that Arduino's analogWrite is actually NOT designed as an analog signal output. It is a PWM, which outputs GND and AVcc levels at variable periods at a fast speed so that it approximates the voltage level you want when averaged.

If you want to experiment with this, you can connect a resistor and capacitor to the output, creating a low pass filter. (Here's more info: http://provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/)

---

Having said all that, I guess the question most of us would like to ask is: is there a reason why you want to send data via analog? Analog signals are prone to noise. If data fidelity is critical, your best best is to use serial communication as highlighted by most answers here.

For simplicity, I suggest I2c which uses only 2 wires to communicate. If speed is of essence (like, writing to 10,000 bytes of data every second) you could try SPI or even parallel communication.

Hope this helps and good luck!

---
Tags: serial, communication, analogwrite
---


title: Time based scheduling, NTP vs delay()

text:
# Question
Title: Time based scheduling, NTP vs delay()
Without asking an open-ended question, i wish to find the best way (resourcefulness) to execute methods from an arduino based on time.

in a nutshell, every 10 minutes i want functionA() to be called & every 30 minutes, functionB(). At this point i'm unable to specifiy whether a method would need to be called at a less frequent rate, however i wish to assume that one may.

My 2 ideas so far:

* encapsulate the functions a & b inside the NTP client, and execute based on the minutes in an hour

**or**

* use delay() or even the milli() counter with functions a & b below inside the loop.

My main worry of the 2nd option is that the arduino handles time keeping itself, in a long run (lets say 1 year), the arduino will end up with no memory left. Whats is the consensus with this?

Board wise, to be run on Uno & Mega.

# Answer
> 1 votes
memory used by delay() and milli() (if any) will be recycled every time you call it, so it does not add up. You should be aware that milli rolls over (resets back to 0) after approximately 50 days - see http://arduino.cc/en/Reference/Millis \- you will need to keep track of how many times it has overflowed, and include that in your calculations.

delay will only be useful if you do NOTHING AT ALL during that time - if you want to do other stuff in that space, you should use milli(). Also, if you delay (without using milli()), your events will drift by the time it takes to run the code. delay() and milli() will also only be as accurate as the crystal on your arduino - it should be no more than 20 parts per million; this comes to 10 minutes per year. This may or may not be a problem.

NTP will use a lot more resources, and has to be polled. It is also potentially less reliable (i.e. NTP may be down for short periods).

If you need accurate timing, the best solution would be to use delay() to pass the time (approximately), milli() to keep the time, and adjust for drift with NTP.

# Answer
> 1 votes
Connect a battery backed up Real-Time clock to your arduino and use that to keep track of the time.

Basically the same idea as NTP but minimal hardware is required and you can get an RTC with the long term accuracy you need.

# Answer
> 1 votes
Both NTP and milli() waste a lot of processing as it keeps the Arduino busy checking if the time is right.

Your best bet is to use the Arduino timer. Set the timer to interrupt every 10 minutes. If you don't need to do anything aside from functions A and B, you can let your Arduino sleep and keep power draw to a minimum.

```
// Example code
void funcA(){
    // do stuff
}
void funcB(){
    // do stuff
}

void setup() {

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // clear TCCR1A
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    // 15624*1024/16000000 = 1sec at 16MHz
    OCR1A = 15624;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // use 1/1024 the speed of the clock:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

ISR(TIM1_COMPA_vect)
// Your task manager here
// This function decides when to execute the functions A and B
{
    static t1= 0;
    static t2= 0;

    // increment your counter flags
    t1++;
    t2++;

    if (t1==10) {//runs function every 10 sec
        funcA();
        t1=0;
    }
    if (t2==30) {//runs function every 30 sec
        funcB();
        t2=0;
    }
}

void loop(){

    // do stuff or sleep for even more power saving
}

```

Hope this helps.

---
Tags: arduino-uno, arduino-mega, millis
---


title: GSM and GPS shield pin conflict

text:
# Question
Title: GSM and GPS shield pin conflict
I have an Arduino GSM shield and I plan to purchase an Adafruit GPS shield. The GPS module uses Pin 7 & 8 for Rx and Tx, but the GSM shield uses Pin 7 for Modem Reset.

Will the overlap on pin 7 affect it in any way? If it does cause issues, how can the problem be avoided?

# Answer
> 3 votes
Looking at the PDF for the Adafruit GPS shield, pin 7 is indeed hard wired to `Rx` and pin 8 is hard wired to `Tx`.

These can not be changed.

Looking at the guide for the Arduino GSM shield pin 7 is indeed reserved for modem reset:

> Digital pins 2, 3 and 7 are reserved for communication between the Arduino and modem and cannot be used by your sketches. Communication between the moden and Arduino is handled by the Software Serial library on pins 2 and 3. Pin 7 is used for the modem reset.

As this is the case, should you stack the two shields together, without modification, then the *overlap of the `Rx` pin on the GPS shield will cause resets to the modem on the GSM shield*.

So, it seems that your best option is to use the solution provided by RedGrittyBrick, to your previous question Arduino shield stacking, the Go-Between Shield

> You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

Once you have used the Go-Between shield to reassign the `Rx` pin to something that the GSM shield does not use, (as 2, 3 and 7 are already used, let's say you use pin 6), then in the **File -\> Examples -\> Adafruit\_GPS -\> Parsing** sketch, you will need to change the line

```
SoftwareSerial mySerial(3,2);

```

to

```
SoftwareSerial mySerial(8,6);

```

instead of

```
SoftwareSerial mySerial(8,7);

```

which is recommended in the PDF.

I hope that this answers your question(s). Let us know how you get on.

---

### Addenum

The schematic of the Arduino GSM shield:

The schematic of the Adafruit GPS shield:

---
Tags: arduino-uno, pins, shields, gsm, gps
---


# Question
Title: Can i use arduino code, without using arduino board but just using MCU included
I am developing a product, and to ease my job i am planning to use MCU inside the arduino with the library of Arduino.

Since all the registers are already defined inside the library, and all required things to registers of corresponding MCU are done to "make a pin input/output , enable interrupt , enable UART , enable I2C". I think that i can directly use the arduino coding enviroment even if i use MCU seperately.

Is it possible and how? (can i use it in commertial product, i have already prototyped it with arduino)

# Answer
Yes, you can. Once you have a .hex file for a specific MCU and environment you can use a programmer to upload it to a discrete MCU.
> 1 votes

# Answer
Ignacio said everything is needed. Just search on google :) You can use programmer like khazama.

Also you can use arduino board to program atmel chips. Using an Arduino as an AVR ISP

And now you need only .hex file to upload to your chip

How to find .HEX

I just want to point out one thing. Do not play with lock bits:)
> 0 votes

# Answer
You can program an AVR microcontroller easily with an existing Arduino as the programmer. AFAIK there's no easy way around SMD packages. The last time I've gotten them, I have to solder programming wires on them before placing it on the board. If you have space, you can also wire the ISP pins to a connector on the board.

In any case, here are the steps to program your chip, whether DIP or SMD.

1. Upload the Arduino ISP Sketch to your Arduino board's MCU.
2. Wire up the Vcc and GND, and the SPI pins (MOSI,MISO,SCL). (The wiring is actually described in the comment section of the sketch. As for the pin out on the ATmega328, go to page 3. You can find similar datasheets if you're using other MCUs.)
3. Write your code
4. Click "File\>Upload using programmer" or just press Ctrl + Shift + U.
5. Done!

I think most AVR MCUs come with an internal calibrated resonator, but if you want to drive it at a higher speed (16MHz/20MHz...) you will need to connect the MCU to a crystal oscillator. As always, refer to the datasheet. ;-)

Here's another link you can refer to: link

Hope this helps.
> 0 votes

---
Tags: programming, bootloader, arduino-ide, compile, prototype
---


title: Arduino around the Xmega?

text:
# Question
Title: Arduino around the Xmega?
I came across a dev board around the Atmel Xmega controller. This an AVR like used on Arduino, but with a lot of extras.

I was surprised to see that the board is hardly more expensive than an Arduino, despite:

> * 384kB of Flash (versus 32kB for Arduino)
> * DMA
> * Xmega can run at 32 MHz (16 MHz for Arduino)
> * on-board OLED display
> * on-board light and temperature sensors
> * on-board microSD socket

For all these on-board features you'd need a shield or breakout board for Arduino. I seems to me that for a lower price than Arduino you could build a much more powerful system, which is Arduino-compatible.
How hard would it be to port Arduino to the Xmega?

see also http://www.element14.com/community/docs/DOC-71436

# Answer
There's an attempt to get the Atmel XMEGA boards working in Arduino IDE.

https://github.com/akafugu/Xmegaduino

It's not fully featured yet but appears to have to features to allow you to start hacking with this board.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to use 503 Thermistors for temperature?
I have a black Thermistor with the number 503 on it.

I know that I would need a 50k resistor as a voltage divider.

I don't get to convert the number I am getting. I get the number 340 when my house is at 64\*F. I bought a kit on Amazon and it came with it and there is no documentation.A test with multimeter has shown at 17\*C I get 30k ohms.

This is how it is wired:

```
[Ground] -- [50k-resistor] -- | -- [(503)thermistor] --[Vcc (5v)]
                              |
                         Analog Pin 0

```

# Answer
> 0 votes
I found some code for a 10k thermistor and modified it for a 50k and cut out the code to display Celcius. I found this on the Arduino playground posted by: Milan Malesevic and Zoran Stupic.

Origional code is found here: http://playground.arduino.cc/ComponentLib/Thermistor2

This is what I came up with and it returned the proper temp in F for a 503 Thermistor.

```
#include <math.h>
// enumerating 3 major temperature scales
enum {
  T_KELVIN=0,
  T_CELSIUS,
  T_FAHRENHEIT
};

#define EPISCO_K164_10k 4300.0f,298.15f,50000.0f  // B,T0,R0

float Temperature(int AnalogInputNumber,int OutputUnit,float B,float T0,float R0,float R_Balance)
{
  float R,T;

//  R=1024.0f*R_Balance/float(analogRead(AnalogInputNumber)))-R_Balance;
  R=R_Balance*(1024.0f/float(analogRead(AnalogInputNumber))-1);

  T=1.0f/(1.0f/T0+(1.0f/B)*log(R/R0));

  switch(OutputUnit) {
    case T_CELSIUS :
      T-=273.15f;
    break;
    case T_FAHRENHEIT :
      T=9.0f*(T-273.15f)/5.0f+32.0f;
    break;
    default:
    break;
  };

  return T;
}

//example of use #2
// using numbers instead of episco k164 definition
// this time reading from analog input 2
// getting result in fahrenheit

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

void loop() {

 Serial.println("********");
 Serial.println("Temp");
 Serial.println(Temperature(2,T_FAHRENHEIT,4300.0f,298.15f,50000.0f,10000.0f));
 Serial.println("********");
 Serial.println(" ");

 delay(500);
}

```

Good luck!!!!

# Answer
> 1 votes
First of, **503** means 50 x 10^3, ie **50K Ohm**: that is the maximum resistance of this thermistor (the higher resistance occurs for lower temperatures). However, having just that without any precise reference may prove difficult to find a relevant datasheet that could help you calculate the temperature from the measured voltage.

I think what could work well is just simple calibration by establishing a mapping between the value returned by `analogRead()` and the temperature measured by a real, good precision, thermometer.

Establighing the mapping for 2 extreme temperatures would provide a **first approximation** on computing any temperature from the read value.

However, such an approximation would not be very accurate because thermistors are **not linear**, ie their resitance don't vary linearly with temperature.

What you can try to do then, is to increase the number of mapped *value\<-\>temperature* with regular intervals of temperatures; then you can use linear approximation between two consecutive mapped values, which would provide better results.

The difficulty here is to "produce" the temperatures for which you want to find the mapped value: if you can spend one year for that, then just let the chqanging seasons operate that for you :-) otherwise use what you can find at home: fridge, oven, fan, heater...

# Answer
> -1 votes
Here is a link to Jameco, one supplier of a 503 thermistor - it is a negative-coefficient thermistor. They have a link to a data-sheet for it. I can't say for sure that this is your device, but a simple experiment with your ohm-meter should confirm it.

---
Tags: arduino-uno
---


title: Send array of Infrared codes

text:
# Question
Title: Send array of Infrared codes
I'm having a bit of a problem when sending IR Codes stored in variables. I swear I had this convered up already. I don't actually know the reason why I can't use variables in the first place. I receive data over Bluetooth Serial Com and I'm using an Arduino ProMicro as ISP for the Arduino Nano.

I want to send data over Serial comm and then send an IR code to the end receiver.

Here is some of the code():

```
#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) // Receive array of characters

char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
String HRD[]={"Power", "Input", "ChaUp"}; // Action referece
byte CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
int IRArray = 2; // Size Of The array

if ( SerChar[0] == 's' ) { // Compare Array
  for (int CountIR = 0; CountIR <= IRArray; CountIR++){ // Loop through array
    if ( SerChar[0] == IDChar[CountIR]) {
       bluetooth.println(HRD[CountIR]); // Send String in array - Works
       SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
    }
  }
}
}

```

There's not a problem with the current expression as it compiles normally and I can send serial data normally finishing the function. If I replace the array **CodesIR\[CountIR\]** for example with **0x61A0F00F** then it works perfectly.

How can I use a variable instead? Can anyone help? It is the **byte CodesIR\[\]** ??

I used a **Switch/Case** and it works but I prefer a variable/array and less useless coding. Thanks for understanding!

# Answer
> 4 votes
Well as usual it was something stupid (-\__-) I changed the **byte** array for **long** and it worked perfectly.

Here is the complete code working():

```
#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) { // Receive array of characters

    char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
    String HRD[]={"Power", "Input", "ChaUp"}; // Action reference
    long CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
    int IRArray = 3; // Size Of The array # Edit

    if ( SerChar[0] == 's' ) { // Compare Array
      for (int CountIR = 0; CountIR < IRArray; CountIR++){ // Loop through array # Edit
        if ( SerChar[0] == IDChar[CountIR]) {
           Serial.println(HRD[CountIR]); // Send String in array - Works
           SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
        }
      }
    }
}

```

---
Tags: serial, bluetooth, arduino-nano, softwareserial
---


# Question
Title: Choosing rangefinder for obstacle-avoiding
I am looking to buy a range finder module for an obstacle avoidance robot. Currently, two good options based on available libraries and compatibility with Arduino and rPI are HC-SR04 and parallax ping.

In terms of form factor these seem the same. The only difference I can tell is 4 pins vs 3 pins. Also the price, with parallax being more than x4 the price. As I would rather not buy something cheaper which will need replacing, is anyone aware of further differences, that will make the parallax a better option?

both need 5V both have max range of 3-4m Sensor angle HC- 15 degrees, parallax cant find..

# Answer
> 1 votes
> Odds are pretty good they are real close. I've only used the sr04 with 4 pins (too lazy to mod) and it was ok. cant say if the parallax is better or not. For 4 times the price you'd expect it to be, but so far in robotics, price seldom reflect performance in my experience. – Spiked3

I've also used the SR (with 4 pins) and it worked great. \<2$ on eBay

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


# Question
Title: Arduino program wont work properly for some reason
I have a arduino program that I wrote with my teammembers. We are working on a project and try to move a RC car. Here is our code.

```
int forward =12 ; //assign to correlating pin attached to TP06
int backward = 11; //assign to correlating pin attached to TP07
int left = 10; //assign to correlating pin attached to (left steer)
int right = 9; //assign to correlating pin attached to (right steer)

// TP09 & TP02 (don't remember which is left and right)

void setup() {
pinMode(forward, OUTPUT);
pinMode(backward, OUTPUT);
pinMode(left, OUTPUT);
pinMode(right, OUTPUT);
}

void move_Forward() {
digitalWrite(forward, HIGH);
digitalWrite(backward, LOW);
}

void move_Backward() {
digitalWrite(backward, HIGH);
digitalWrite(forward, LOW);
}

void turn_Left() {
digitalWrite(left, HIGH);
digitalWrite(right, LOW);
}

void turn_Right() {
digitalWrite(right, HIGH);
digitalWrite(left, LOW);
}

void stop_Completely() {
digitalWrite(forward, LOW);
digitalWrite(backward, LOW);
digitalWrite(right, LOW);
digitalWrite(left, LOW);
}

// loop will keep going while arduino has power
void loop() {
move_Forward();
turn_Left();
}

```

When we run this code, for some reason forward pin and left pins are becoming deactivated, which are the pin numbers 12 and 10. Like it does not supply voltage anymore for some reason. However right pin and backward pins, which are pins 9 and 11, which was not included in loop, works! I can run the RC car with these pins. I dont understand why this is the case. Shouldn't the left and forward pins work? If they are not working, how come? Sorry I am new to arduino programming language and its been very challenging for me and my group. Thanks in advance.

# Answer
On many Arduinos, those pins (10-12) are shared with the ICSP header - are you programming/testing with it plugged in or unplugged? If plugged in, you might be affected by what you're plugged into.

Here's a useful pinout: http://t.co/MKtmCILSdj

Here's a Nano pinout:

Note that the ICSP is electrically connected to pins D11, D12 and D13 - so if you have something plugged into the ICSP header, you have something connected to those pins which might be causing your problem.

If you're programming via serial port (TX/RX) and have nothing connected to ICSP, then this isn't your issue. If that's a case, it's possible to fry a few pins on a Nano and have it still appear to mostly work - trying another couple of pins might tell you more. (For instance, try D4 and D5 instead of D10 and D12.)
> 1 votes

# Answer
Have you tested this on more than one Arduino? My first Arduino board had a dead UART. Took me weeks and purchasing a second Arduino to figure it out. It worked well enough to not initially suspect the UART (I'm not a complete idiot). ;)
> 0 votes

# Answer
First: turn off the old direction before turning on the new one. Now you're doing it the other way around.

Then, in your main loop you're repeating forward and left over and over. I guess you want to move forward for some time, then turn left, then move forward again, etc.
But moving forward does deactivate the reverse, but doesn't change left or right. So you're always repeating commands which haven't been changed in the first place: forward will always be active, and so will left be. You'll go in a circle, I don't know if that is the idea.

If you want to go straight, you'll probably want to turn off both left and right? Then add a delay before turning; right now your commands occur within microseconds of each other.
> 0 votes

---
Tags: arduino-nano
---


title: Arduino Based Home Automation System

text:
# Question
Title: Arduino Based Home Automation System
I am working on my project of home automation system using Arduino GSM SIM900 & four channel relay module. I am facing a problem in my code. Can any one help me on this, SMS is receiving but its not switching the relays?

```
#include <SoftwareSerial.h>

// EN: String buffer for the GPRS shield message
String msg = String("");
// EN: Set to 1 when the next GPRS shield message will contains the SMS message
int SmsContentFlag = 0;
//control pins of relay.
int relay_a=4;
int relay_b=5;
int relay_c=6;
int relay_d=7;

// EN: Code PIN of the SIM card (if applied)
//String SIM_PIN_CODE = String( "XXXX" );

void setup()
{
  Serial.begin(19200);                 // the GPRS baud rate
  // Initialize  PINs
  pinMode( 4, OUTPUT );
  pinMode( 5, OUTPUT );
  pinMode( 6, OUTPUT );
  pinMode( 7, OUTPUT );
  digitalWrite( 4, LOW );
  digitalWrite( 5, LOW );
  digitalWrite( 6, LOW );
  digitalWrite( 7, LOW );
 Serial.println( "AT+CMGF=1" );
 delay(200);
}

void loop()
{
    char SerialInByte;
    if(Serial.available())
    {
        SerialInByte = (unsigned char)Serial.read();
       delay(5);

        // -------------------------------------------------------------------
        // EN: Program also listen to the GPRS shield message.
        // -------------------------------------------------------------------
       // EN: If the message ends with <CR> then process the message
        if( SerialInByte == 13 ){
          // EN: Store the char into the message buffer
          ProcessGprsMsg();
         }
         if( SerialInByte == 10 ){
            // EN: Skip Line feed
         }
         else {
           // EN: store the current character in the message string buffer
           msg += String(SerialInByte);
         }
     }
}
// EN: Make action based on the content of the SMS.
//     Notice than SMS content is the result of the processing of several GPRS shield messages.
void ProcessSms( String sms ){

  if( sms.indexOf("ona") >= 0 ){
    digitalWrite( relay_a, HIGH );
  }
   if( sms.indexOf("onb") >= 0 ){
    digitalWrite(  relay_b, HIGH );
  }
   if( sms.indexOf("onc") >= 0 ){
    digitalWrite(  relay_c, HIGH );
  }
  if( sms.indexOf("ond") >= 0 ){
    digitalWrite(  relay_d, HIGH );
  }
  if( sms.indexOf("offa") >= 0 ){
    digitalWrite(  relay_a, LOW );
  }
  if( sms.indexOf("offb") >= 0 ){
    digitalWrite(  relay_b, LOW );
  }
  if( sms.indexOf("offc") >= 0 ){
    digitalWrite(  relay_c, LOW );
  }
  if( sms.indexOf("offd") >= 0 ){
    digitalWrite(  relay_d, LOW );
  }
}
// EN: Request Text Mode for SMS messaging
void GprsTextModeSMS(){
  Serial.println( "AT+CMGF=1" );
}

void GprsReadSmsStore( String SmsStorePos ){
  Serial.print( "AT+CMGR=" );
  Serial.println( SmsStorePos );
}

// EN: Clear the GPRS shield message buffer
void ClearGprsMsg(){
  msg = "";
}

// EN: interpret the GPRS shield message and act appropiately
void ProcessGprsMsg() {
  if( msg.indexOf( "Call Ready" ) >= 0 ){
   //  Serial.println( "*** GPRS Shield registered on Mobile Network ***" );
     GprsTextModeSMS();
  }

  // EN: unsolicited message received when getting a SMS message
  if( msg.indexOf( "+CMTI" ) >= 0 ){
   //  Serial.println( "*** SMS Received ***" );
     // EN: Look for the coma in the full message (+CMTI: "SM",6)
     //     In the sample, the SMS is stored at position 6
     int iPos = msg.indexOf( "," );
     String SmsStorePos = msg.substring( iPos+1 );
   //  Serial.print( "SMS stored at " );
  //   Serial.println( SmsStorePos );
     // EN: Ask to read the SMS store
     GprsReadSmsStore( SmsStorePos );
  }

  // EN: SMS store readed through UART (result of GprsReadSmsStore request)
  if( msg.indexOf( "+CMGR:" ) >= 0 ){
    // EN: Next message will contains the BODY of SMS
    SmsContentFlag = 1;
    // EN: Following lines are essentiel to not clear the flag!
    ClearGprsMsg();
    return;
  }

  // EN: +CMGR message just before indicate that the following GRPS Shield message
  //     (this message) will contains the SMS body
  if( SmsContentFlag == 1 ){
 //   Serial.println( "*** SMS MESSAGE CONTENT ***" );
 //   Serial.println( msg );
 //   Serial.println( "*** END OF SMS MESSAGE ***" );
    ProcessSms( msg );
  }

  ClearGprsMsg();
  // EN: Always clear the flag
  SmsContentFlag = 0;
}

```

# Answer
> 1 votes
I think you'd want to include a call to `ClearGprsMsg()` right before the line `GprsReadSmsStore( SmsStorePos );`.

Then, `msg += String(SerialInByte);` is probably wrong, see for example http://arduino.cc/en/Tutorial/StringConstructors:

```
// using a constant integer:
stringOne =  String(13);
Serial.println(stringOne);      // prints "13"

```

---
Tags: gsm, relay
---


# Question
Title: Cannot program Arduino Micro in OSX without hard resetting the board every time
I am experiencing a problem when programming Arduino Micro in OSX Mavericks. I have tried to reproduce this problem in XCode and Arduino IDE and it is persistent. I need to make a hard-reset at the same time as a click the "program" button.

I have tried to use the new Leonardo bootloader to see if it solves my issue, but its still persistent.

I am running avrdude 6.1, what is the problem?

Stacktrace:

```
---- Size ----

Binary sketch size:   24162 bytes (of a 28672 byte maximum)
Estimated SRAM used:  733 bytes (of a 2560 byte maximum)
Elapsed time: 5.2 s

---- Reset ----

screen -X kill

No screen session found.

make: [reset] Error 1 (ignored)

sleep 1

9.2-RESET:  <   micro   ./ ./

stty -f /dev/tty.usbmodem1411 1200

---- Upload ----

10.6-UPLOAD:  <     micro   ./

/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -patmega32u4 -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -D -cavr109 -b57600 -P/dev/tty.usbmodem1411 -Uflash:w:Builds/embeddedcomputing.hex:i

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

```

# Answer
> 1 votes
This Arduino.cc article describes the differences between Leonard & Micro vs. other Arduinos, including the fact that Micro does not have a separate USB processor on board but creates a virtual USB with the main processor. There is no (or a very different) auto-reset mechanism. There is apparently a way for the IDE to open the Mac's USB at 1200 baud to cause the Micro to reset; then the IDE can wait for the virtual USB to re-appear. But it also says you may need to use the reset button suggesting the 1200 baud dance doesn't work all that reliably.

---
Tags: arduino-ide, avrdude, arduino-micro
---


# Question
Title: Unable to flash bootloader on ATmega32U4 with AVR dragon
I am flashing a *naked* ATmega32U4, but the process fails in the end where it is verifying.

```
avrdude -c dragon_isp -p m32u4 -P usb -U flash:w:Caterina-Micro.hex -U lfuse:w:0xff:m -U hfuse:w:0xd8:m -U efuse:w:0xcb:m -U lock:w:0x2f:m -v -B 100

avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
         User configuration file is "/Users/SomeUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : dragon_isp
         Setting bit clk period        : 100.0
avrdude: usbdev_open(): Found AVRDRAGON, serno: 00A200050468
JTAG ICE mkII sign-on message:
Communications protocol version: 1
M_MCU:
  boot-loader FW version:        255
  firmware version:              7.38
  hardware version:              1
S_MCU:
  boot-loader FW version:        255
  firmware version:              7.38
  hardware version:              7
Serial number:                   00:a2:00:05:04:68
Device ID:                       AVRDRAGON
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         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  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 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 : DRAGON_ISP
         Description     : Atmel AVR Dragon in ISP mode
         Vtarget         : 5.0 V
         SCK period      : 100.37 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.16s

avrdude: Device signature = 0x1e9587
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 62.28s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 152.35s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x66 != 0x6e
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as FF
avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
avrdude: safemode: lfuse reads as FF
avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
avrdude: safemode: Sorry, reading back fuses was unreliable. I have given up and exited programming mode

avrdude done.  Thank you.

```

I get another verification error when i program without fuses:

```
avrdude -c dragon_isp -p atmega32u4 -P usb -U flash:w:Caterina-Micro.hex -u

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.16s

avrdude: Device signature = 0x1e9587
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 69.60s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 178.10s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x04 != 0x0c
avrdude: verification error; content mismatch

avrdude done.  Thank you.

```

# Answer
I literally gave up and got myself a Atmel-ICE which solved all my problems.
> 0 votes

# Answer
I think you need to pass the option `-u` to disable safe mode, see the avrdude documentation. Under the `-u` option the manual states:

> If you want to change fuses you will need to specify this option
> 0 votes

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


# Question
Title: Interfacing Arduino Leonardo with PCA8574AN
I'm trying to interface my Leonardo with a "Mindsensors Magic Wand" - 8 LEDs connected to a PCA8574AN chip. On the manufacturer's page, they say it's compatible with Arduino, however no instructions or code are given. http://www.mindsensors.com/index.php?module=pagemaster&PAGE\_user\_op=view\_page&PAGE\_id=120

I've connected the SDA, SCL, 5v, and GND connectors on the arduino to the device, but have had no luck in communicating with it. None of the LEDs light up regardless of input.

I can verify that power is being supplied. The i2c address of the device is 0x70. Code is below.

```
#include "Wire.h"
#define TWBR=400000L
void setup() {
  // put your setup code here, to run once:
 Wire.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  Wire.beginTransmission(0x70);
  Wire.write(32);
  Wire.endTransmission();
}

```

# Answer
**tl;dr:** It seems like you need to send a null bit (0) to terminate the communication with this board.

In the downloads section, I found a .nxc file, which I assume is a NXT code file.

In the main loop, they configure the I2C port and a "touch sensor" (I believe this is to figure out how to synchronize the text with the motor). In that, there is a main loop in which they call `DispLetter`.

This is the `DispLetter` function:

```
void DispLetter (const byte & letter[])
{
  int nbytes;
  // Wait for the end of previously sent data
  while(I2CStatus(I2Cport, nbytes)==STAT_COMM_PENDING);
  // Write buffer to send to PCF8574
  byte WriteBuf[];
  ArrayBuild(WriteBuf, I2CAddr8574, letter);
  for(int i=1; i<ArrayLen(WriteBuf); i++)
  {
     WriteBuf[i] ^= 0xff;
  }
  I2CWrite(I2Cport, 0,  WriteBuf);
}

```

Let's read this code! First of all, it seems to make sure that the I2C port is connected, which we don't really have to worry about in our case since that's platform-specific.

After that, they create an array called `WriteBuf[]` that will store the data to be sent to the controller. Then we come across a function called `ArrayBuild`. Looking that up, it combines `I2CAddr8574` and `letter` and places it into the `WriteBuf` array. (Click here for documentation for that function.) Please note that the `I2CAddr8574` is just a byte containing 0x70 (the address of the chip), so we will not have to do this step since the Arduino handles the address. So, you will just have to send the `letter` array to the controller, ignoring the `WriteBuf` and `ArrayBuild`!

Let's figure out how `letter` is passed. In the main loop, they had this code:

```
DispLetter(L_);
DispLetter(E_);
DispLetter(G_);
DispLetter(O_);

```

That must display "LEGO." Let's figure out what `L_` is defined as. At the beginning of the document, they have this defined:

```
// Display patterns
// Each byte represents a column of dots
// Bit set to 1 means lit LED.
// Least significant bit is at top of column.
// Last byte must be all 0
// Maximum number of bytes par pattern: 15

byte L_[] = {0xff, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0};
byte E_[] = {0xff, 0x89, 0x89, 0x89, 0x89, 0x81, 0x81, 0};
byte G_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x91, 0x90, 0x72, 0};
byte O_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

byte La_[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0};
byte Ea_[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0};
byte Ga_[] = {0x72, 0x90, 0x91, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};
byte Oa_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

byte N_[] = {0xff, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xff, 0};
byte X_[] = {0x80, 0x41, 0x22, 0x14, 0x08, 0x14, 0x22, 0x41, 0x80, 0};
byte T_[] = {0x01, 0x01, 0x01, 0x01, 0xff, 0x01, 0x01, 0x01, 0x01, 0};

```

As you can see, they listed out how the dots are configured. There's a max of 15 bytes (I assume including the null bit).

There's one more piece of code that we haven't talked about:

```
for(int i=1; i<ArrayLen(WriteBuf); i++)
{
   WriteBuf[i] ^= 0xff;
}

```

So it goes through each bit, and does something to it. That is the shorthand for this:

```
WriteBuf[i] = WriteBuf[i] ^ 0xff;

```

No, that is *not* an exponent. That is an exclusive OR, a *bitwise* operator. A bitwise operator is basically where it "overlays" the two binary sequences and it does a special computation on them. If the nth bit of each input number is 1 or the nth bit of each input number is 0, the nth output bit is 0. If the nth bit of one input number is 1 and the nth bit of the other input number is 0, then the nth bit of the output is 1.

Since 0xff = B11111111, it will essentially reverse the values of each bit. You can avoid this if you say that a bit set to *0* is on, instead of a bit set to *1* (like they do in the example code). A minor adjustment that just makes your life a bit easier :)

After that, you can write that array to the I2C bus and it should display the data!
> 2 votes

---
Tags: i2c, arduino-leonardo
---


# Question
Title: Program button to switch between two values
There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.

So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.

I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.

# Answer
Pseudocode:

```
value = 0
if button is pressed:
  value = 1 - value

```
> 1 votes

# Answer
It sounds like you are using a number as a boolean (true/false) value.

You might consider using a a boolean instead.

```
boolean value = false;
if button is pressed {
    value=!value
}
if value {
    // do something here.
}

```

You can set it to `true` or `false`, or change it to it's opposite (with `value=!value` as shown above). You can also do `if value` or `if !value` ("if not value") - these are equivalent to `if value=true` or `if value=false`.
> 0 votes

---
Tags: sketch, variables, code-optimization
---


title: How to get Baite Pro Mini working?

text:
# Question
Title: How to get Baite Pro Mini working?
I have recklessly bought the Baite Pro Mini and I find it difficult to upload any program. I use Ubuntu Linux, but out of frustration I am ready to install Windows, if it is necessary.

I've read the information from the blog http://nerdralph.blogspot.ca/2014/01/baite-pro-mini-review.html . Too bad, that the blog owner didn't put much details. Can anyone here fill some blanks for me?

1. How exactly should I connect the Arduino device to the computer? I have a converter USB to serial pl2303HX: which I tried to connect with the Baite Pro Mini in almost any plausible permutation of the wires, but never got any result.

---

edit:

Here is the description of pins of the pl2303HX:
<sub>(source: fasttechcdn.com)</sub>

I did connect it the following way:

```
Baite Pro Mini      pl2303HX
GND
GND  <------------> GND
VCC  <------------> +5V
RXI  <------------> TXD
TXC  <------------> RXD
DTR

```

I also tried the permutation with different `GND` pin. I also tried pressing the `reset` button on the Baite Pro Mini around the time of hitting the "Upload" button on the Arduino standard compiler.

I believe my failure might have something to do with the absence of `DTR` pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

2. Which exactly Arduino bootloader do I need?
3. How to connect USBASP to the Beite Pro Mini?

# Answer
> 2 votes
I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).

I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.

I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.

Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!

You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)

# Answer
> 2 votes
Your connections are incorrect if you are "straight through" connecting.
Gnd & Vcc are adjacent on the processor board and separated by 2 pins on your converter.

If you find Gnd, Vcc, TX, RX on USB module and processor then you should

* Connect Gnd to Gnd
* Connect Vcc to Vcc
* Connect ........TXD to RXD and
........................RXD to TXD
* Ensure that you have the correct USB converter drivers loaded.

A reset does not seem to be needed when using the Baite processor AND Baite USB module.

---

I have a number of Baite Pro Minis working perfectly.
In my experience (3 or 4 sales so far) Baite's products are usually of acceptable quality .

Connecting "almost any plausible permutation of the wires" is a fine way to attempt to destroy the converter and/or the BPM. Logical connection should work - if you have not damaged something.

Connect as Ignacio says.
Note that you connect **BPM-TX to USB-converter-RX**, and RX to TX and \**NOT RX to RX). The BPM has connections shown on the PCB.

Baite provide this diagram

Your converter module has a different pinout which needs to be allowed for.

You must also have drivers on your system for the USB to serial bridge IC used on your converter. The Baite converter uses a CH340G IC. Your may or may not.

---
Tags: arduino-pro-mini, linux
---


# Question
Title: How Do I Send An Email WITHOUT An Ethernet or WiFi Shield
I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?

# Answer
> 4 votes
If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.

You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.

Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.

---
Tags: library
---


title: What do these operators do?

text:
# Question
Title: What do these operators do?
Going through the "timeouts" example of the elapsedMillis library (https://github.com/pfeerick/elapsedMillis) I found the following statement:

digitalWrite(LEDPIN, flashPattern\[ledIndex++\] ? ledBrightness : !ledBrightness);

* flashpattern is an array of boolean variables (boolean flashPattern\[\] = { 1,1,1,1,1,1,1,0,1,1,0 };)
* ledBrightness is a boolean as well.

What does the "?" and the ":" do there? are these boolean operators?

# Answer
```
A ? B : C;

```

is shorthand for

```
if(A) {
    B;
} else {
    C;
}

```
> -1 votes

# Answer
They are the conditional operator. If the expression before the `?` is true then the result is the expression before the `:`, otherwise it is the expression after.
> 5 votes

---
Tags: programming, sketch
---


# Question
Title: Bluetooth hc-06 and Standalone Atmega168(possible?)
I am making a project that requires bluetooth communication between a Raspberry Pi(equipped with a bluetooth dongle) and a standalone atmega168 circuit.

I want to be able to transfer information serially between the two devices over bluetooth.

I have selected the hc-06 for the arduino and some usb bluetooth dongle for the PI.

I would like to know if connecting the hc-06's TX and RX pins to the RX and TX (respectively) pins of my atmega will work or not. If not, I would like to know how to achieve that (bluetooth on a standalone arduino-powered microcontroller)

# Answer
The HC-0x Bluetooth transceivers are a drop-in replacement for a serial connection. Once the transceiver is configured (with baud-rate, device name, and pairing PIN #) you can plug it in in place of a serial line and expect to communicate. The device will take care of pairing and accepting a connection from the master device with no need for any code support from the AVR.

I use a separate program on an Arduino or a breadboarded AVR to configure my HC-06es. They retain their configuration across a power-down, and in fact, there is no hardware support for resetting them to a standard configuration; you need a program that figures out their current baud-rate in order to reconfigure them. It can save a bunch of hassle if you write down their configurations whenever you change them.
> 1 votes

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


# Question
Title: PWM pins weird on Arduino Mega, works on Arduino Uno
I've bought one of those cheap 2.4" TFT LCD resistive touchscreens, one of these:

It works great on my Arduino Uno, using the code from this github repository. Now I'm trying to get this to work on my Arduino Mega.

On the Arduino Uno, the LCD controller data lines are configured as:

```
data[0:7] = PORTB[0:1] | PORTD[2:7]

```

ie. data pins 8, 9, 2, 3, 4, 5, 6, 7 make up the LCD controller data lines.

On the Mega, the pin numbers are the same but the ports are configured differently, so that:

```
data[0:7] = ((PORTH >> 5) & 0x03)
   | ((PORTH << 3) & 0xc0)
   | ((PORTG >> 1) & 0x10)
   | ((PORTE >> 2) & 0x0C)
   | ((PORTE << 2) & 0x20)

```

I've rewritten the `TFTLCD::read8` and `TFTLCD::write8` functions accordingly.

The screen doesn't work, though. I've cut example code down to just resetting the LCD controller and reading the chip ID register, ie:

```
Tft.writeData(0);
Tft.writeData(0);
Tft.writeData(0);
Tft.writeData(0);

Tft.writeCommand(0);
unsigned id = Tft.readData();

```

Now, 9 times out of ten, this obtains the correct device ID, `0x9325`. But the other time, it obtains the device ID of `0`.

I initially suspected that this was due to the Mega running somewhat faster, but liberally sprinkling `delayMicroseconds(10)` through the `writeData`, `writeCommand` and `readData` functions doesn't seem to make any difference.

Is there something that I'm missing that is messing with the use of the PWM lines on the Arduino Mega as ordinary digital port pins?

# Answer
Never mind; this was me making a mess of the bit masking.

See this github repository for working code with Arduino Mega.
> 1 votes

---
Tags: arduino-mega, pwm, digital, timing
---


title: Arduino Raspberry Pi USB Communication

text:
# Question
Title: Arduino Raspberry Pi USB Communication
I am trying to connect an Arduino and Raspberry Pi over USB. I would like to send serial commands, just like the serial monitor in the Arduino IDE. I know how to do this on the Arduino end but I'm not sure how to send/receive serial communication on the Pi end. Ideally the solution would utilize Python.

# Answer
> 2 votes
You will need PySerial to accomplish this. A tutorial on interfacing Arduino and the RPi using a usb can be found here

# Answer
> 1 votes
You would be better to ask this on http://raspberrypi.stackexchange.com

You can use program `minicom` on the Pi; this is a terminal program like the serial monitor in the Arduino IDE, and of course you can use Arduino IDE on the Pi.

If you look at the Pi site you will see lots of Python serial communication programs.

# Answer
> 1 votes
Why do you want to use the USB port on the Pi? Isn't it easier to connect the Arduino directly to the UART pins (Pins 8 and 10) on the PI and then read out the UART in your python programme?

---
Tags: arduino-uno, serial, usb, python
---


title: Can't figure out the error to this code

text:
# Question
Title: Can't figure out the error to this code
I've written up this very simply code to control transistors in an inverter circuit. The editor is flagging up errors which I can't see myself. I'm pretty new to Arduino programming but it's very simple code and can't see why it's being shown as having errors.

At first glance, what am I missing? I've pasted a section below:

```
int Phase1pos = 13;
int Phase2pos = 12;
int Phase3pos = 11;
int Phase1neg = 10;
int Phase2neg = 9;
int Phase3neg = 8;

void setup() {
pinMode(Phase1pos, OUTPUT);
pinMode(Phase2pos, OUTPUT);
pinMode(Phase3pos, OUTPUT);
pinMode(Phase1neg, OUTPUT);
pinMode(Phase2neg, OUTPUT);
pinMode(Phase3neg, OUTPUT);
}

void loop() {
    delayMicroseconds(16);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase2pos, HIGH);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase1pos, LOW);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase3neg, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3neg, LOW);

    delayMicroseconds(7);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3neg, LOW);
    digitalWrite(16);

    delayMicroseconds(28);
    digitalWrite(Phase3neg, HIGH);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase1pos, LOW);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase2neg, HIGH);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase3neg, LOW);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase1pos, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase1pos, HIGH);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase2neg, LOW);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase1pos, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase2neg, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase2neg, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase1neg, HIGH);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase2neg, LOW);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase3pos, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase1neg, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase2pos, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase1neg, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase1neg, HIGH);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase2pos, LOW);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(16);
}

```

# Answer
> 5 votes
Here's line 109:

```
 digitalWrite(16);

```

As the error message says, there aren't enough arguments. It looks like you meant to call `delayMicroseconds()` there instead of `digitalWrite()`.

---
Tags: programming
---


title: delay() vs delayMicroseconds()

text:
# Question
Title: delay() vs delayMicroseconds()
I just started using Arduino and so far I've used both `delay()` and `delayMicroseconds()`. I was wondering what the difference between these two is, because it seems to me that they're the same.

# Answer
From the documentation:

> # delay()
>
> ## Description
>
> Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

So... milliseconds vs. microseconds.
> 3 votes

---
Tags: arduino-nano
---


# Question
Title: New to Arduino: Should I learn C, C++ or both (C & C++)?
From what i've researched here is my thoughts on both

1. C++ I heard that you can create libraries using C++ in arduino. And you can use the Arduino IDE to do that stuff. Here is the proof

http://arduino.cc/en/Hacking/LibraryTutorial

Notice that it uses the C++ syntax.

I also see arduino projects on github written on C++ https://github.com/search?l=C%2B%2B&q=Arduino&type=Repositories&utf8=%E2%9C%93

2. C

I heard that you can use AVR GCC and code it without the arduino ide. And I heard it's much faster than the arduino language because it's more closer to the metal. But I think it's harder to set up because you need a programmer into the Atmel chip, which is much more costlier compared to directly plugging in the arduino using the USB to printer cable. And you also need to download a bunch of stuff to get coding in pure avr gcc (win-Avr GCC, atmel studio etc.).

Which one should i learn C or C++? I prefer the easy to debug route. Or is it beneficial if i learn both?

# Answer
The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as `printf` and `malloc`) can be used from C++ programs.

The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.

Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.

As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.

It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.
> 5 votes

# Answer
Arduino supports c++, but does not support many of the standard libraries. The vast bulk of the functions in the Arduino IDE are c functions.

You can do almost everything in c, except for a few advanced items.

Due to the limited c++ libraries it will be difficult to learn c++ on Arduino; indeed it is not the ideal platform to learn c, as most of the tutorials will not work (because there is no I/O on Arduino).
> 2 votes

# Answer
For starting out? I would say neither. The arduino IDE is based on a programming language called processing. Which you can look at. Honestly, if you have done any programming in the past you will be fine for the basics. The advanced stuff might make you look at working with c++ files. But there is nothinging overly complex there. A lot of the add-on hardware that you can purchase comes with existing arduino libraries. Use these as a baseline.
> 1 votes

# Answer
@ConnorWolf Way too kind.

Arduino is based on Wiring, which is based on Processing, which is a kludge of Java, resembling C++ running on an embedded prototyping platform ill suited for learning programming by any Definition. Many libraries half written and confusing, implementing only as much as the original author needed, not the entire spec (SPI being a great example).

Get a Pi for the same price, at least it is an end user computer for poor people.

Besides, if you have something that can run the Ardunino IDE why are you learning to program on an Arduino? You need to be proficient in C or C++ before you attempt anything for real on an Arduino. Blinking lights is fine, beyond that, good luck.

Learn C or C++ (preferred as it is newer) on what you have, then start using the Arduino. Eclipse or Microsoft Visual Studio Community are both free and support both languages. (Both also support Arduino development when the time comes, avoid the Arduino IDE it is terrible). There are enough samples for either to keep you busy for a long time. Embedded programming REQUIRES understanding of low level hardware and IS NOT suitable for learning.

Forget modern debugging. Paid engineers grumble when they have to do it and it cost a decent price for the enabling hardware. Stick to the old fashioned printf debugging style.
> 1 votes

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


# Question
Title: Connect Arduino via TX RX Pins to Computer's USB Port
I want to avoid using the big USB B connector to program my Arduino Mega. Since there are those RX TX Pins I thought, it would be possible, to connect my USB - Wires from my PC directly to those RX TX Pins. `D+ -> TX and D- RX`. This Post on Arduino Stackexchange says, those wires are just connected, while this post says the exact opposite.

I'm confused. Is it possible or would I damage my board when connecting USB wireq to RX / TX pins on my Arduino?

# Answer
> 3 votes
The first answer that you cite that you say says it is possible is in fact not talking about what you are referring to - it is discussing the use of the RX & TX pins directly when they are not being used for USB connection.

The second answer you cite is technically incorrect but "correct enough" in the context.

The answer to your question is "It can be done but it requires a different boot loader, its slower, its technically inferior, it's less standard, it requires a degree of understanding (on someone's part) to get it going, and **it can be done**

It IS possible to access USB directly from digital I/O pins. As TX & RX are also standard digital I/O pins they could be used for this purpose BUT you need dedicated bootloader code to do this and it has inferior performance if a USB to serial converter is available. The eg ADAFruit Arduino Trinket uses this system.

---

Here is how the (or a) **ADAFRUIT Trinket Bootloader** works. (The Trinket is not mentioned here but I'm told that this is what it uses. If not, it works in functionally the same manner).

This is in turn based on the **USBaspLoader**

A (very) simple "more or less Arduino compatible" development board which can use this system is Metaboard. It's circuit diagram is shown below. As can be seen - it uses an ATMega168 and the USB connection is made to two standard digital I/O pins.

**"Metaboard" using ATMega168**

* note USB connection to pins PD2 & PD4 - NOT via RXD on PD0 and TXD on PD1 via a serial to USB converter, as is more usual.

---

AND another version: **AVRUSBBOOT**

---

And **again**

**BootloadHID** They say -

* BootloadHID is a USB boot loader for AVR microcontrollers. The uploader tool requires no kernel level driver on Windows and can therefore be run without installing any DLLs.

BootloadHID is a USB boot loader for AVR microcontrollers. It can be used on all AVRs with at least 2 kB of boot loader section, e.g. the popular ATMega8. The firmware is flashed into the upper 2 kB of the flash memory and takes control immediately after reset. If a certain hardware condition is met (this condition can be configured, e.g. a jumper), the boot loader waits for data on the USB interface and loads it into the remaining part of the flash memory. If the condition is not met, control is passed to the loaded firmware.

This boot loader is similar to Thomas Fischl’s avrusbboot, except that it is built on top of the HID device class. This implementation is more user friendly on Windows, since no kernel level drivers need to be installed.

# Answer
> 0 votes
Strictly Serial interfaces use ±15V, although this is uncommon these days (but then so are PCs with serial ports). ±12V, ±5V or even 0/+5V also exist. Connecting a ±15V interface to the Pi would destroy it. There are RS232 adapters to ensure safety.

If you are talking about connecting USB data lines to serial forget it. The voltages are the least of your worries, the USB serial encapsulates the data in a protocol.

---
Tags: serial, programming, usb
---


title: How to really shrink a sketch

text:
# Question
Title: How to really shrink a sketch
I want to make a sketch that is as small as possible, for test purposes. The problem is, when i compile the BareMinimum sketch (with an empty setup and loop), i get 466 bytes for the Uno and a whopping 4,242 for the Leonardo. Is there any way to write your own code that has no extra functions (namely Timer0 for `millis()` and `delay()`). I would also like to be able to disable the keyboard/mouse functions for the Leonardo.

# Answer
> 3 votes
You should be able to create your own board definition with a custom boards.txt file as per https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification. As I see there are several usb features in the leonardo's definition. I would hope that the compiles inclusion of the 4K is based off of these flags and not the processor type.

Where the boards.txt would use the upload, bootloader sections from the Leonardo and the build from the uno.

This is all assuming the core library build does not use processor specific flags to include USB functions.

*If you get such working. post back, I am sure others would be interested in such.*

---

I recently ran into this 4K used limitation on a library demo that actually maxed out the UNO and had to put in a

```
#if !defined(__AVR_ATmega32U4__)
...

```

around a large chunk of extra features in the sketch to fit on the Leonardo.

I had assume (wrong) that this 4K was because I still included Serial.print which when over the USB's CDC on the Leo. But I see after a memory dump of an empty sketch they are still there.

```
C:\Users\mflaga\AppData\Local\Temp\build8958339595868119500.tmp>avr-objdump -d sketch_feb13a.cpp.elf > sketch_feb13a.cpp.elf.lst

```

Which makes sense. As the Leonardo still requires the USB-CDC client (the 4K) as to detect the 1200 Baud connect from AVR-DUDE as to stroke the remote reboot.

---

Hence making a custom boards.txt without USB in the build, also needs to have

```
leonardo.upload.use_1200bps_touch=true

```

removed.

Once loaded on the target, this would require the upload to be synchronized with a manual reset of the target. As the ability to remote reboot is lost.

# Answer
> 3 votes
I recently wanted to do exactly this. Since there is no nice way to do so, I wound up writing a patch for the Stino sublime-text arduino plugin to do exactly this. It's subsequently been accepted, so it should be in any up-to-date Stino installs.

This adds a new option to Stino:

Using this mode produces compilation results like the following:

For a Uno:

> Binary sketch size: 172 bytes (of a 32256 byte maximum, 0.53 percent).
> Estimated memory use: 0 bytes (of a 1024 byte maximum, 0.00 percent).

For a leonardo

> Binary sketch size: 240 bytes (of a 28672 byte maximum, 0.84 percent).
> Estimated memory use: 0 bytes (of a 2560 byte maximum, 0.00 percent).

Actually *programming* the leonardo with the above compiled output is *probably* a bad idea, as it *might* break the auto-reset functionality, but you *could*, if you wanted. Hat-tip to mpflaga for noting this in his answer.

Note that the memory reports are actually incorrect, but that's a separate issue.

The code used for the above is:

```
int main()
{
    while (1)
    {

    }
}

```

Some notes:

* You ain't writing a "Sketch" anymore, not that you ever actually *do* write a sketch. You write **programs**. Period. I don't care what the Arduino wackos want to say, they don't get to redefine terms.
* All interrupt management is manual. This means no `milis()` or similar.
* You *can* still use the arduino serial libraries and so forth, if you want. You do have to `#include <Arduino.h>`.
* You define `main`. You don't ever return from `main`. If you want setup stuff, it goes before the `while (1)`.

# Answer
> 2 votes
Although it depends on your sketch, you can somewhat decrease the size by **reusing code with methods.**

Take this code:

```
int led = 13;
int val;

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

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  val = digitalRead(10);
}

```

1,322 bytes on Arduino Uno. Now let's shrink it a bit:

```
int led = 13;
int val;

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

void loop() {
  for(uint8_t i = 0; i < 8; i++) {
    blink(HIGH);
    blink(LOW);
  }
  val = digitalRead(10);
}

void blink(uint8_t state) {
  digitalWrite(led, state);   // turn the LED to the right state
  delay(1000);                // wait for a second
}

```

1,194 bytes. That's about a 10% decrease!

Anyway, although it doesn't *greatly* shrink a sketch, it sometimes can be the easiest route when you are two bytes over the limit, or just want to make a more compact sketch to begin with without loosing any functionality. It's not for every situation, but I find it useful sometimes.

# Answer
> 0 votes
@annonomus penguin, sure we can Although the code compiles into 1180 bytes flash + 13 bytes RAM for an uno on my computer, we can improve on it :) so golf challenge accepted and also a few usefull tips since we are in the business of learning.

Step 1: decrease variable requirements. Using an int for a led port seems a bit overkill, we certainly don't have 65535 addressable IO ports on the arduino :) So we change it to a byte just for the fun of it. We will change it over to a #define later on, but to show the impact of using too large variable types.

```
byte led = 13;
int val;

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

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

```

Compiles into 1172 bytes + 13 byte RAM. This saves 8 bytes of flash due to fewer needed operations for the byte instead of a integer. I would expect 12 bytes of ram, but okay. Not that much, but every byte saved is good.

Step 2: change over variable into defines when it makes sense. For example, the led byte is not needed, the pin won't unsolder itself.

```
#define LED 13
int val;

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

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

```

Compiles into 1142 bytesflash + 11 bytes ram. Already 38 bytes saved. This is due to fewer register operations needed to fetch the int value. Also we saved 2 bytes from RAM. (still wondering why the byte didn't compile into 1 less byte of ram.....)

Step 3: optimize code. I see 2 delays. I wonder if i change it to 1 delay it would save space, but i have to figure out the value of the LED pin and toggle (invert) it. We can do that with digitalRead(), but will it save space?

```
#define LED 13
int val;
void setup() {
  pinMode(LED, OUTPUT);
}
void loop() {
  blink();
  val = digitalRead(10);
}
void blink() {
  digitalWrite(LED, !digitalRead(LED));   // toggle the led based on read value
  delay(1000);               // wait for a second and spare yourself the other delay
}

```

Compiles into 1134 bytes + 11 bytes ram. Yay! another 8 bytes. That makes a total of 46 bytes and 2 fewer lines of code.

Also another general tip on decreasing codesize. Don't use the String class. It's HUGE, learn how to deal with char arrays, strcpy(), strcmp(). If all you have are some basic string operations, the usage of the String class is mostly just wasting space on both flash and RAM.

---
Tags: programming, sketch, arduino-leonardo
---


title: Internet of Things at home only

text:
# Question
Title: Internet of Things at home only
My question isn't specific to Arduino but can concern Raspberry Pi and all Internet of Things homemake projects.

As I'm preparing a personal projet with sensors, data storage and visualisation/reporting web page (not yet Android app) I'm looking about Internet of Things platform.

It seems all that I can find are cloud related system. I would prefer a home localized solution but I'm not able to find one (and maybe open source) where datas don't go outside home.

The goal is to be able to :

- send datas from my Arduino to a home storage server
- store these data into database for later query (may be MySql)
- trigger some computation or aggregation job over datas
- prepare some graphs
- generate some html page from template
- option: allow Android client to connect and get datas/graphs

Before starting thinking how to create my own (non standardized) system is anyone can give me some advice ? some name of such existing system ?

Thanks

Thomas

# Answer
> 1 votes
I recently worked extensively on a Home Automation Project and here's what I would recommend based off of that:

1. Use Arduino for hardware interfacing.
2. Use Raspberry Pi for hosting your server.
3. Write your server using Node.js (or Python if you wish).
4. Use Express, Socket.io (or Python simple server). Google these.
5. Use Serial (USB) for communication between Arduino and Raspberry Pi
6. Use RF/BLE if you want to go wireless.
7. Use Redis or MySQL for database.
8. Use a graph JS API for charting.
9. To build an android app, send http requests (or a Socket.io link), for communication.

This is a simple to implement, but you'll need to put some time. Good luck. All of the above steps are abstracted from each other. This means that if you want to incorporate additional features, you can change any stage without affecting the whole.

# Answer
> 0 votes
Setting up a basic webserver on the Raspberry Pi is fairly straightforward, and as long as you have a firewall and aren't port-forwarding the data will be restricted to your home network. You can also setup the firewall on the Pi to allow only local access fairly easily. I did a similar project, and here was my process.

1. Get the Arduino to output the data in a standard way. I used CSV format, but as long as it easy to parse you should be fine.
2. Get the Arduino to make the data available. I ended up using the webserver sketch to generate a page with all of my values, but you could just as easily have it send data instead.
3. Insert the data into a database. I had a cron job that every x minutes would pull the webpage, parse the data, and insert it into the database.
4. Make the webpage. There are a ton of open source graphing projects, and I chose a PHP based one as that is the language I am most comfortable with. Javascript, Python, and CSS can also do it if you prefer.
5. Since I used PHP it was fairly easy to setup a template system. Basically it had some standard include statements, then worked off of $\_GET variables to call a variety of graphs.

---
Tags: programming, datalogging
---


# Question
Title: Didn't have MAC address on Wiznet based ethernet shield (cloned)
My Ethernet shield dont have any MAC address, please tell me how to find the MAC address, I'm stucked! Here is the link from where I bought the Ethernet shield.
http://www.amazon.in/gp/product/B00AXVX5D0?ie=UTF8&at=&force-full-site=1&ref\_=aw\_bottom\_links

# Answer
You can set the Mac address to whatever you want. Many of the example sketches will have one already present, but as long you follow the standard mac format it should be happy (I am using the same shield). In the Examples menu, you should see Ethernet then Webserver where you can find the following example. You can change it a bit, but most of the time I just leave it alone.

```
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

```
> 1 votes

# Answer
Ethernet will work as long as two different machine in the LAN don't have the same MAC address, as @Nathan wrote in his answer.

The MAC address is built by two parts, a prefix which are given to manufacturers of network devices and is called *OUI*, and a suffix that is the node part that manufacturers can use as they wish.

If you want to build an MAC address yourself, use a *Locally administered* address. Universally administered and locally administered addresses are distinguished by setting the second-least-significant bit of the most significant byte of the address. That will make this address to not use any OUI prefix, as that bit is zero on OUI, which minimize the risk of two or more devices have the same MAC address in same LAN.

If you get the same MAC addresses you will get very strange results if they happen to be in the same LAN, I tell you. Been there, done that, and it wasn't fun to debug.

Here are a site that looks up MAC addresses (and generate random ones). But if you want to see which manufacturer have that MAC address, you read it from IEEE and their list.
> 3 votes

---
Tags: shields, ethernet
---


# Question
Title: Arduino-like boards with other microcontrollers
Are there any *Arduino-like* board designs that are ***NOT*** using an AVR chip, but perhaps a chip like the Z80 or the 6502?

# Answer
You have to define what you mean by "Arduino-like" beyond just not using an AVR.

There's the Arduino Galileo using an Intel chip and supports the Arduino development tools, as well as the Arduino Due which is an Arm-based chip.

There's the Netduino which uses ARM chips (STMicro's) and is pin compatible with Arduino shields, but I don't know what the development framework is (other than it being in .NET), though this doesn't necessarily say much because not even all Arduino boards have the same pin compatibility (Nano boards are much smaller, LilyPad Arduinos which are round and semi-flexible, etc.)

Then there are related boards, but don't support the Arduino environment or any pin compatibility (TI Launchpad springs immediately to mind, but pretty much every manufacturer has some sort of demo board or development board for their MCU's).

There's a huge list of Arduino-like boards here (split into levels of compatibility, includes the official Arduino boards).
> 1 votes

---
Tags: avr
---


# Question
Title: USB to TTL with switchable 5v and 3.3v in one
are there any USB to TTL with switchable 5v and 3.3v

i need to use it for raspberry pi and arduino

# Answer
Many 3.3V FTDI based devices are 5V tolerant and will work with both:

Here is general information about logic levels: https://learn.sparkfun.com/tutorials/logic-levels
> 1 votes

---
Tags: usb
---