title: Arduino and visual basic Serial data

text:
# Question
Title: Arduino and visual basic Serial data
I am trying to send command serially through Vb.through serial monitor working fine . But Through VB it not detecting port **My arduino code:**

```
int ledPin = 2; // the number of the LED pin

void setup() {
Serial.begin(9600); // set serial speed
pinMode(ledPin, OUTPUT); // set LED as output
digitalWrite(ledPin, LOW); //turn off LED
}

void loop(){
while (Serial.available() == 0); // do nothing if nothing sent
int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number

if (val == 1) { // test for command 1 then turn on LED
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // turn on LED
}
else if (val == 0) // test for command 0 then turn off LED
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW); // turn off LED
}
else // if not one of above command, do nothing
{
//val = val;
Serial.println("Wrong command");
}
Serial.println(val);
Serial.flush(); // clear serial port
}

```

VB Code

```
Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class Form1
    Shared _continue As Boolean

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.Open()
        SerialPort1.PortName = "COM3"

        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = IO.Ports.Parity.None
        SerialPort1.StopBits = IO.Ports.StopBits.One
        SerialPort1.Handshake = IO.Ports.Handshake.None
        SerialPort1.Encoding = System.Text.Encoding.Default 'very important!

    End Sub

    Private Sub Button1_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("1")
        SerialPort1.Close()
    End Sub

    Private Sub Button2_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("0")
        SerialPort1.Close()
    End Sub

End Class

```

Error I am getting .Arduino port is 3. and configured to port 3 . i dont know why it giving error.

```
The port 'com10' does not exist.

```

This Line added as you said

```
Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Open()
        Dim str As String
        str = SerialPort1.ReadExisting
        Current_Read.Text = str
        SerialPort1.Close()
    End Sub

```

This is working But data not being updating

```
Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Current_Read.Text =SerialPort1.ReadLine
    End Sub

```

# Answer
You've opened the port before you've configured it.
> 1 votes

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


# Question
Title: Controlling mains (230 V) supply up to 5/10 amps using Arduino
I am looking for a simple, low cost solution to control on/off of mains supply to certain equipment. The control will be done using one of the output pin of Arduino Uno.

The input trigger and how to control it is application dependent. e.g. controlling an equipment or controlling supply to section of home but in principle mains control module implementation remains same. So looking for solution which is safe while doing connections as well as while in use in indoor conditions for years.

# Answer
> 6 votes
The PowerSwitch Tail 2 is a great way for experimenters to control mains voltages. It is insulated and internally decoupled, so you only have to hook up 5v, gnd, and a signal line to control it.

This model supports only 120V, but there are also kits for 230V.

image from sparkfun

# Answer
> 2 votes
Playing with mains is dangerous - so best to use a kit designed for that purpose. Be careful with units designed in the US - their safety requirements are a bit different from UK and Europe.

For example the Power Switch Tail kits do not include a fuse - if the appliance being controlled goes faulty and starts drawing a bigger current, the switch could burn up.

Here is one designed with Uk safety features in mind:

http://www.sf-innovations.co.uk/mains-switch-widget.html

---
Tags: power, relay
---


title: Relay activation

text:
# Question
Title: Relay activation
I am posting my simple code here, I wanted to print the Output\_Current Inspite when delay function called.Below is my code.

```
#include <MsTimer2.h>

int Analog_Pin=5;
int newaverage;
float Output_Current;
#define RELAY1  7
#define MAX_TRIP_COUNT  5
float Current_Limit=0.6;
static int Trip_Count=0;
static int Tripped_Flag=1;
int Serial_Status=0;

void TakeReading()
{
  newaverage = analogRead(A5);

//  Serial.print("newaverage:");
  //Serial.println(newaverage);
  Output_Current = 0.0336666666667*newaverage - 17.17;
}

void Chk_Relay_Tripped()
{
  if(Output_Current>=Current_Limit)
  {
    Trip_Count=Trip_Count+1;
    if((Trip_Count>=MAX_TRIP_COUNT) &&(Serial_Status==0))
    {

      Trip_Count=0;

  MsTimer2::set(30000, Relay_Activate); // 500ms period
  MsTimer2::start();
     // Relay_Activate();
    }
    else
      if(Serial_Status==1)
      {
        Serial.println("> MODE");
        Relay_Deactivate();
      }

  }
  else
  {
    Trip_Count=Trip_Count-1;
    if(Trip_Count<0)
    {
      Trip_Count=0;
    }

    if(Trip_Count<MAX_TRIP_COUNT && Serial_Status==1)
    {
      Relay_Deactivate();
      Serial_Status=0;
    }

  }

}

void Relay_Activate()
{
   // MsTimer2::stop();

   for (unsigned long start = millis(); millis() - start < 10000;)
  {
    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;
  }

    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;

}

void  Relay_Deactivate()
{
  digitalWrite(RELAY1,LOW);
 // Serial_Status=0;
}

void Relay_Intialize()
{
  digitalWrite(RELAY1,LOW);
}

void setup() {
  Serial.begin(9600); // set serial speed
  pinMode(RELAY1, OUTPUT); // set LED as output
  //digitalWrite(RELAY1, LOW); //turn off LED

  pinMode(Analog_Pin,INPUT);
  Relay_Intialize();
}

void loop(){
  TakeReading();
  Chk_Relay_Tripped();
  Serial.println(Output_Current);
   //while (Serial.available() == 0); // do nothing if nothing sent
  int val = Serial.read() - '0';
  if (val == 1) { // test for command 1 then turn on LED
    Serial.println("RELAY on");
    digitalWrite(RELAY1, LOW); // turn on LED
    Serial_Status=1;

  }
  else if (val == 0) // test for command 0 then turn off LED
  {
    Serial.println("RELAY OFF");
    digitalWrite(RELAY1, HIGH); // turn off LED
    Serial_Status=0;
  }
  delay(500);
}

```

In above code everything working fine. But as soon as this function called . It wait 30s. after that it will print data. But i wanted to print data on serial monitor even if this function called. Please let me know how can i do this. Main intenstion of code is when current \>1A trip the relay , wait for 30S and connect back. I wanted to print output even in 30S

```
void Relay_Activate()
{

   for (unsigned long start = millis(); millis() - start < 30000;)
  {
    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;
  }

}

```

# Answer
> 0 votes
I read you code as: check the output current every 500ms. If it exceeds the limit more than `MAX_TRIP_COUNT` times, set `Relay_Activate` to run after 30secs. In `Relay_Activate`, write `HIGH` to the `RELAY1` over and over for 30 seconds:

```
void Relay_Activate()
{
  for (unsigned long start = millis(); millis() - start < 30000;)
  {
    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;
  }
}

```

I don't think you really mean to do this, especially as after the 30 seconds you are not writing `LOW` to turn it off. Maybe you mean that after 30 seconds it should start checking the current again?

```
void Relay_Activate()
{
  digitalWrite(RELAY1,HIGH);
  Serial_Status=1;
}

```

What you want is a state machine so that your delays don't hold up your loop. Here is some pseudo code:

```
loop {

* read current
* print out current

switch(current_state) {
  //Normal operation
  case 0:
    * check if tripped
      - if tripped change state to 1
  //Turn on relay
  case 1:
    * turn on relay
    * set state_timer = millis()
    * change state to 2
  //Turn of relay after 30 seconds
  case 2:
    * if millis() -state_timer > 30000 turn off relay
    * change state to 0
}
delay 500ms
}

```

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


# Question
Title: Arduino IDE Unable to detect ZumoMotor.H ( PIXY PET )
recently i trying to make the pixy pet work for my project. (https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/playing-with-your-pet).

I used the given code for the arduino IDE, but i keep on getting this error Arduino: 1.5.7 (Windows 7), Board: "Arduino Leonardo"

sketch\_sep17a.ino:27:24: fatal error: ZumoMotors.h: No such file or directory compilation terminated.

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

The Code, im using, was given by the official maker of the Pixy Pet. Please have a look. ( https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code)

Thank You.

# Answer
> 1 votes
It looks like you need to install the ZumoMotors library.

There's one available at the following link, although I don't know for sure that it's the same one your Pixy Pet requires:

That page includes instructions on how to install the libraries. If you get stuck, there's more help in the official Arduino documentation:

---
Tags: c++, arduino-leonardo, library, arduino-ide
---


# Question
Title: Class TKPotentiometer has no member named 'read'
I am testing a set-up using the TinkerKit shield for Arduino Uno, and a few TinkerKit inputs and outputs. I have an issue with the code provided on the TinkerKit website for the potentiometer component:

```
#include <TinkerKit.h>

// creating the object 'pot' that belongs to the 'TKPotentiometer' class
TKPotentiometer pot(I0);

// creating the object 'led' that belongs to the 'TKLed' class
TKLed led(O0);

int brightnessVal = 0;  // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps
  Serial.begin(9600);
}

void loop() {
  // read the potentiometer's value:
  brightnessVal = pot.read();

  // set the led brightness
  led.brightness(brightnessVal);

  // print the results to the serial monitor:
  Serial.print("brightness = " );
  Serial.println(brightnessVal);

  // wait 10 milliseconds before the next loop
  delay(10);
}

```

I get an error message when compiling:

```
Class TKPotentiometer has no member named 'read'

```

According to this webpage, though, `read` should be a member of the class. Why am I receiving this message?

# Answer
As soon as I finished writing the question, it came to my mind that perhaps I misspelled something, so I looked for a file in the Menu's sketchbook that I could load.

With my surprise, I found the same exact code as I posted, with a little difference:

`pot.read()` was substituted with `pot.get()`
> 1 votes

---
Tags: arduino-uno, potentiometer
---


# Question
Title: Do we need another controller when using ArduPilot?
I'm a newbie on the all Arduino platform and I'm currently building a drone with Autopilot functionality. I've heard about ArduPilot and I'm wondering if that is all I need, in terms of controllers (I'm excluding the ESC, engines, and the rest). Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?

Cheers, r

# Answer
> 1 votes
There are a few key points worth making before answering your question:

* **Ardupilot** has undergone a re-branding and is now known as **APM**; this change was made to reflect that the technology has grown beyond strictly using an Arduino environment. You can see this for yourself at their website.
* The term(s) Ardupilot/APM have been used somewhat interchangeably for both the hardware and software. This can be confusing so I'll refer to the hardware as an "APM Kit"

**Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?**

Yes, 3DRobotics offers APM Kits that are plug-and-play hardware packages with preloaded firmware. They (optionally) supply all of the components needed to operate a small unmanned hobby aircraft including:

* Power module
* Transmitter and receiver for the APM-to-Ground-Station link
* GPS module w/ compass

The user is generally expected to provide:

* Airframe
* Batteries
* Servos
* RC transmitter and receiver
* An additional voltage-regulator/BEC if using high-torque servos
* A computer (groundstation)

However, the unspoken question is:

**How easy is it to setup Ardupilot/APM to work safely and correctly?**

In truth, it takes considerable effort to put together a properly working system. The plug-and-play hardware saves you a great deal of trouble but tuning and operating an RC aircraft requires a different skillset. If you're experienced in RC, this *may* not be a problem.

From experience, you can expect to spend a number of weekends configuring and tuning APM (the software) even if you have a perfectly tuned RC aircraft.

---
Tags: programming
---


# Question
Title: Arduino Yun - not enough i2c & interrupt pins?
I'm trying to build a small personal weather station. The rain sensor, and wind speed sensor use interrupts. The barometric sensor uses i2c SDA and SCL.

Reading the Arduino Yun manual, it says there are 5 interrupt pins, but 2 of them are SCL/SDA (pins D2 and D3), and 2 of them are serial comms between Linio and the 32U4 (pins 0 and 1).

This leaves me with 1 interrupt pin left (pin 7).

Is there a work around to get my 2 digital sensors AND SDA SCL pins connected?

If I do use pins 0 and 1 (Linux serial), what do I risk? I will need to use the Bridge to relay information to the internet.

# Answer
Any of the port B pins on the ATmega32u4 can interrupt on pin change. Unlike the external interrupts however, these pin change interrupts share the same interrupt vector. So in the interrupt routine you have to work out which one fired.

The port B pin change interrupt is not support by the Arduino core library so you have to download a third-party library. This one seems fairly recent:

https://code.google.com/p/arduino-pinchangeint/

Then you connect your two interrupt lines to spare Port B pins and monitor for pin changes.
> 2 votes

# Answer
OR the interrupt lines together so that you only need 1 external interrupt. Then when an interrupt is triggered, poll the devices until you find the one that triggered the interrupt. If the interrupt outputs are open-drain then you can wired-OR them together, otherwise you will need something like the 74LVC32 to OR the push-pull outputs together.
> 2 votes

---
Tags: arduino-yun, i2c, digital
---


# Question
Title: Problem connecting Arduino Uno with Wifi and NFC
I'm new here and also new to Arduino.

I've got a rather specific problem and I've posted to the official Forum on arduino.cc two days ago (original Post)

Sadly, I've yet to recieve any help and since it's a project for work, theres a (loose) schedule. So I've decided to post it here as well.

If you have some ideas, it'd be really great!

Also, if I've posted this question without acknowleding some forum rules please tell me so that I can write better posts in the future ;-)

Regards,

Patrick

**Edit:** The original Posts as Text :-)

**Post # 1**

Hello Guys,

this is my first time posting in the forum since I'm new to Arduino, so please be kind smiley-wink. Me and a colleague of mine have been given a Project to create with arduino hardware.

The Project is, that you should be able to read NFC tags with the arduino and send them to a server to be checked and eventually being written into a db.

The hardware: Arduino Uno R3 (funduino.de/index.php/shop/product/view/2/4) Adafruit CC3000 (www.adafruit.com/products/1469) Adafruit PN532 (www.adafruit.com/products/789) Stepper Motor (not yet included and not relevant for the problem)

Sorry about not using hyperlinks, but the forum says I'm not allowed to post more than 2 links at once...

Now on to the Problem: When we're using the shields separately (meaning connecting the arduino to either of the shields by itself), the shields work fine. The cc3000 gets a connection and the PN532 reads cards. Now we've tried to stack them together for live use. That's where the trouble starts...

If I connect the PN532 5V to the arduino 3.3V and CC3000 VIN to 5V arduino, the shields both do what they should with separate example sketches ('readMifare' and 'buildTest').

If I put my sketch in (which combines both of those sketches and some other stuff) and comment out the initialization of either the PN532 or the CC3000, the other shield works.

Now if I try to use both, the CC3000 and the PN532, the CC3000 tries to initialize, but falls into a loop of restarts. I've read that that (possibly) is because of the lack of power supply. (I've connected a 12V wall-wart by the way and it didn't work with that either)

The manual says, that the CC3000 needs 5V, but can work on 3.3V too (though I didn't find a source to explain how) and the PN532 needs 3.3V to run.

Am I doing something wrong, or is it a problem with the arduino? If I'm doing it wrong, how am I connecting these parts correctly?

I really am not that good with electronics and didn't find a sollution to my problem nearly a days worth of searching the net. For your understanding I'll post the script I'm using and some pictures of the board setup. Thanks in advance for ANY help you guys can give me (even if it's just good guide for problems like mine) ^^

Regards, Patrick

The part of the sketch that initializes the components (and also where the CC3000 gets stuck...) Code:

```
//WLAN-Libraries
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"

//NFC-Libraries
#include <Wire.h>
#include <Adafruit_NFCShield_I2C.h>

//Motor-Libraries
#include <Stepper.h>

//NFC-shield PINs
#define IRQ   (2)
#define RESET (4)  // Not connected by default on the NFC Shield

Adafruit_NFCShield_I2C nfc(IRQ, RESET);

```

//Motor-settings

```
const int stepsPerRevolution = 180;  // change this to fit the number of steps per revolution
                                     // for your motor

Stepper Motor(stepsPerRevolution, 6,7,8,9);  // initialize the stepper library on pins 8 through 11:

```

//Wifi-settings

```
// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIV2); // you can change this clock speed

#define WLAN_SSID       "mySSID"           // changed for your convenience
#define WLAN_PASS       "myPassphrase"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client www;  //defines how we will refer to the cc3000 connection object

// What page to grab!
#define WEBSITE      "10.2.10.170"  //NOTE: CC3000 doesn't seem to like the default localhost address of 127.0.0.1 - need to enter actual IP
#define WEBPAGE     "/index.php"

//this is the counter that will be used for uploading data
long pollCounter = 1;

//used for storing data for upload
//set it to the data type that suits your data
int
  NFC_ID, Session_ID, UID_final;

//used for commands received from base station
int
  command_open, command_close;

  boolean pollFlag = false;         //tells the sketch whether to poll or not

//declare a variable to hold a numeric IP address
//can be overridden below if you use lookup
  uint32_t ip = (192L << 24) | (168L<<16) | (1<<8) | 13;

/**************************************************************************/
/*!
    @brief  Initialization of the modules (Motor, Wifi, NFC-Reader)
*/
/**************************************************************************/

void setup(void)
{

```

//Set up the Motor for the lock

```
  // set the Motor speed at 60 rpm:
  Motor.setSpeed(60);

```

//Set up the Wifi module

```
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialize the Wifi module */
  Serial.println(F("\nInitializing..."));                 //<======== Here the CC3000 gets stuck in a loop
  if (!cc3000.begin())                                          //                          when both shields are connected
    {
      Serial.println(F("Couldn't begin()! Check your wiring?"));
      while(1);
    }

  cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
    {
      delay(100); // ToDo: Insert a DHCP timeout!
    }

  /* Display the IP address DNS, Gateway, etc. */
  while (! displayConnectionDetails())
    {
      delay(1000);
    }

  cc3000.printIPdotsRev(ip);

```

//Set up the NFC module if (pollFlag == true) { nfc.begin();

```
        uint32_t versiondata = nfc.getFirmwareVersion();
        if (! versiondata) {
          Serial.print("Didn't find PN53x board");
          while (1); // halt
        }
        // Got ok data, print it out!
        Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
        Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
        Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

        // configure board to read RFID tags
        nfc.SAMConfig();

        Serial.println("Waiting for an ISO14443A Card ...");
  }
  else {
     Serial.println("Failed to initialize NFC-Reader... Sorry...");
  }

  }

```

Hope I'm not messing up the image-uploads... (I kept the wiring-colors where I coul for you to see the connections easily)

The boards connected via cables (both separately working) www.directupload.net/file/d/3740/j3y3tx38\_jpg.htm

The boards put together www.directupload.net/file/d/3740/yb9q6qla\_jpg.htm

The boards connected together with the Wifi in the picture. (You can't see the LED on the CC3000 light up, but I swear it does smiley-wink) www.directupload.net/file/d/3740/uorksjrj\_jpg.htm

**Post # 2**

Ok, I got myself a multimeter today to measure if it is really a problem with the power supply.

With the NFC-Reader running I measured 4.85V on the 5V-Pin and 3.32V on the 3.3V-Pin. This means, that the CC3000 should have enough Power to run.

So I'm now looking for a possible address collision in the libraries (specifically I2C- and SPI-collisions). As I'm still new to this, help is really appreciated.

**Edit #2:**

Morning everyone! What I've found out since yesterday is, that the PN532 uses I2C while the CC3000 uses SPI to communicate. When I looked through the libraries I found out that the PN532 includes Wire.h which gets its address at "nfc.begin();"

In the begin-function in Wire.cpp there is an address transmitted to the function, but I can't find it's source. Is it possible that that address collides with the one the CC3000 uses?

When I uploaded an I2C-Scanner to the UNO, it said that the only device fount is the PN532 on address '0x24'.

I don't really know what to do with that info though, since there are more libraries being included (like which in term calls others) and I cant even find these on the Mac I'm working on at the moment...

**Edit #3:**

The problem has been solved in the arduino.cc forum. The SRAM was overflowing, but applying the F()-macro to the strings being printed solved the issue! (Just in case someone has similar issues ^^)

# Answer
> 0 votes
The problem has been solved in the arduino.cc forum. The SRAM was overflowing, but applying the F()-macro to the strings being printed solved the issue! (Just in case someone has similar issues ^^)

---
Tags: arduino-uno, wifi, i2c, library
---


# Question
Title: If I connect a battery to the vin pin on the arduino, will the 5V pin be activated?
My wording might be a bit confusing, if I plug an 8 volt battery into Vin, will the arduino be powered and will the 5V pins work?

# Answer
Yes, that's what the Vin pin is for: unregulated voltage or a voltage higher than 5V. Then the 5V pin will be at 5V, regulated by the on board regulator. You would only connect a source to the 5V pin if the source is already a regulated 5V.
> 3 votes

# Answer
> * **VIN.** The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

source
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: How to implement setSyncProvider and verify it is working with PC
I'm trying to retrieve / synchronize time from PC using this Time lib function:

```
setSyncProvider( requestSync);  //set function to call when sync required

```

It sends ASCII BEL (07) character to PC, but I'm getting no response using `Serial.available`. What am I missing?

Do I have to run a specific app on the PC to get a response? The docs do not specify that.

# Answer
> 2 votes
Yes, you'll need something running on the PC which is monitoring the serial port, and which will provide a response in the appropriate format.

The download on **this page** contains a Processing sketch which will do this for you. After you've unzipped it, look in `Time/Examples/Processing/SyncArduinoClock`. Open the sketch in Processing, run it, and then start your Arduino.

If you're not familiar with it, Processing is a free programming language / environment based on Java. It's aimed largely at beginners and non-programmers, and is quite commonly used for communicating with Arduino projects via Serial. You can download it here:

---
Tags: arduino-uno, time
---


title: Webserver with Arduino Yun without SD

text:
# Question
Title: Webserver with Arduino Yun without SD
I'm trying to set up a simple web-server with Arduino Yun without an SD card, i.e via REST, if I understood it right (I'm new to some of these stuff). I want to be able to "get" data (sent by Arduino) through a jQuery script and show the user a formatted HTML page.

Here I provide you a simplified version of my Arduino sketch:

```
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

const byte internalLED = 13;

YunServer server;

void setup() {
  pinMode(internalLED, OUTPUT);
  digitalWrite(internalLED, HIGH);     // Turn the led on to advise about bridge begin in progress
  Bridge.begin();          // Let's activate the Yun Bridge...
  ledBlink(150);           // ...bridge activation done (user sees a blink)
  // server.listenOnLocalhost();       // Listen for incoming connection only from localhost (no one from the external network could connect)
  server.begin();          // Let's acrivate the Yun server...
  ledBlink(150);           // ...server activation done (user sees a blink)
}

void loop() {
  YunClient client = server.accept();  // Get clients coming from server
  if (client)                          // Is there a new client?
  {
    client.print(77);                  // Send a "77" to client (e.g. browser)
    client.stop();                     // Close connection and free resources.
    ledBlink(500);
  }
  delay(50);
}

void ledBlink(int delayTime) {
  digitalWrite(internalLED, HIGH); // Turn (or keep) the LED on
  delay(delayTime);
  digitalWrite(internalLED, LOW);  // Turn (or keep) the LED off
  delay(delayTime);
}

```

My Arduino Yun is connected via WiFi with static IP (192.168.1.98) to the same network of my laptop, and they can ping each other. Right now, if I insert into my browser the address

```
http://192.168.1.98/arduino/whatever

```

I correctly receive a simple «77» (no quotes or \r\n)

But I cannot "get" it when opening the page get\_test.html (which is on my harddisk, not in the SD):

```
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $.get("http://192.168.1.98/arduino/whatever", {}, function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
</script>
</head>
<body></body>
</html>

```

This is strange to me because this html code works if I change the address inside the "get" request with https://dl.dropboxusercontent.com/u/12389503/demo\_test.txt which consists only of a «21» (no \r\n). The problem is I don't even receive the alert when the address is the IP of Arduino, but the board is receiving the request since I can see the led blinking once, as expected. I'm running out of tests, any suggestion is welcome.

# Answer
> 0 votes
Whenever making ajax calls from/to different hosts (as your pc and the yun) you should use JSONP.

---
Tags: arduino-yun, web-server
---


# Question
Title: how to push data from an Arduino pin to Bluetooth module
I'm writing a software that can receive data from Arduino via Bluetooth. My software is pretty fine now, at least it can pair with my hardware but when I try to test whether it can receive data via Bluetooth, I'm stuck. My Arduino receives temperature readings from a sensor at Analog pin 0. My Bluetooth module HC-05 connects with Arduino at Digital 0 and 1 (RX and TX pin respectively, as default). I don't know how to push data from Analog pin 0 to the Bluetooth module. Thanks in advance for any suggestion.

# Answer
> 1 votes
The HC-05 looks like like any other terminal to the Arduino so any serial operations that you would use for a wired terminal can be used with the HC-05. See the HC-05's manual for how to set it up initially. Note that HC-05s don't forget their settings and they have no reset command to put them into a known state, so write down your settings for your future reference.

```
- Read the analog pin value;
- Convert the value into whatever physical units you require;
- Print the result with Serial.print() or Serial.println()

```

Edit: You wrote that your HC-05 is connected to Digital 0 and 1, but you created your SoftwareSerial, `mySerial`, to transmit on Digital 11. In that case your HC-05's receive pin must be connected to Digital 11.

# Answer
> 0 votes
It's my code. Can anyone suggest anything wrong with it if my idea is to push data from Analog pin 0 to Digital pin 11, which is the Tx pin on Arduino connecting to Rx pin on HC-05?

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
int tempPin=0;

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

void loop()
{
 float reading = analogRead(tempPin); // reading on tempPin
 float voltage = reading*5.0/1024.0; // the resolution of a pin is 10 bit,
 float tempC = voltage/0.01; // 10mV = 1 Celcius
 mySerial.write(tempC);

 delay(3000);
}

```

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


# Question
Title: How can I make ultrasonic sensors resistent to splashes and dirt?
I wasn't sure where to ask this question, but since it's actually an Arduino project, I'll try it here.

I want to upgrade my old car with ultrasonic parking sensors: I've already bought HC-SR04s as sensors and started to play on my breadboard.

But what I'm still unsure about: if I place them in my car's rear bumber, how can I make them resistent to rain or dirt or something like that? As pictured on Wikipedia, the sensor is covered with a small piece. But what could I use to cover the holes in the bumper, without interfering with the ultrasonic measuring?

# Answer
I don't think you'll be able to cover that sensor in a way that will still allow it to work. There are waterproof ultrasonic sensors out there, here's one on Amazon, for example.

The other thing you might want to look at is IR instead of ultrasonic. That's easier to weatherproof since the IR emitter/receiver are already covered. You'll probably have less range with IR, though.
> 2 votes

# Answer
Maybe at a minimum for testing you could point the sensor downwards and then use a reflector to discourage water and dust. Something like: http://letsmakerobots.com/content/cyperbolic-reflector-review
> 1 votes

---
Tags: sensors
---


# Question
Title: Resurrecting a fried Arduino (Bluno) USB port
Slightly distractedly, I went and connected 5V to the 3.3V pin on my DFRobot Bluno (the pins are right next to each other!)

The magic smoke leaked out of the AMS1117 3.3V regulator in a neat little puff. The sketch that was loaded on the board still runs fine, but the Bluno is no longer recognised by my Macbook Pro when I plug it into USB (I have tried different ports and different cables; they're all fine—it's the USB on the Bluno that's fried.)

In an attempt to repair it, I've replaced the AMS1117 (check the third paragraph of that tutorial—ha!) with an LF33ABV; this went well and I'm now getting a stable 3.3V on the 3.3V pin. Check out my handiwork:

However, the Bluno still isn't being recognised by the USB ports on my Mac.

Is there another way to upload new sketches to the Bluno? Theoretically you can do so over BTLE, but you need another Bluno to act as the "peripheral" and I don't have one to hand. I have various other Arduinos laying about if that helps.

# Answer
> 4 votes
Upload via ICSP. See those six pins next to the regulator you so expertly tacked on? Those are the ICSP pins. You'll need a second controller or programmer to do it.

http://arduino.cc/en/Tutorial/ArduinoISP

---
Tags: uploading, bluetooth
---


# Question
Title: Minimum current or power for Arduino Mega
I wanted to use the cigarette lighter receptacle of a car as the power supply for the Arduino Mega. From 12 V, I will convert it to a 7 V supply, but my problem is, what must be the minimum current or electrical power to be fed into the Arduino Mega?

And are there any things I have to do to the Arduino Mega 2560 for it to function well in supplying it a 7 volts supply from a car?

# Answer
> 2 votes
The Arduino's voltage regulator is rated for a suggested input range of 7 to 12 volts. Automobile power will range from slightly below 12 volts to over 13 volts, so stepping it down to 7 volts is a good idea.

Looking at the data sheet it doesn't say how much current it draws. Since it uses a linear power supply it will likely draw the same amount of current regardless of the input voltage, and simply waste the power from a higher input voltage as heat.

The power from a car cigarette lighter should have plenty of current, so your proposed setup should work just fine. Is your 7 volt supply regulated?

Note that you could also use a "buck" style switching power supply to feed 5 volts directly into the 5V line. There are several buck style power supplies on the market for less than $10 US that will provide up to 3A of regulated 5 volts.

---
Tags: arduino-mega, power, current
---


title: need help hooking up an oled display

text:
# Question
Title: need help hooking up an oled display
recently i bought this oled display .

http://www.wvshare.com/product/0.96inch-OLED-A.htm

how can i connect it with arduino . Driver Chip is SSD1306 . Supported Interface are 3-wire SPI, 4-wire SPI, I2C . it's can display two colors Yellow and Blue.

i need some guidance on how to hook it up with arduino lets say using i2c protocol . and is there any existing library ?

Note : on the wvshare website there's only code sample for STM32 Microcontrollers .

# Answer
it's working with u8glib. but i am using 4-wire SPI.

constructor for U8GLIB

```
U8GLIB_SSD1306_128X64 u8g(13, 11, 10, 9,8);

```

Pin configuration was

```
Arduino -   Oled Display
13 -    CLK
11 -    DIN (SI)
10 -    CS
9 - D/C (A0)
8 - RES

```

the reset pin is required. i used 3.3v arduino pin for vcc .
> 2 votes

---
Tags: i2c, display
---


# Question
Title: Receiving two-byte int values over serial
I am using Python **smbus** `write_word_data` method to send int values from a Raspberry Pi to an Arduino using I²C.

This seems to be the correct method.

When I send values from 0-255, I see the following in my Arduino serial monitor

> 0,0,0
> 0,1,0
> 0,2,0
> 0,255,0

Sending 256 I see:

> 0,0,1

For 257 I see:

> 0,1,1

Etc, etc...

My question is, how would I modify the following Arduino code to properly 'reconstitute' the int values, and then send them back to the RPi?

```
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
bool newData = false;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
  Serial.println("Ready!");
}

void loop() {
  Serial.println(receivedValue);
  newData=false;
}

// callback for received data
void receiveData(int byteCount) {
  while(Wire.available()) {
    newData = true;
    Wire.read();
    if(Wire.available() == 2) {
      receivedValue = Wire.read() | Wire.read() << 8;
    }
  }
}

// callback for sending data
void sendData() {
  Wire.write(number);
}

```

# Answer
> 2 votes
```
void receiveData(int byteCount){

  // Looks like your number is sent in a 3 byte packet
  if (bytecount == 3)
  {

    // Discard first number as it is seemingly alway zero
    Wire.read();

    // Read low byte into rxnum
    int rxnum = Wire.read();

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    // Send back
    sendInt(rxnum);

  }

}

void sendInt(int num){

  // Uncomment below if you want so send back in same format
  // Wire.write(0);

  // Send low byte
  Wire.write((uint8_t)num);

  // Send high byte
  num >>= 8;
  Wire.write((uint8_t)num);
}

```

# Answer
> 1 votes
Ir seems to me that there is something wrong with the Python Raspberry Pi code. What you show is 3 bytes of data, not 2. That's wrong.

If you're writing a 2 byte word, I would expect to see 2 bytes, not 3. You might want to post a question on the Raspberry Pi forum to get help resolving **THAT** problem first.

If you're stuck with the sending code you have, then here's what you would do.

Looking at your data, the first byte is always zero. You want to discard it.

The second byte is your low order byte, and your third byte of data is the high order byte. You need to do some juggling to get the data into the correct byte order, like this:

```
void readWordWithPadding()
{
  if (Wire.available()<3)
  {
    newData = false;
    return;
  }
    newData = true;

  Wire.read(); //Throw away the filler byte
  int lowByte = Wire.read();
  int hiByte = Wire.read();

  //Shift the high byte by 8 bits and add in the low byte
  receivedValue = (hiByte << 8) + lowByte ;
  return;
}

```

# Answer
> 1 votes
Unless (and until) your application needs high enough data rates that you need to make the most efficient use possible of your data channel (or you're talking to an inflexible hardware device that dictates the data protocol), you'll save yourself a lot of headaches by sending human-readable strings, something like:

```
x= 12345, y=   -32
x=   432, y=-33221

```

You can reconstitute them at the other end with with `atol()`, log them to a file, be able to understand them later, and see instantly whether the sender sent what you expected it to. Don't optimize until you have to; you may not have to.

---
Tags: serial, i2c, python, raspberrypi
---


title: Over voltage on Arduino and Ardumoto

text:
# Question
Title: Over voltage on Arduino and Ardumoto
I am using Arduino Leonardo and Ardumoto to drive 2 12v motors running at 1.3 amps each.

I purchased a rechargeable battery of 12V with 5AH

I first started by plugging in the battery to the Arduino via the barrel jack. Arduino then sparks and is fried.

I read somewhere that I wasn't supposed to hook it up to the Arduino and to hook it up to the VIN ports in the Ardumoto. I purchased a new Arduino and plugged in the Positive and negative from the battery to the ports and now the Ardumoto board fried (copper lining on board burnt off).

I'm reading online and from what I've gathered, the Ardumoto can handle a max of 18 volts and a maximum of 2 amps per each output. I'm obviously missing something and would not like to fry my boards next time.

Please assist?

# Answer
> 1 votes
From your description, everything *should* be wired correctly. It should not have failed.

Unfortunately, testing this sort of thing with a 5 amp-hour lead-acid battery is not a great way to get started, since a battery that large can source a *lot* of current, and doing anything wrong will likely produce immediate and spectacular failure.

Really, the only think I can think of is that you have the polarity of the output lugs/pins on the battery backwards. Buy a $5 multimeter, and check them.

---
Tags: motor, arduino-leonardo, arduino-motor-shield
---


# Question
Title: ULN2803 and common-anode RGB strip; how am I doing it wrong?
I'm not super-good with my electrical foo. But I've managed to get a ULN2803 wired up to give the +12v that my RGB LED strip needs. The strip has four connectors, RGB and common +12v.

My concern is that (I think) the Arduino is shorting out- while the Arduino processes my loop, the USB connection dies and the RX/TX LEDs light up.

Here's how I am wiring things. I'm currently powering the Arduino through USB, so when I say "power supply" I'm referring to the +12v supply I'm using.

* power supply ground to Arduino ground, ULN2803 pin 9.
* power supply +12v to 2803 pin 10, common +12v on LED strip.
* arduino output pin 11 to 2803 pin 1
* 2803 pin 18 to green LED strip

So, that's my circuit. It works- the strip lights up. But again, I think it's wrong. How do I correct it?

# Answer
> 1 votes
The COM pin on the ULN2803 is for protection when driving inductive loads, which means motors, solenoid. For an LED, nothing needs connect to COM.

The chip you are using is a low side driver. That means it connects between the low side of the load (your LED) and ground. When you drive +5 to the input pin, the transistors will conduct, connecting the output pin to ground.

So for your LED strip make the following connections:

* Arduino output pin -\> driver input, 1B = pin 1
* driver output, 1C = pin 18 -\> LED strip R G or B
* +12 -\> LED strip common power
* ground -\> GND = pin 9

Without the ground connection on the driver chip, no surprise that odd things happened. There are diodes designed to protect the input and output pins (see chip data sheet). Without the ground connection to the driver chip, the input protection diode might have been conducting back to the microcontroller output pin.

---
Tags: led
---


title: Sensing busy-ness of a restaurant?

text:
# Question
Title: Sensing busy-ness of a restaurant?
I'm planning on an Arduino project for a restaurant I work at that would require determining how busy it is at any point in time, but I'm not sure how I would go about procuring this information.

I don't have access to any of their IT systems or I would have simply pulled the data from their till systems.

I was thinking perhaps measuring the ambient sound of the restaurant as it gets quite loud during peak time but that could be thrown off when the music volume is adjusted.

# Answer
> 1 votes
There are a few ways to go about it but my initial thoughts would be to detect people entering (and exciting) the front door and simply keep a running total.

Motion detector http://www.adafruit.com/products/189

IR beam detectors http://arduino-info.wikispaces.com/InfraredBeamPair

---
Tags: sensors
---


# Question
Title: Use Arduino's PWM to control motor direction?
I'm looking for a way to allow Arduino to control a motor using PWM.

So far what I have gathered is that using Arduino's PWM sets the digital value of 255 to 5v and 0 to 0v.

However what I am looking to do is to set the motors to stop at 2.5v, move forward as it approaches 5v and move backwards as it approaches 0v.

Any suggestion on how I would go about accomplishing this will be highly appreciated.

# Answer
> 6 votes
You seem to have misunderstood PWM here. It's actually a digital signal which is constantly pulsing on and off very quickly (several hundred times per second). You don't actually change the output voltage at all -- it's only ever HIGH or LOW (+5v or +0v). The thing you change is how long the signal is HIGH for on each pulse.

This page gives a deeper explanation: http://arduino.cc/en/Tutorial/PWM

When you're controlling a DC motor, this approach is actually better than varying the voltage. The constant pulses still make the motor turn at an adjustable speed, but without losing torque. PWM is also useful for controlling the brightness of LEDs, which don't respond so well to changes in current/voltage.

To address your original motor control question, there's no sensible way to change the motor's direction using the PWM value. You will need some additional circuitry which is able to reverse the polarity of the connections to the motor (meaning your PWM value just controls speed, and doesn't care about direction).

An H-bridge is the usual approach for this. Here's a fairly good tutorial which covers the basic principles: http://www.instructables.com/id/H-Bridge-on-a-Breadboard

Obviously you'd need to modify it for use with your Arduino project. The push switches could easily be replaced by digital signals from a couple of Arduino pins. The motor's power supply would be controlled by the PWM signal. You'll need an extra transistor for that, because you can't safely power the motor directly from an Arduino pin.

# Answer
> 0 votes
You can use a MOSFET to control a DC motor directly from an Arduino. Using a H-Bridge is another way to control DC motors. Probably the L298N is the most used one but I prefer TB6612FNG. It's a bit expensive, but uses much less current and is something with a better response.

You will find tons of tutorial with both modules.

Good luck!

# Answer
> 0 votes
continuous rotation servo demonstrates a different approach of using PWM.

A continuous rotation servo is a standard servo modified in 2 ways. First the "position feedback" in the servo is disconnected and set to always read as if the servo was in the center position. Second the "stop" which physically prevents the motor from turning 360 degrees is removed.

Then if you set the servo to 0 degrees it rotates fast in one direction if you set it 180 degrees it move in the opposite direction.

More information:

---
Tags: motor, pwm
---


# Question
Title: Two 300RPM 12V DC motors connected to arduino motor shield r3 power supply
I have two 300RPM 12V DC motors connected to arduino motor shield r3 that is mounted on arduino uno board.

Problem is my motors runs very slow some times not even running.

After googling I found I need to use external power supply. I did supplied 9 volt dc power to arduino motor shield r3. But still motor is running very slow what could be the issue.

My other questions.

When supplying power to arduino motor shield r3 via external power supply pins do I need still need to provide separate power to arduino uno board via power jack.

Can I use 9 volt dc for arduino uno board and another 9 volt batter to arduino motor shield r3.

Is single 9 volt batter enough for running two 300RPM 12 dc motor.

My circuit.

My program

```
          void setup() {

          //Setup Channel A
          pinMode(12, OUTPUT); //Initiates Motor Channel A pin
          pinMode(9, OUTPUT); //Initiates Brake Channel A pin

          //Setup Channel B
          pinMode(13, OUTPUT); //Initiates Motor Channel A pin
          pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

        }

        void loop(){

          //Motor A forward @ full speed
          digitalWrite(12, HIGH); //Establishes forward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 255);   //Spins the motor on Channel A at full speed

          //Motor B backward @ half speed
          digitalWrite(13, LOW);  //Establishes backward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 123);    //Spins the motor on Channel B at half speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

          //Motor A forward @ full speed
          digitalWrite(12, LOW);  //Establishes backward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 123);    //Spins the motor on Channel A at half speed

          //Motor B forward @ full speed
          digitalWrite(13, HIGH); //Establishes forward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 255);   //Spins the motor on Channel B at full speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

        }

```

# Answer
The external power of the shield is connected to the VIN pin, so it will power the Arduino via that. (vin goes to the voltage regulator that will provide the 5v the arduino needs).

You can connect two batteries in parallel to provide mode current.

But since they are 12v motors, they would need 12v to run at maximum power. 9v is a lot less than that.
> 2 votes

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


title: GSM arduino to webservice not working

text:
# Question
Title: GSM arduino to webservice not working
I have setup a arduino with a SIM300 based GSM board. I have

> Tx of Arduino connected to the Rx of GSM board
>
> Rx of Arduino connected to the Tx of GSM board
>
> Gn of Arduino connected to the Gd of GSM board

The GSM has a Vodafone 3g sim, activated with 3g. The GSM board has 2 LED's, one remains `ON` and the other blinks ever 4-5 seconds. Which I guess means that its configured to work with the SIM.

I then run the following code.

```
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  mySerial.begin(9600);

  Serial.println("Serial ports initialized");

   delay(500);
   Serial.println("AT+CGATT=1");
   delay(500);
   Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\",\"0.0.0.0\",0,0");
   delay(500);
   Serial.println("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
   delay(1000);
   Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
   delay(2000);
   Serial.println("AT+CIICR");
   delay(5000);
   Serial.println("AT+CIFSR");
   delay(500);
   Serial.println("AT+CIPSTATUS");
   delay(500);
   Serial.println("AT+CDNSORIP=1");
   delay(500);
   Serial.println("AT+CIPSTART=\"TCP\",\"http://myec2DNS-us-west-2.compute.amazonaws.com:myportnumber/mywebservice/myreques/Authentication/Request?identity=somecode&identityType=sometype\",\"myportnumber\"");
   delay(500);
   Serial.println("AT+CIPSEND");
   delay(500);
   Serial.println("AT");
}

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

```

On cutecom I get te following

```
Serial ports initialized
AT+CGATT=1
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET","0.0.0.0",0,0
AT+CDNSCFG="8.8.8.8","8.8.4.4"
AT+CSTT="TATA.DOCOMO.INTERNET","",""
AT+CIICR
AT+CIFSR
AT+CIPSTATUS
AT+CDNSORIP=1
AT+CIPSTART="TCP","http://myec2DNS-us-compute.amazonaws.com:8080/myservice/mycommand/Authentication/Request?identity=%somecode&identityType=1","8080"
AT+CIPSEND
AT

```

When I run \`tail -f /var/lib/tomcat7/logs/localhost\_access\_log.2014-09-20.txt' on my webserver, I get nothing from the arduino.

What am I missing here ?

# Answer
it seems like you are using the wrong serial interface. I see `Serial` and `mySerial`.

After `mySerial.begin()` you write to `Serial`, not to `mySerial` which runs on pins 10 and 11.

What's when you send the AT Commands from your Serial connection to the Arduino? It Should redirect them to the GSM board.
> 1 votes

---
Tags: arduino-uno, gsm
---


title: Salvaged Stepper Motor Blues

text:
# Question
Title: Salvaged Stepper Motor Blues
So recently my company threw away some rather large and reasonably old laser printers. One was a LaserJet 9050dn the other was a Epson printer/scanner combination. Being a little industrial I thought let me salvage them and brought them home.

I managed to salvage a couple of stepper motors. However I am having huge trouble is getting them to step properly. So lets get into the details.

Components used:

* 1x Freetronics eleven (Arduino Uno compatbile)
* 1X H-Bridge driver shield(Freetronics rated for 40V/2A max).
* 1X Old scanner power supply which has a output of 24V/2A.

Currently there are two stepper motors I am interested in using. They have the following part numbers:

* 1X MITSUMI M42SP-4N
* 1X Minebea-Matshushita 17PM-J212-G2ST

Just to keep this short I am going to focus on the Minebea-Matshushita 17PM-J212-G2ST. I have been unable to find exact matches on these serial numbers when looking for datasheets but I have managed to find the following sheets on the net.

1. Minebea-Matshushita 17PM-K datasheets found from Minebea. However I cant match the model exactly.
2. Minebea Stepper Motor Information & Specifications also carries some useful information.

So it appears that these are 24V steppers(in both cases). The Minebea-Matshushita 17PM-J212-G2ST appears to have a step angle of 1.8 degrees which should give me 200 steps per revolution. I have not been able to find the current needed to drive this motor but judging by the looks of things it will be between 0.8A and 1.2A.

I then used my multimeter to find the pairs of wires. It has 4 wires coming out (Bipolar motor I guess). The colours of the wires are red, yellow,orange and blue. First pair was red and yellow with red being positive/anode. Second pair orange blue with orange positive/anode side.

I wired my power supply into my h-bridge and started using the recipe and quickstart found at the freetonics site. This is where the frustration begins. When asking the motor to do one complete revolution(360 degrees) it does more than 360 degrees at times and other times it does less. I tied a cable tie to the motor so I can confirm it.

So I tried the one-step-at a time sketch to see if I can troubleshoot it. Here is what I have noticed. The steps are mostly correct one step at a time clockwise however every now and again it will jump counter clock wise and then clock wise again. I suppose you can call it a jitter.

Interestingly both these motor show the same behaviour pretty good step action just every 25 degrees or so a jitter. So I suspect that this might not be bi-polar motors but uni-polar? This blog entry points me to believe that this might be the case. However the datasheet in this case points to a M42SP-7.

So my question would be simple how do I figure out if they are bi-polar or uni-polar?

Can someone help me with a proper datasheet?

Any tips would be really appreciated.

Update:

Note that I can get both motors to step clock-wise and counter clock-wise I just cant get them to do a whole 360 degrees without a jitter. Based on the Wiring Mitsumi stepper ( M42sp-4np) with arduino blog it appears that the Mitsumi is a uni-polar motor with a 2-2 phase excitation. What stumps me is that the wires are paired thus it must be bi-polar?

So last night I tried 2-2 phase excitation with the MITSUMI M42SP-4N and it appears to be solve the problem with this motor in particular. From early observations the motor now steps without jitter, however it was late so I will need to confirm this.

I was previously using 1-1 phase excitation i.e.

```
Step number: 1a 1b 2a 2b
1            1  0  0  0
2            0  0  1  0
3            0  1  0  0
4            0  0  0  1
5            1  0  0  0

```

When using 2-2 phase excitation I get a more steady step however this needs to be confirmed a bit more:

```
Step number   1a 1b 2a 2b
1             1  0  0  1
2             1  0  1  0
3             0  1  1  0
4             0  1  0  1
5             1  0  0  1

```

Just some added observations. The headache continues but I am learning a LOT about steppers motors.

Update:

Not a 2-2 phase excitation these are definitely bi-polar. I am currently watching the Minebea-Matshushita 17PM-J212-G2ST do 360 degrees both clock and counter-clockwise. I hooked them up to a 12V/1A power supply both motors are running smoother and cooler and stepping relatively jitter free. I suspect the whole issue is a lack of a proper data-sheet.

Will update as things progress and once solved add pictures and sketches so the next lucky sod wont loose as much hair as me.

Update:

Thanks to Chris who made me look at the sketch in detail again. These motors seem to have a minimum rpm of sorts. I was trying to go for a really slow rpm under 5rpm at this speed these motors show the jitter effect. However when moving the speed to 10rpm and up no jitter.

# Answer
> 3 votes
Keeping this here for future reference. It appears these motors have a minimum RPM of sorts and running them on a lower RPM causes the jitter effect described above.

Like I mentioned in the updates when running at 10RPM or above these motors seem to perform very nicely.

Update: I recently bought a ADAFruit motorshield and I am getting much more stable results with this shield and the stepper motors. I am even running them off 6V and they are working perfectly even at lower rpm.

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


title: MMA7361 readings deviate a lot

text:
# Question
Title: MMA7361 readings deviate a lot
This is what I get using a MMA7361 breakout board (just the IC, no resistors or capacitors). The IC is powered using arduino nano's 3v3 pin.

The x, y, z values are read from analog pins A0, A1, A2. The readings are subtracted with 338.

```
x   y   z
-4 -26 44
44 -27 -5
-57 -11 27
-29 -23 22
28 -21 9
-44 3 20
-26 -14 39
26 -32 -8
-17 -12 19
-30 -15 35
4 -26 14
24 -43 49
-58 -19 0
16 -29 24
9 -48 13
-58 -42 12
12 -47 14
-24 -31 9
-46 -31 10
16 -52 1
-43 -21 8
-31 -25 16
37 -18 11
-45 -10 20
-22 -36 16
27 -19 20
-5 -9 1
-59 -10 10
37 -18 30
-53 -18 16
-30 -8 10
54 -19 17
-27 -29 15
-40 -23 -14
-1 -18 19
34 -22 2
-35 -24 41
13 -17 7
-14 -17 21
-39 -14 35
-19 -31 6
62 -9 34
-63 -16 16
-12 -6 23
60 -33 36
-45 -2 34
-18 -15 9

```

As you can see the x value, when the whole thing is not moving, can range from -59 to +44. This looks very unusual as other people's reading seems to have just +-3 deviations. What might be wrong with my setup?

# Answer
> (just the IC, no resistors or capacitors)
>
> What might be wrong with my setup?

That's easy: You miss the capacitors ;-) Check figure 5 of the datasheet and try again.
> 3 votes

---
Tags: sensors
---


# Question
Title: Driving power MOSFET from 3.3v or lower Arduino Pro Mini
I want to control a low voltage (hobby class) motor with a 8Mhz/3.3v Arduino Pro Micro. I'd like to power both from 2 alkaline cells. The motor draws approximately 1 A @ 3V with new batteries. I would be doing PWM of a couple of channels at the normal Arduino rates.

My thought is to connect the batteries to the Vcc pin (not Vraw) and run the Arduino unregulated at about 3V, but somewhat less when the motor is running. I'm willing to reprogram the fuses for a lower brownout voltage (or none) if needed.

I'm feeling my way on the rest of this - I'll lay out my (perhaps naive) approach and get some feedback about whether I'm understanding it, and how to proceed.

With such a low battery voltage, a TIP120 darlington seems to drop too much voltage and substantially reduce the motor speed/power. So I'm thinking that I need to use a power N channel MOSFET, and it appears that I need to be fairly selective to get one which can sufficiently turn on with a \<3V gate to source voltage.

I'm considering something like the

If I read the datasheet correctly, Vgs of 3V and a load Ids of 1A would result in less than 100mV drop Vds. But this transistor may be overkill, and the TO220 package is larger than I'd prefer.

If I'm willing to deal with SOT-23-3 surface mount packaging, there are some options like:

If I'm reading it right, with 2x1.5v (nominal) batteries directly powering an Arduino Pro Micro, I can sufficiently drive Vgs to handle 1A Ids at a small Vds and a low enough power dissipation, with any of these three.

I would put a reverse diode and a cap across the motor. I've seen devices with a small electrolytic across the motor terminals, and I've seen a smaller value ceramic cap - what's the best practices?

Is this a feasible and reasonable approach? What are the gotcha's that I need to take into consideration? Any advice about choosing among these (or other) transistors?

My concerns are: not understanding MOSFETs enough, and the unregulated power supply being too noisy for the ATMega328p when it's also powering the motor. Can I handle the latter by adding another cap or two across the Arduino Pro Micro's Vcc/Ground?

Backup option: run 3x1.5v alkalines and power the Arduino Pro Micro through its regulated Vraw input.

# Answer
> 1 votes
I don't think the mosfets will be an issue. Looking at the last one (BSS806NE); in figure 5 in the datasheet you see that for 1A and 1.4v (Vgs) you'd get a Vds of only .1v.

I think a bigger problem might be the voltage of the batteries dropping under load. You'd have to measure that with a multimeter while the motor is running. A simple cap might help with a little noise, but not with the voltage dropping while the motor is running. Not sure how much the AVR would mind having its supply voltage dropping all of a sudden.

Of the top of my head the minimal voltage of the Atmega328 @8mhz is 1.8v, while default fuse settings use 2.7v, so I'd probably change to fuses to make BOD at 1.8v. Other fuses don't need to change.

Backup option sound good, though you might have to go with 4 x 1.5v depending on the voltage drop under load. Another alternative might be to have two sets of 1.5v batteries in parallel, halving the current load on each battery.

---
Tags: power, arduino-pro-mini, mosfet
---


title: From transfer function to arduino

text:
# Question
Title: From transfer function to arduino
This question might seem stupid, but I have been curious about it for a long time.

So I am a new engineering student, and we learned a lot about "designing a controller". For example, design controller for a car steering system and so on. All the "controllers" we designed are in the Laplace domain aka s-domain. And most of the times it will be just a transfer function. So how do real control system engineers use these transfer functions in arduino and other microcontrollers? I mean you cannot just put the function in there right?

Do you have to convert the transfer function to some other form and write the code for the microcontroller or is there a simpler way to do it?

Thanks for your time!

# Answer
Let's assume you have an Arduino that you have arranged to sample a signal with a sample rate of 1/T that is then processed by your controller. Let's also assume that the processing time for your controller is small compared to T e.g. 0.1/T

Firstly, you need to convert the controller transfer function to discrete time. There are lots of ways to do this. Matlab has a convenient c2d() function. One way you can do it on paper (not the best way), is to use Euler's Method.

**s=(z-1)/T** where T is the sampling period.

Converting a transfer function then: **(s+a)/(s+b) =\> (z-(1-aT))/(z-(1-bT))**

So now you have a TF in z such as : **Y(z)/X(z)=(z-c)/(z-d)** where Y is the output and X is the input.

To implement this in a controller you need this as a difference equation in terms of delays. So convert the equation to a function of (z^-1) which is a delay:

**Y(z)/X(z) = (1-cz^-1)/(1-dz^-1)**

and re-write as: **Y(Z)(1-dz^-1) = X(z)(1-cz^-1)**

**Y(Z)-d.Y(z).z^-1 = X(z)-c.X(z).z^-1**

and change to sample time treating z^-1 as a delay: **y(n) - d.y(n-1) = x(n) - c.x(n-1)**

rearranging: **y(n) = d.y(n-1) + x(n) - c.x(n-1)**

You can implement this easily in the Arduino by realising that y(n-1) is the previous value of y(n) and similarly for x(n), and x(n) is the value input to the controller; i.e. the reference minus the output from the ADC.
> 5 votes

---
Tags: programming, system-design
---


# Question
Title: Why does the battery eliminator connected to the wall provide a better spin to my dc motors than my battery of the same voltage?
Using a H-bridge, I've connected my DC Motors to an Arduino. When I accept the external power source from a wall, using a 9V battery eliminator, the motors spin well and consistently. However, when I connect it to a 9V battery, the motors spin slower, and the speed deteriorates till the motors stop. This happens in approximately 5 minutes. I checked with multiple 9V batteries of the same type. I have tested the batteries to check if they're dead after the motors stop. They are not, and if I reconnect the motors to them, the same process occurs all over again. I have checked for short circuits, and there are none. Any possible ideas as to why this is happening?

# Answer
> 4 votes
First off, never use 9V batteries to power motors or any device that consumes more than a few hundreds mA. Those batteries are just too weak.

Now a battery eliminator is not a pure equivalent as it can typically supply 800 mA or more, depending on the model you get.

The only commonalities between the battery and the eliminator are the 9V voltage and the socket.

If you want to power DC motors with batteries then rather use several 1.5V batteries in series.

# Answer
> 4 votes
The question is not about volts, but current.

A 9V battery is notoriously bad at powering anything that requires high current, like running a motor. Due to to chemical nature of the battery, the 9V will struggle to keep supplying enough current and will fairly quickly drain.

A regular alkaline 9V block can supply you with 565 mAh, which is not much if you power motors. You'll have more luck with LiPo (lithium polymer) batteries, which are capable of supplying 2200 mAh or more!

To learn more about different types of batteries check out https://learn.sparkfun.com/tutorials/battery-technologies

Wall power can quite easily provide the required current your motors need.

# Answer
> 2 votes
Batteries use a chemical process to produce power. If you draw to much current (motors use quite lot) the chemical process can't keep up and the voltage will drop, resulting in a slower running motor. Try connecting two batteries in parallel. That way each battery only has to produce half the current.

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


title: Webservice C# JSON to Arduino

text:
# Question
Title: Webservice C# JSON to Arduino
I have a project in Microsoft Visual Studio C# and I have to pass JSON data to my Arduino via Ehternet Shield.

This is how it works:

Is it possible? How to do it?

# Answer
Yes.

If you're using an Ethernet Shield, you should be able to run a webserver on the Arduino and simple do an HTTP request from your C# webservice to the Arduino.

Check this tutorial on how to write a webserver for arduino using the ethernet shield: http://arduino.cc/en/Tutorial/WebServer

Doing an HTTP request of any kind from C# should be easy enough and is not in the scope of this site.
> 2 votes

---
Tags: web-service
---


# Question
Title: Receiver xbee receiving data while the Transmitter is powered off?
My receiver xbee is receiving data even if the transmitter is disconnected , so if i am sending the string hello world , the receiver will repeat this string .

```
void loop() {
    Serial.println("Hello");
    delay(1000);
}

void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

```

# Answer
> 1 votes
As @Garben mentioned, we do not know what is your question, problem or whatever... Provide some more information about wiring. I looked at your question 5 mins and still can't get what is wrong...

What are you doing here??? Sending from Arduino+XBEE to another Arduino+XBEE???

```
void loop() {
    Serial.println("Hello");
    delay(1000);
}

```

Here you are resending what you got

```
void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

```

So what is your problem? Or is this all your code??? Arduino has to have

```
void setup(){
//Set up your Arduino here
}
void loop(){
//Code here will run over and over and over...
}

```

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


# Question
Title: Lego / Meccano style blocks for 'serious' projects
What can be used like Lego or other construction sets, but is more serious and 'professional'? E.g. what comes with gears and screws and things like that, but is geared to serious modelling or more permanent projects?

# Answer
Here is what comes to mind (by no means exhaustive):

billed as "the Industrial erector set", 8020 is legitimately used in industry for that kind of purpose, and if I remember correctly, pretty expensive. It is the most "professional" thing I can think of.

OpenBeam styles itself as the the cheaper, "open sourced" 8020. I've frequently heard of it being used in 3d printers.

These are not as serious or professional, but might be worth mentioning:

MINDSi is pretty close to the mindstorms, but tries to be more rigid/durable. It's aimed at robotics.

Servo City's actobotics is an aluminum modular building system. It is also sold on sparkfun.

I have not used these enough to give good comparisons, but I hope one of these will be what you are looking for.
> 2 votes

---
Tags: hardware
---


title: How to tap my thermostat's serial line

text:
# Question
Title: How to tap my thermostat's serial line
This is a home heating system hack.

I want to add an arduino in-line between my thermostat and air handler; and possibly between the air handler and outdoor compressor. The long-term goal is to post long-term statistics to an RRD web page (run time, power consumption, temp, etc.) and control the blower (without the heat) automatically when we are burning our wood stove.

The product is a Nordyne IQDrive (notable in that the equipment comes with 5 separate brand logos to adhere to the equipment: Tappan, Frigidaire, Westinghouse, Nutone, and Broan).

At this stage, all I want to attempt to do is to tap the serial links and record the conversations. I would prefer not to shoot myself in the foot.

The "System Field Wiring Instructions" describe both links as "serial." The wiring diagrams label the connection points as:

air handler interface board --\> \[description\] --\> thermostat

```
      G --> GND --> C
      - --> DX- --> B-
      + --> DX+ --> A+
      R --> R   --> R

```

Googl'ing these might indicate that this is an RS485 (never heard of it).

How do I tap and record the communication?

# Answer
I does sound like RS-485.

You can get cheap RS-485 transceivers from the usual sources. These take the 0..5v TX line and convert it to RS-485 voltages, or RS-485 voltages and convert to the 0..5v RX expected by your Arduino. You would normally enable only one direction at a time - sending RS-485 from the Arduino TX or receiving RS-485 to the Arduino.

In your case, you just want to receive, so keep the transmit side (TX to RS-485) disabled, while enabling the receive side (RS-485 to RX).

RS-485 is just an electrical standard, and they could be sending any pattern of on and off signals they want, but often they will be sending asynchronous data with one start bit, 7-8 data bits, and one stop bit per character - which the Arduino's Serial port can handle. So it's worth testing to see if that works.

The next thing you need to know is the clock rate, or "baud rate", which is how many bits per second (including start and stop bits) it is sending. Often you can figure this out by trying some standard rates like 1200,2400,4800,9600,19200,38400,57600,115200 (there are others) and printing the results to your screen - when you are at the wrong rate you will get nothing, or some odd garbage. When you get the right rate, it will look more reasonable.

If no speed works, you may need to reverse A and B.

You might temporarily hook up an LED and a resistor (say 2.2K or higher) between the RX from the RS-485 and your 5v power. This will give you an idea of when there are transmissions from or to the thermostat. If it only transmits once a minute, say, you might have to wait a while for each speed test. Or changing the set temperature may trigger a send.

You may be able to test the lower speeds at least using Software Serial, and then echo the received data to the hardware serial port which goes to the Serial Terminal in the Arduino IDE.

From there, you may need to figure out the protocol - the structure of the data. Protocols vary widely. It may be text or it may be binary; if it's binary you may want to have the arduino convert each character (values 0..255) into hexadecimal (00..FF) for printing.

Most protocols for this kind of control send data in a burst, or packet. You will likely be able to detect the start and end by the timing (ie: a long pause between the end and the start of the next). Of course, some protocols might send several packets continuously, but still the first character (or binary value) after a long pause will often be the packet header.

Remember that there may be packets from the themostat, and packets to the thermostat, and you will see both without knowing which is which (so long as you are just passively tapping the line).

I hope this is enough of a pointer to get you started. Decoding protocols is a more extended subject.
> 4 votes

# Answer
I read the WikiPedia article on RS485 (http://en.wikipedia.org/wiki/RS-485). The more I learn about RS485, the more likely it seems this is the right track. RS485 is typically wired in a bus with as many as 32 nodes. It's noise tolerant and more than fast enough for a heating/cooling system. At slower data speeds, it can run as far as 4000 feet.

The next step appears to be trying to record some traffic. I found this question on the EE Stack Exchange about tapping RS485: https://electronics.stackexchange.com/questions/30511/hijack-observe-rs485-communication-data-by-wire-tapping

A USB widget appears to be affordable. Inserting the widget between the two ends (I'll try and test to see whether the ends both have termination resisters) should be some easy wiring.
> 1 votes

---
Tags: serial
---


# Question
Title: Opening .h and .cpp files from folders other than the sketch folder
My team has a C++ program from another microcontroller that we are moving to Arduino, which is currently divided into two main folders, the sketch and libraries. We want to be able to open some of the library files in the Arduino IDE along with the sketch, something it will do automatically if they are in the same folder, but not allow otherwise. The files in question are referenced from the other libraries though, which means moving just a few of them results in compilation errors. We don't want to move them all to the sketch folder, since that defeats the purpose, but a few of my teammates are vehemently opposed to having to edit them using another IDE.

So is there a way to have these files open in the Arduino IDE with the sketch? Or do I have to tell my teammates to suck it up and use a second editor if they want to make changes?

Alternatively, a way to get the libraries able to reference files in the sketch folder would also work.

# Answer
> 1 votes
I don't recommend this

A) Because the arduino editor is pretty bad for serious coding

B) Because you will need to have a header guard on all library code that doesn't have one already (even in .cpp's)

But, if you really have to, the only way I can think of is to make a symbolic link to the library file in the sketch directory. It works, but the file gets compiled twice, so you need those header guards on everything.

---
Tags: arduino-ide
---


title: Finding arduino bootloader version?

text:
# Question
Title: Finding arduino bootloader version?
I have problem with WDT reset. After reset the device goes on for a boot loop. from the following link https://code.google.com/p/arduino/issues/detail?id=181 It has been mentioned that there is problem with Bootloader because some of them does not support wdt properly.How can i find which version of bootloader is running in my arduino mega 2560 . Which version of bootloader support wdt properly? where these bootloaders can be found?

# Answer
> 1 votes
In all practicality; put a known boot loader on it. Because if it is a problem version you will need to replace it anyways.

The Mega uses STK500 protocol. Which only shows a command to read its type (or signature) and not its version of firmware.

It is a good exercise, but not really worth the time to go deeper into it, as programmers are cheap and or you can use another Arduino as the programmer.

# Answer
> 1 votes
The watchdog timer will reset the Arduino in case of a timeout. The way to prevent this from happening is to catch the WDT interrupt.

```
ISR(WDT_vect)
{
  // do nothing
}

```

This has nothing to do with the bootloader. The fix suggested in the link above only makes the bootloader detect a reset triggered by a WDT event, and have it not add any delay. This delay is normally needed to see if the usb-host is trying to upload a new program.

---
Tags: bootloader
---


# Question
Title: Now at IDE 1.0.5, should I upgrade to 1.0.6 or 1.5.7 Beta for Pro mini and ATMega2560 use?
Do I need to **re-install many libraries** (or similar 'house keeping' works)? Is the upgrade straight forward?

Apparently, from Arduino web, one need 1.5 BETA series for use with Due. For Pro Mini, UNO and ATMega2560, should one use **1.5 BETA or 1.0.6** (no beta, presumable stable)?

I am running out of code space. Wonder if the upgrade will install a **newer gcc** compiler and smaller code size?

# Answer
Old libraries will work with 1.5 Beta, but you will most likely need to copy any of your own libraries over to the new beta installation, depending on if they were installed to the sketchbook location or inserted into the installation before. That should be about all you need to do after installing the beta for it to work.

The Beta supports all the regular boards as well as the Due and Yun. I doubt you will see any change in binary size if you update. I've been using the beta for some time now and it has been quite stable.

Which version you should use is up to you, the differences are relatively minor. I think the beta adds a few convenient features, but there are no changes to the code or functionality like the switch to v1.0 made.
> 2 votes

# Answer
I have had trouble with 1.5.7 (Beta), so I would stick with 1.0.6. As for code space, you might want to look into Atmel Studio (Free), which uses a Visual Studio shell as the IDE. It blows the Arduino IDE out-of-water. Atmel is the maker of all the AT chips, so the Atmel Studio IDE is a great IDE for writing AVR code. Lots of tutorials online and there is a Arduino plug in called Visual Micro (Free also).
> 3 votes

---
Tags: arduino-ide
---


# Question
Title: What software is available for use with AVRISP and USBASP on ATMega48, 328, 2560?
What software is available for use with AVRISP and USBASP on ATMega328, 2560 for read/write fuse, flash and EEPROM for UNO, Pro Mini and Mega2560 board?

(a fact question not opinion) Which software did you use?

Did it work straight forward (like the software did all the needed 'auto select')?

Does it need human selection for options, etc. on the above 3 boards?

Do I need WinAVR installed before able to use the 'ISP software'?

# Answer
Almost everyone uses either AVRDUDE (directly or indirectly, e.g. via the Arduino IDE) or the upload capability in Atmel Studio. I cannot speak for AS, but AVRDUDE does require options to tell it which programmer and device to use. WinAVR includes AVRDUDE, but is not strictly required as Win32 downloads are available at the AVRDUDE site.
> 2 votes

# Answer
As Ignacio Vazquez-Abrams mentioned, you should look into Atmel Studio. You can use a 3rd party AVR programmer (Arduino w/isp) or one from Atmel. The IDE is awesome and has a lot of features like setting fuse bits.
> 0 votes

---
Tags: software, isp
---


# Question
Title: How to enable maximum Dead Code Removal?
I am running out of code and data memory space on ATMega328P.

Code size is big as I used several libraries, but, I only use a few functions of those library.

Apparently, the default IDE is only doing a partial job in **dead code removal** (remove unreferenced code and data).

Some experiments shows:

1. A normal program that uses several Arduino libraries is 22 kilo bytes in code size.
2. Rename setup to o\_setup. Rename loop to o\_loop

Add

`void setup(){};`

`void loop(){};`

Code size is 8 kilo bytes while the program is 'empty' effectively.
3. **Start** a new program.

Add

`void setup(){};`

`void loop(){};`

Code size is 0.5 kilo bytes

Apparently, the IDE (linker called by IDE) is doing a 'partial' dead code removal job, as reducing code from 22kB to 8kB (case 1 and 2), **instead of 0.5kB** (case 3).

How can I **enable maximum dead code removal** function (reclaim code space occupied by unused library functions)?

# Answer
> 6 votes
Enable your IDE's verbose of the compile via the preferences. From there you can see exactly what and how it is being compiled.

In short the IDE (and toolchain) will compile everything and anything it can find into an object. Where only the used code is compiled in the linking phase, as garbage collection is enabled with the "--gc-sections" command.

Note that the optimization level is "-Os" or "Optimize for size". In IDE 1.0.+ this appears to be hardcoded. Where as in IDE 1.5.+ the compiler options are configurable, in "\arduino-1.5.6-r2\hardware\arduino\avr\platform.txt" can be customized to meet your needs.

Where you can use the avr-objdump command as described in https://stackoverflow.com/questions/15291750/does-importing-libraries-load-everything-in-arduino/15296808#15296808.

I would recommend 1.5.6r2 and not 1.5.7 as the gcc commands won't run individually without some path manipulation.

---
Tags: arduino-ide, code-optimization
---


# Question
Title: Arduino Yun C++ environment? Bridge + Cross-Compiler
I'm creating an XMPP chatbot for the Arduino Yun. However, I'm not too confident in the Python performance on such a low performance device and I'm much more comfortable with C++. Is there a C++ crosscompile environment available, and is there a port of the Bridge library to C++? Alternatively, documentation on how to interface with the ATMega using raw serial communication?

# Answer
> 1 votes
The Linux side of the Yun is just an OpenWRT installation. It has hardly been modified at all.

To cross-compile you will first need a Linux computer, or a Linux virtual machine. Then you need to download the OpenWRT source code and configure it for the Yun (I think it defaults to the right settings). Then you can build the whole OpenWRT image. One side-effect of that is it compiles and configures a full cross-compiling environment for you.

You can then use that cross-compiling environment to compile your own code.

# Answer
> 1 votes
Even if compiling C++ on the openwrt of the yun is possible with the last release of the yun-openwrt you should make a **yun build-chain**. That makes you compile on you computer for the processor architecture of the embedded machine on the yun.

I have never done but you can find some informations about it in those links: \- https://github.com/arduino/openwrt-yun \- http://fibasile.github.io/arduino-yun-custom-buildroot.html \- http://fibasile.github.io/compiling-nodejs-for-arduino-yun.html \- https://github.com/arduino/openwrt-yun/issues/20

For the other question.. for sure you can read/write serial directly from the openwrt. You need to disable the Bridge library (there are a lot of post around the internet. one is this one see the `Disabling the Bridge Script` chapter) and manually handle the serial communication.

Hope it helps!

---
Tags: c++, arduino-yun
---


# Question
Title: Can I change font Color and/or Type for IDE 1.5.6r2?
The program becomes harder to read (at least on my particular monitor) after upgrading.

Any way to change font **Color to darker** color and/or **Type to thicker stroke** (like B in this question editor) for IDE 1.5.6r2?

# Answer
> 6 votes
Yes.

Under the file menu select the preferences. From this you can find and than view/edit the preferences.txt file, which has the color settings.

Example preferences.txt

---
Tags: arduino-ide
---


# Question
Title: Digital pins on Arduino function as both positive and negative terminals?
I'm learning the arduino platform and working on a circuit that connects the two pins of a piezo buzzer -- one to ground and the other to a digital pin of the arduino board. In this configuration, is the arduino's digital pin acting as the positive terminal of the circuit?

The arduino docs seem to suggest it is:

> They (the digital pins) can provide a substantial amount of current to other \>circuits. Atmega pins can source (provide positive current) or sink (provide \>negative current) up to 40 mA (milliamps) of current to other devices/circuits.

Can the digital pins act as both positive and negative terminals in circuits? Does this question even make sense? What resources are out there that can help me better understand the underlying electronics of the arduino and microcontrollers in general?

# Answer
> 3 votes
The answer to your question is basically yes, you can use ATmega I/O pins as +/- power supply terminals for other circuits. But there's a limit to what you can power that way (20mA per pin and 100mA total per ATmega). In practice this means you can only power the simplest circuits (single LEDs per pin, and not many LEDs in total, for example). As a general rule, you should really look for other ways to power anything else.

Also, there's a problem with the citation you gave. That 40mA figure is the absolute maximum current per pin, but that should be avoided. Safest is to use about 20mA of maximum current per pin. Also, the ATmega pins should not have more than 200mA flowing through Vcc and GND (also an absolute maximum that should also be avoided).

Usually, you should either power other stuff off of the regulated +5V that also feeds the ATmega (up to the regulator capacity that depends on the Arduino board - 500mA for the Arduino Uno - 1A for LM7805 regulators - and so on). You could also use the unregulated power in some cases. Then you should use digital pins on the ATmega to switch transistors on and off which in turn will switch your load. Sometimes you can use transistors to switch relays, that in turn will switch even larger loads.

# Answer
> 3 votes
Step one: read the data sheet for the microcontroller. In there is a nice diagram that shows you exactly how the IO pins work.

The pins can work in 2 modes: input, and output. You're interested in output mode.

The drive state of a CMOS output pin consists of two MOSFETs, one connecting the pin to Vcc and the other connecting it to GND. Only one of the MOSFETs is ever turned on at a time, so the output pin is either connected to Vcc through one MOSFET, or connected to GND through the other.

When it's connected to Vcc it's said to be *sourcing current*, since it's at a positive potential compared to ground and current can flow *out* of the pin to light an LED (say), and when it's connected to GND it's said to be *sinking current* because current can flow *into* the pin to get to ground.

As an example of how it all works, consider how you would connect up and power a capacitative humidity sensor.

These sensors require a square wave at around 1KHz to operate. The humidity defines the impedance, and as part of an impedance divider (like a resistor divider) the output voltage is relative to the humidity.

Now, they don't just want any square wave, but require a square wave that reverses polarity around a virtual ground point, and that means reversing the polarity of the power across the sensor at 1KHz. How can you do that with an Arduino? The answer is simple:

Connect the sensor to two IO pins rather than 1 IO pin and GND.

Both pins are set as output, and one is set HIGH with the other set LOW. So the voltage across it is 5V.

Now you switch the outputs over, so the one that was HIGH is now LOW, and the one that was LOW is now HIGH. The power across the sensor has been reversed! It's now (effectively) -5V (compared to what it was before).

# Answer
> 2 votes
Arduino's digital output pin can not output a voltage lower than GND. In other words, the voltage on the digital output is always positive with respect to GND.

Can it be a negative terminal? It depends. There is no universal definition for "positive terminal" and "negative terminal". If you want to use these terms, you define what "negative terminal" is for each particular case. Suppose, you want to sink the current through an LED (and a series resistor). Then you connect the resistor to the VCC and Anode (negative terminal of the LED) to the digital output. Then you could say that digital output is the negative terminal for the LED.

# Answer
> 1 votes
When a GPIO pin is set to output mode, you can either drive it "high" (ie: VCC), or "low" (GND). They can not, however, drive a negative voltage (ie: -VCC). If you want to create a negative voltage, you'd need some external GPIO expander chip sourced off some negative voltage supply, or you'd need to create a negative voltage rail source via a buck-boost converter or similar to generate it from Vcc.

Fortunately for you, Arduino already has a pieze-electric buzzer library, and wiring it up is dead simple. The relevant GPIO pin is connected to the buzzer's positive terminal, and the buzzers negative terminal is grounded.

# Answer
> 1 votes
To summarize other people's answers:

Arduinos have a whole bunch of GPIO, or general purpose I/O, pins. They can be configured as digital inputs or digital outputs. Certain pins can also be configured as analog inputs or PWM outputs.

For a simple digital pin, if it is an input, it has nearly infinite impedance. (It looks like an open connection.)

If it's an output, it acts like a current source (connected to +5V) if it's HIGH, and acts like a current sink (connected to ground) if it's LOW.

Arduino I/O pins (on most boards, check your board's specs) have a hard limit of 40mA of current flowing through them, but you should generally keep the current below 20 mA.

Is a ground connection the same as a negative connection? Sort of. Some circuits include ground, one or more positive voltage sources, and one or more negative voltage sources. Audio (analog) circuits, for example, often need ground, +12, and -12 volts.

Arduinos don't deal with negative voltages, and applying a voltage that's less than ground to any pin will likely destroy it.

Think in terms of positive voltage and ground, not positive and negative. It's less ambiguous.

Don't think of Arduino pins as being power sources. Remember that they are LOGIC pins, and only put our very small amounts of current. Trying to source or sink too much current from an Arduino pin may destroy it.

If you need to source or sink more than 20mA, use a transistor as a switch to handle the higher current load.

In addition to all that, you need to watch the total current that you pass through all your logic pins, and also the total current you draw from the power supply. Check the specs on your board and make sure you stay within the limits.

# Answer
> 0 votes
First of all, the Arduino doesn't supply negative voltage. It flows from positive to *ground*, the reference point that determines voltage.

Anyway, I'm not quite sure of the exact details of the inner-workings of the ATmega chip, but I assume it goes something like this:

* A CPU cycle modifies a CPU register (or similar memory/latch somewhere)
* To the output of that "register," a circuit is connected that:
    + Shorts the pin to 5V if HIGH
    + Shorts the pin to GND if LOW

I suppose the latch could be directly connected to the pin, but I think that the current draw might be too high for the latch circuit, so an external transistor is used.

That above isn't anything that's really technically correct (as these details aren't always released), but its intended purpose is to show you how it basically works from a logic point of view.

You can then manipulate the pin's connection using either of these two pieces of code:

```
//HIGH (== 5V)
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);

```

```
//LOW (== GND; 0V)
pinMode(4, OUTPUT);
digitalWrite(4, LOW);

```

---
Tags: pins, digital
---