body: How can I control an AC ceiling fan speed using Arduino Uno R3? I cannot understand the key behind controlling AC voltage using Arduino (though I know how to on/off ac appliances using arduino and relays).

title: AC ceiling fan speed control using arduino Uno R3

Answers: 1

body:
**Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.**

Now that's the disclaimer out of the way, on to your question.

Unlike DC, you cannot use PWM to control the average power of AC.  That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.

For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.

If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays.  It's crude, but simple, and also probably the safest option for the beginner.

If you want proper variable speed, though, then you're going to have to chop up the waveform.  The theory is quite simple:  Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.

Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.

![enter image description here][1]

A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point.  While simple, these circuits aren't good.  The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc.  It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.

So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.

  [1]: https://i.stack.imgur.com/RxuQX.gif


body: I tried different times to use socat and ser2net in order to upload a sketch to an Arduino Uno (connected to a PC) from my laptop, unsuccessfully. Can anyone teach me how to achieve this goal? I use Linux.

title: Upload sketch remotely through a serial-IP-serial connection

Answers: 3

body:
**Basically it would require another bootloader.**

You might want to check this out:
http://playground.arduino.cc/Code/TFTPBootloader1

**Programming through serial**

I don't have the intention to advertise a product, but I worked with an Lantronix xport which was able to receive serial information (or a telnet session) over ethernet. You might want to look into cheaper models of other manufacturers (that do not use modem like commands) you should look for ethernet to serial converters.
It should be compatible  with: http://blog.solutions-cubed.com/programming-the-arduino-uno-with-a-serial-port/

**You might also connect to another PC over ethernet which then programs the arduino**

This would require another PC, but can be fairly easy to set up, but cumbersome to use. You could use teamviewer or another remote desktop. Find a way to send your code (or completely program it at the other pc) and then execute the program command. You might even check if it's possible to use an raspberry PI instead of a full PC (always wanted to try this).

**Use an arduino to program your arduino**

You might use an arduino that receives code and then uploads it to another arduino. Not sure how that works out. Or how to get the code on the first arduino. Should work fine if you've got something like a modificated arduino webserver running.

Also details on programming arduino can be found here:
http://www.arduino.cc/en/Tutorial/ArduinoISP

body:
I've been searching through the net for some days, in order to discover how I could easily upload a sketch to an Arduino that is not phisically connected to my PC, but instead that is connected to an another one, that belongs to the same LAN. I mean:

PC1-SERVER
Arduino Uno is connected to this PC with classic USB cable.
This PC is running Ubuntu linux, and sees Arduino as a serial port /dev/ttyACM0.

PC2-CLIENT
This is the PC where I create and compile the sketch.
I want to upload the sketch to the Arduino Uno described above (so, connected to SERVER, port /dev/ttyACM0)

SOLUTION:
server-side commands:

Code:

    sudo apt-get install ssh-server ser2net

    sudo passwd root    (to set the root password)

    sudo reboot

client-side commands (assuming 192.168.0.7 as IP address of SERVER):

Code:

    ssh -L 8086:localhost:8086 root@192.168.0.7 \
    '/usr/sbin/ser2net -d -C "8086:raw:600:/dev/ttyACM0:115200 NONE 1STOPBIT \
    8DATABITS -XONXOFF LOCAL -RTSCTS HANGUP_WHEN_DONE "'

you can then upload sketches to arduino doing this:

Code:

    avrdude -C /path/to/avrdude.conf -p atmega328p -c arduino -P net:localhost:8086 -U flash:w:/path/to/file.hex:i

NOTE:
In Eclipse, if you are using the arduino plugin, just place "net:localhost:8086" in the configuration panel, where "port:" field is required.

This solution was also posted on [arduino forum][1].

  [1]: http://forum.arduino.cc/index.php?topic=326850.0

body:
You can use an ethernet to ttl adapter and then install a virtual com software.

What i did was the following.

I used an ethernet to 232 converter,  and tweaked the board as you can see in the attached photo, I removed the 232 chip and jumpered the ttl directly to the output.

Then I installed USR-VCOM and set a virtual com port that shows in the arduino ide, it works without any software /boot changes

I am not sure how to remote reset the arduino....  Probably someone else knows.

![enter image description here](https://i.stack.imgur.com/1Jr5U.jpg)


body: i'm having few PCF8574P which i want to use with my arduino and multiplex them however i have no idea how to use the I2C BUS and the IC in general. There are few libraries but they're fairly complex. Is there any library which makes writing and reading from the PCF8574P easy?

title: How to use an PCF8574P with the simplest code possible

Answers: 1

body:
Have you given [Rob Tillaart's library from the Arduino Playground](http://playground.arduino.cc/Main/PCF8574Class) a try? The demo sketch might look a bit overwhelming, but at it's simplest, all your sketch should need to have to make a led blink like the standard arduino 'blink' sketch is

    #include "PCF8574.h"
    #include <Wire.h>

    // adjust addresses if needed
    PCF8574 PCF_38(0x38);  // add led to P0 (pin 4) (used as output)

    void setup()
    {
    //your setup code here
    }

    void loop()
    {
        //turn P0 (pin 4) of the I/O expander on and off once a second
        PCF_38.write(0, 1);
        delay(1000);
        PCF_38.write(0, 0);
        delay(1000);
    }

I don't have any of these parts handy so I can only give generic advice.


body:
I originally discouraged my friend against the use of Javascript in his robot project because I didn't know any use for Javascript outside of web developement but then I saw [this][1] book on amazon. Since I wouldn't want to mislead him could someone help me develop a better understanding of how often Javascript is used when making robots with an Arduino?

  [1]: http://www.amazon.com/dp/1457186950?ref=spks_0_0_2085848882&pf_rd_p=2085848882&pf_rd_m=ATVPDKIKX0DER&pf_rd_t=301&pf_rd_s=desktop-auto-sparkle&pf_rd_r=0G8XYED6NNM4FQ7Z508C&pf_rd_i=Javascript&qid=1432076822

title: To what extent is Javascript used in robots?

Answers: 1

body:
It wouldn't be my first choice for programming of robotics, but it's certainly doable.

Thanks to NodeJS, JavaScript (or ECMAScript as it is properly known) has broken free of the browser and is now a general programming language.

Thanks to the BeagleBone Black (and others), which runs most of its systems by default through NodeJS, including its web-based IDE, you can program the whole board with ECMAScript.

So yes, you *can* do robotics with ECMAScript, and there are platforms which *do* allow you to do robotics with ECMAScript.

Would you want to do it in a real industrial environment?

As I said - it wouldn't be my first choice.


body:
I want my arduino to give the output at a specified delay .The delay is calculated from a polynomial equation.

    unsigned long t=40*Vin*Vin-760*Vin+4320;
    delay(t);
    digitalWrite(ledPin,HIGH);

but while doing this i was unable to get the delay accurately while observing it through oscilloscope??

title: giving delay function to output

Answers: 2

body:
I suggest you look into using a hardware timer rather than using delay(), I suspect it will give you more accurate timing.

Timer configuration is not as straight forwards as using delay - they don't work in milliseconds or microseconds, but instead in multiples of clock cycles, which (I find) makes configuring them a little difficult to understand, but it is possible to set the interval of a timer within its own interrupt routine.

Another advantage to using timers is that your code can do other things whilst waiting between interrupts.

Have a read here for more information and simple examples:
http://playground.arduino.cc/code/timer1
or just Google "Arduino timers" for other examples and explanations.

body:
Perhaps you had in mind something like this fragment, which will raise `ledPin` for the time you calculated (in msec) then lower it again?

    // ...
    unsigned long t=40*Vin*Vin-760*Vin+4320;
    digitalWrite(ledPin,HIGH);
    delay(t);
    digitalWrite(ledPin,LOW);
    // ...


body:
I would like to read MUX 14 with the ADC.  On page 263 of the [Atmega328 data  sheet][1] it shows 1110b on the MUX corresponding with reading V_BG.

I need to read this so I can calibrate my sensor readings taken with the 5v reference to those taken with the 1.1v reference.  Because the 5v power supply may vary and the 1.1 is more stable, I need to be able to translate the readings taken with a 5v reference based on how the internal 1.1v is read.

Based on the [code for analogRead][2], I wrote this:

    int readVBG(int _analogReference) {
      uint8_t low, high;
      ADMUX = (_analogReference << 6) | 14;
      sbi(ADCSRA, ADSC);
      while (bit_is_set(ADCSRA, ADSC));
      low  = ADCL;
      high = ADCH;
      return (high << 8) | low;
    }

_analogReference is either 1 or 3 depending on the reference voltage desired.

I expect to read 1023 when _analogReference is 3 and about 225 when _analogReference is 1.  Instead I get smaller values which I'm guessing are from a floating (unconnected) analog pin.

  [1]: http://www.atmel.com/Images/doc8161.pdf
  [2]: http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html

title: Trouble reading V_BG

Answers: 1

body:
The problem is that a 2ms delay is required after setting the ADMUX bits before starting the conversion.  Thank you Majenko for the link.

    int readVBG(int _analogReference) {
      uint8_t low, high;
      ADMUX = (_analogReference << 6) | 14;
      delay(2); // Wait for voltage to settle
      sbi(ADCSRA, ADSC);
      while (bit_is_set(ADCSRA, ADSC));
      low  = ADCL;
      high = ADCH;
      return (high << 8) | low;
    }

The above code is specifically for the Arduino UNO.  Majenko's link above has #ifdef statements which support other devices.


body:
I am using Windows 8.1 64 bit. I have an Arduino Mega 2560. I configured and installed it with the Merlin firmware before. I had a system format in between. I tried to connect my Arduino again.

I have the following problems:

1. Not detecting any hardware when plugging in the Arduino board: the green LED is on and the yellow LED is blinking. I checked the Device manager. It doesn't come in either COM ports or other devices. (The last time it came in COM ports as Arduino Uno). I installed legacy hardware on COM 3 (which was used before) and tried to update the driver from a newly downloaded version of Arduino. No success. I disabled the certification signature requirement from boot menu and tried: again no success.

2. The serial port on Arduino is greyed out.

I need some help. I am running out of ideas. I tried uninstalling COM port. I cleaned the registry with CCleaner. I uninstalled all Arduino software. I rebooted the system. I downloaded everything again, then connected the board. Still not detecting the new hardware. :P

Help me out.

title: Not detecting Arduino Mega 2560. It worked before but now not detecting

Answers: 3

body: What you said has happened to me before.This happened to me as I supplied over 20v to the arduino.Did you supply a higher voltage than recommended or pull too many amps from the board?If you did so,it is almost futile to try to repair it.

body:
Assuming the board is not fried...

Sounds like 'USB <--> serial' chip issue. Not sure which chip it is, could be CP2102 or FT232 or CH340G. If it is FT232R and not a genuine one and you are using a specific version of the driver - you could have bricked the USB <--> serial converter.

Without assumptions, I would start with a bootable USB pen-drive with some flavour of Linux - I prefer Linux Mint/Ubuntu. Here is how I would go:

 1. Boot the system with the pen-drive with Arduino disconnected
 2. Open terminal and tail the system log (e.g. tailf /var/log/syslog)
 3. Attach the Arduino board and see what shows up.
 4. If Arduino is detected, there will be a message with the serial port device name (e.g. /dev/ttyUSB0)
 5. Arduino IDE could run on Linux. If the port is detected, run Arduino IDE and see if it detects the board.

If not detected, the board is still useable, but you might need to find a way to connect external USB <--> Serial converter and disconnect the on board one. That means cutting traces and probably soldering some pins.

body:
It's possible it's fried - but I have had recovered some boards like this that the boot software had gotten corrupted.
It's easy enough to reapply the bootloader to the device - you will need either a second arduino:

  https://www.arduino.cc/en/Tutorial/ArduinoISP

or an usbasp programmer (about $10 on eBay).

There is also a tutorial on reflashing the USB chip (link below) - but I would try the above first.

https://www.virtuabotix.com/how-to-cure-sudden-uno-death-syndrome/


body: I'm using Hc-Sr 04 ultrasonic sensor for my project and I want to know that if I could or not utilize an slope. Have you an idea?

title: Hc Sr 04 Ultrasonic Sensor

Answers: 2

body: Slope surfaces may cause reflections so you need to try. I think 30 degree going to make reflection and gives wrong value

body:
I have a couple of these running right now, and they will often work at a slope when the surface is complex (not flat). However, the detection angle, as it comes from the sensors, appears to be about 30deg from centre in each direction. Hence, the sensors do need to be relatively pointed at the object being detected.

When placing my hand directly above it, it doesn't really matter what angle I tilt my hand, presumably since I have fingers that are not flat. On the other hand, if I put a paper towel in front of it, it will stop seeing it if I angle the paper towel more than 20 or so degrees.

Overall, if you keep the object within 30 degrees from the sensor's fixation point, it will work, granted the object, if flat, is "pointed" at (facing) the sensor flat-wise within about 20 to 25 degrees. For irregularly surfaced objects, it does not seem to matter too much unless the angle is pretty steep, such as 60 degrees.

Here is what I mean:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/sKF5E.png


body:
I am building a device that communicates with my Android phone.
I know that my App works but my Arduino code seems to have a problem.
So I have made a smaller programm and everything works fine there.

SMALLER PROGRAM - THAT WORKS
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>

    SoftwareSerial btSerial(8,9); // RX, TX

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

    void loop() {
      //Send everything from PC-Console
      while( Serial.available() )
      {
         btSerial.write( Serial.read() );
      }

      //Show everything received with bluetooth to PC-Console
      if(btSerial.available())
      {
        while(btSerial.available())
              Serial.write((char)btSerial.read());

        Serial.println("");
      }
    }

I thought everything is fine so I've changed a few things in my original code.
But still the Arduino receives nothing, sending is no problem.

ORIGINAL PROGRAM - PROBLEM

    #include <SoftwareSerial.h>

    SoftwareSerial btSerial(8, 9); //RX TX
    SoftwareSerial rfidSerial(11, 12);

    char tagCollection4][13] = { {"6A003D68AA95"},
                                 {"6A003D8879A6"},
                                 {"6A003D49617F"},
                                 {"6A003A426775"} };

    String tagCollection_str[4] = {"6A003D68AA95",
                                   "6A003D8879A6",
                                   "6A003D49617F",
                                   "6A003A426775"};

    bool tagsFound[4] = {false, false, false, false};

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

    void loop() {

     //Send everything from PC-Console to Bluetooth device | that part works
      while( Serial.available()  )
      {
        btSerial.write( Serial.read() );
      }

      //Show everything received with Bluetooth device on my PC-Console
      if( btSerial.available() )
      {
         while(btSerial.available())
                  Serial.write((char)btSerial.read());

        Serial.println("");
      }

      //Here starts the Rfid Part that I’ve done first it works mostly
      char tagString[13];
      int index = 0;
      boolean reading = false;

      if(rfidSerial.available() )
      {
        while( rfidSerial.available() )
        {
          int readByte = rfidSerial.read(); //read next available byte

          if(readByte == 2) reading = true; //begining of tag
          if(readByte == 3) reading = false; //end of tag

          if(reading && readByte != 2 && readByte != 10 && readByte != 13){
            //store the tag
            tagString[index] = readByte;
            index ++;
          }
        }

        delay(50);
      }

      checkTag(tagString);
      clearTag(tagString); //Clear the char of all value
    */
    }

    void checkTag( char tag[] )
    {
      if(strlen(tag) == 0) {return;}

      int tagNum = compareTag( tag );

      if( tagNum == -1 )
      {
        Serial.println("");
        Serial.println("NO MATCH");
        Serial.println("");
      }
      else
      {
       if( !tagsFound[tagNum] )
       {
          tagsFound[tagNum] = true;
       }
       else
       {
         tagsFound[tagNum] = false;
       }
       //Just a little delay
       delay(2000);
      }

      //Show the scanned tag
      Serial.println("");
      for( int i=0; i<13; i++ )
      {
       Serial.write(tag[i]);
      }

      Serial.println("");

      for(int i=0; i<4; i++)
      {
          Serial.println( tagsFound[i] );
      }

      Serial.println("");
      Serial.println("");

    }

    int compareTag( String tag )
    {

      if(tag[9] == tagCollection4[0][9])
          return 0;

      if(tag[9] == tagCollection4[1][9])
          return 1;

     if(tag[9] == tagCollection4[2][9])
          return 2;

      if(tag[9] == tagCollection4[3][9])
          return 3;

      return -1;
    }

    void clearTag(char one[]){
    ///////////////////////////////////
    //clear the char array by filling with null - ASCII 0
    //Will think same tag has been read otherwise
    ///////////////////////////////////
      for(int i = 0; i < strlen(one); i++){
        one[i] = 0;
      }
    }

Please help me, it's for a school project.

Thanks for everything in advance.

title: Arduino code issue (using Bluetooth and Rfid technology)

Answers: 0


body:
I want to Create a battery Charger with the Arduino with real time battery status. I don't have any idea how to do that same time as the charging.

> **I know to use a serial monitor to get battery status but not to charge.**

I would like to know how to do that simultaneously so that I don't over charge the battery.

 - This is the battery for Lumia 822
 - Nokia BP-4W 1800mAh 3.7v 6.7Wh

title: Create a Li-Polymer Battery Charger

Answers: 1

body:
**(1) A simple method**

BEST method is to use a proper charger - they are not high cost if you look around and doing it properly extends precious battery life.

Next best in this context is my "better" method in 2. below.

BUT, given the system you say you are using now, the following very simple method will greatly improve your result and ave your battery from an early death.

You need a 1 Ohm resistor and a voltmeter that you can trust to read a 4.1V votage accurately. Without these the simple method risks battery damage or destruction - just as your present method does.

Warning: Straight connection to a USB port is very unwise but may be viable if the port current-limits.

 - If the current is ever higher than the rated maximum then battery destruction may occur.

 - If the battery voltage ever exceeds 4.2V at room temperature battery damage WILL occur and battery destruction may occur.

Worst case a badly treated battery can turn into a flaming inferno in seconds.

A usably OK result can be gained by:

(1) Calculate Imax = same mA as battery mAh capacity.
LOWER is OK. Higher is not.
eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.

(2) Connect a ONE OHM resistor in USB to battery line.

(3) Connect **discharged** LiPo battery to USB port via 1 Ohm.

(4) Measure voltage across the resistor.  The voltage will be 0.001 Volt for every mA that flows. eg
1000 mA gives 1.000 Volt
789 mA gives 0.789 V.
1234 mA gives 1.234 V. etc.

If the measured mA is LESS THAN Imax in (1) above then this is OK to charge with.

(5) Use Arduino analogRead() function WHILE CHARGING to measure battery voltage.
BE SURE that the voltage that you read with the Arduino matches what a quality meter says.
When Vbattery (measured from Bat + to Bat- AT the battery) measures 4.1 V STOP CHARGING, remove voltage.
Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged).

For 10 bit ADC = 1024 counts total (0-1023) then
for 5V reference 4.1V count = 4.1/5 x 1023
= 838 counts.
Using 830 counts to start with is safer.

When battery is at the upper charge limit,  and **before** removing Vcharge, measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system.

Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.

The BEST method is to use a proper charger - they are not high cost if you look around and they extend precious battery life.

._______________________________

**(2) A better method:**

LiIon (Lithium Ion)and LiPo (Lithium Polymer) batteries are functionally the same for charging purposes. I'll use the term "LiPO" from here on. I'll assume single cell batteries as most in cellphones and similar are. If the terminal voltage is between about 2.5V (should really be higher) and 4.3V they are single cell,

LiPo batteries have 4 main charge areas.

 - Under about 2V = dangerously dead. Discard

 - 2V to about 3V = under voltage - charge very slowly

 - 3V to 4.2V = charge at CC  = Constant Current.

 - On reaching 4.2V charge at CV = Constant Voltage until current reduces "automatically" (under battery chemistry control)  to about 1/4 x max rate.

Max charge rate is set by the manufacturer but is almost always the numerical mAh rating in mA. eg for a 1000 mAh battery max rate is 1000 mA. For a 3300 mAh battery it's 3300 mA etc. In a very few cases it is lower - maybe =half standard values and for a very small number of cells its higher - assume you do not have those.

Max voltage **MUST NOT** exceed 4.2V at room temperature. Lower, say 4.1V, does no harm and increases battery cycle life while slightly reducing capacity per charge.

The battery mAh rating is known as "C".
If C = 1200 then a cahrage rate of 1200 mA = C/1,
a charge rate of 300 mA = C/4,
a charge rate of 12 mA = C/100 etc

An easy charging method that gives long cycle life and about 70% to 80% of max possible capacity and a fast charge is

 - Determine max charge rate = C  = Imax = same mA as battery has mAh capacity.

 - If Vbattery is < 3V, charge at C/20 or less until Vbattery reaches 3V.
 If Vbattery never reaches 3V it is dead.

 - When V_battery = >= 3V, charge at C/1 until Vbattery = 4.2V ( or 4.1V)

 - Finished!.

 - Remove applied voltage. DO NOT EVER leave 4.2V applied to a charged battery.

A more usual method that is only slightly harder is.

 - Monitor charge current.

 - Charge as above until Vbat = 4.2V.

 - While holding Vbat at 4.2V monitor charge current. This will fall as the battery absorbs additional charge.

 - When  Icharge falls to C/2 or C/4, stop charge. C/4 adds slightly more charge than C/2 but shortens cycle life.

 - Again - DO NOT leave 4.2V applied to battery once charged. Doing so will destroy the battery rapidly. Remove all voltage once charged.

.______________________________

**Battery University:**

[Charging Lithium Ion & LiPo](http://batteryuniversity.com/learn/article/charging_lithium_ion_batteries)

[Increasing lifetime](http://batteryuniversity.com/learn/article/how_to_prolong_lithium_based_batteries)

[Index](http://batteryuniversity.com/learn/)

.______________________

### Q&A

>Q: This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept.

Read the above material and the battery university pages.

4.1 V ABSOLUTE MAXIMUM is what I recommended.

 - Most LiPo single cell batteries are labelled as 3.6 V or 3.7 V as that is approximately the **average voltage** across the discharge cycle.

 - When **fully charged** they are at **about 4.2 V (or 4.1 V if you take my advice -** which you should :-).

 - As they discharge the voltage falls and by the time they get to just above 3 V they are essentially fully discharged. They should never be discharged below 3 V as it damages them and there is only a tiny amount of energy left.

So 4.1 V ABSOLUTE MAXIMUM is good
MEASURED WHILE CHARGING and
AT the battery terminals or very close to them.
ie no long leads or resistors or connectors.

If using an Arduino to measure battery voltage,  connect an Arduino ground lead to battery negative with as short a wire as practical and the ADC +ve input to the battery +ve at the battery connection point.

So once more: A LiPo battery labelled as 3.6V or 3.7V can and should be charged to 4.1V maximum and never discharged to below 3V.


body:
This is my first post to this forum.  I am fairly experienced in electronics, but am in the process of learning C, Arduino coding, and how to use microcontrollers in general for various applications.

I have a toy-like 5 degree of freedom (DOF) robot arm that is currently controlled using the OEM hand-held switch box.  It is a basic electromechanical robot arm to illustrate the fundamentals and it uses DC motors to drive the joint motions.  The direction of motion is controlled by changing the polarity of the applied voltage.  The manufacturer did offer an "interface board" and SW to be able to hook up the arm and control it using a computer program.  However, this approach was fairly dated and their SW was not compatible with windows 8.1.  I wanted to experiment and use an Arduino Uno Rev 3 and 5V DC relay PCBs to develop my own interface system.

Basically, the HW aspect was straightforward and is working fine.  The Arduino SW also is working fine.  I am playing around with 2 variations of the program: 1) One program that simultaneously moves up to 3 joints and 2) A sequential joint movement program where each joint only moves after the other has finished moving.  One **note** about the simultaneous program is that I am using the "internal" batteries in the robot's base (only 3V each direction) and thus can not realistically move more than 3 joints at the same time without putting too much load on the source voltage.

**Ok, now to my question!** As it stands now, the program works well, but is not intuitive.  Each joint has 2 relays associated with it: one for each direction of travel.  There are 5 joints total in the robot arm.  I am able to use the program easily since I know directly (from setting up the HW and then the SW) which relays correspond to which Arduino pins and of course which relays correspond to each joint.  I'd like to make the program more intuitive where instead of "2,2,0,0,3,4" input string for example, the user would do something like "B,CCW,S,CW"  where B is for B = base, CCW = is counter clockwise etc.

Please note that in the numerical only input string "2,2,3,4" for example, the 2nd value corresponds to the duration in seconds that the relay will be ON (and thus the joint moving).  The robot arm is not very sophisticated in that it doesn't have encoders for position feedback.  The simplest way (and the method which the OEM interface board uses) to interface this arm and make a program where the arm will move in a "hands-off fashion" was to use relays and program delays (to create time durations of joint movement".  The numerical only input works really well currently and it was very easy to use examples to figure out how to parse a comma separated string.

I understand (I think) from looking at the examples how to parse a comma separated text string and pull from it the input values.

BUT, I am uncertain how to use those input values and then associate them in the SW with the correct relays (Arduino Pins)!

I have already tried seeking help with this but am unable to understand this thread:  http://forum.arduino.cc/index.php/topic,94701.0.html

Basically, I need a 2D table where the joint and direction are input and then the SW associates one particular relay with those inputs. Please see the table below for a graphical example of what I tried to say above.

One possible solution that I **dread** and saw mentioned was to use a ton of **if else-if statements....**  I dread this since I want to be able to input any joint in any order and thus it seems like when the code parses the input string for the ith relay, it would have to check ALL of the conditions to see which joint it is, which direction etc.  For example, I think I could minimize the # of if statements needed if I only entered in the input commands in a certain order: base first, shoulder next, etc.  Doing so however, limits the intuitiveness of the program.

![enter image description here][1]

  [1]: https://i.stack.imgur.com/zkLUT.png

Thank you all for reading this!  I hope this isn't too challenging!

title: How to implement a 2D lookup table?

Answers: 4

body:
I suggest you turn this into a simple 1D table by using two different
separators, for example ‘:’ between joint and direction, and ‘,’ between
consecutive movements. Then, instead of “B,CCW,S,CW” you would type
“B:CCW,S:CW”. For parsing the string, you split at the commas, and
consider the pieces between the commas as single items. In other words,
“B:CCW” would be the name for relay 2, and you do not try to split it
further.

Here is a simple method to map the strings to the relays:

<!-- language: lang-c -->

    const char * const relay_names[] = {"", "B:CW", "B:CCW", "S:UP",
        "S:DN", "W:CW", "W:CCW", "E:UP", "E:DN", "G:OP", "G:CL"};

    // Return the relay number.
    int get_relay(const char * name)
    {
        for (int i = 1; i <= 10; i++)
            if (strcmp(name, relay_names[i]) == 0)
                return i;
        return -1;  // meaning invalid
    }

body:
 In C/C++, multi-dimensional arrays are represented as arrays of arrays of arrays ..., for the number of dimensions needed (the last subscript varying most rapidly as you step through the stored elements in RAM).

The array you described is a sparse array; not all cells hold valid data. To simplify (and that's a relative term!) the storage and the code, I would arbitrarily assign each joint a forward and a reverse direction, reducing your 10-row sparse array to a dense array of only 2 rows. You can then, if you wish associate joint-relative motionss (up/down, open/close, etc.) with forward/reverse. Then you can find the pin # for a given joint relay by the joint name and direction as `RelayPin[<direction-name>][<joint-name>]`. A downside is that writing `RelayPin[DIR_OPEN][JNT_ELBO]` looks like nonsense but actually executes, though maybe not in the direction you think you meant.

This code snippet defines a 2D array of joint-relay pin numbers, with an example of enabling one of the relays:

    // Number of joints and directions
    #define NDIRECTIONS 2
    #define NJOINTS 5

    // Basic joint-motion directions
    #define _DIR_FWD 0
    #define _DIR_REV 1

    // Aliases for joint-motion directions
    #define DIR_CW _DIR_FWD
    #define DIR_CCW _DIR_REV

    #define DIR_UP _DIR_FWD
    #define DIR_DN _DIR_REV

    #define DIR_OPEN _DIR_FWD
    #define DIR_CLOSE _DIR_REV

    // Joint table indices
    #define JNT_BASE 0
    #define JNT_SHOU 1
    #define JNT_ELBO 2
    #define JNT_WRIS 3
    #define JNT_GRIP 4

    // Joint table - each element is a digital pin number
    uint8_t const RelayPin[DIRECTIONS][JOINTS] = {
    //  B  S  E  W  Ga
       {1, 3, 7, 5, 9}, // forward
       {2, 4, 8, 6, 10}, // reverse
    };

    // Example of enabling motion to raise the shoulder:
    digitalWrite(RelayPin[DIR_UP][JNT_SHOU], HIGH) // raise shoulder

body:
Another thing you can consider is to define a *struct*.  This is a compound variable that contains other variables of different types.

You could define a *struct* to describe the joints of an arm:

    struct arm {
        int base;
        int shoulder;
        int elbow;
        int wrist;
        int grip;
    };

Which you can then assign as variables:

    const struct arm left_forward = { 1, 3, 7, 5, 9};
    const struct arm left_reverse = { 2, 4, 8, 6, 10};

You can then get at different pins by using such things as:

    digitalWrite(left_forward.shoulder, HIGH);

Another trick is to make your struct contain a *union* and an *anonymous struct* so you have multiple ways of accessing the pins:

    struct arm {
        union {
            struct {
                int base;
                int shoulder;
                int elbow;
                int wrist;
                int grip;
            };
            int pins[5];
        };
    };

You can now get at `left_forward.shoulder` and `left_shoulder.pins[1]` and they point to the same thing.

You can create an array of these structures now:

    const struct arm left[2] = {
        { 1, 3, 7, 5, 9},
        { 2, 4, 8, 6, 10}
    };

So now you have `left[0].shoulder` and `left[0].pins[1]` both for the left shoulder moving forwards.

Another option, which might be far more logical, is to turn the whole thing inside out.  Define a "pin pair" structure that defines the two pins for a joint:

    struct pinpair {
        int forward;
        int reverse;
    };

Then an arm consists of 5 "pin pairs":

    const struct pinpair leftarm[5] = {
        {1, 2},
        {3, 4},
        {7, 8},
        {5, 6},
        {9, 10}
    };

So to move the left shoulder forward it would be `leftarm[1].forward` and to move the wrist backward would be `leftarm[4].reverse`.

Of course, you could combine the two and have a struct of named structs for each joint if you wanted (`leftarm.shoulder.reverse`. I'll leave you to work out the syntax for that from the examples above).

Now for your "control string".  How to deal with that.  Well, I would "pre-parse" it into an array of numbers.  Compile it into "byte code" if you will.

Start with an empty array that would be big enough to store the data you want, then work your way through the string.

Tokenize it (hint: strtok() is good for this) and check each piece of the string against others.  Unfortunately it's not something you can easily automate, and you'd either have to loop through an array of strings to compare each one to, or use a series of "if" statements.

For each item that you match you then assign a "command code" to - a number you can then easily associate with a specific action or joint.  For instance, "B" may equate to command 0, "S" to 1, ""E" to 2, etc - which just happen to coincide with the array slices for the joints.

The directions could then be other codes (keep them outside the range of your array so you can identify them), maybe 16 and 17 (hint: think about the hexadecimal representation of those and how you could use that to your benefit).  It can also be useful to mark the end of the array with a special token to say "this is the end" - say 255 (0xff).

Then once you have parsed the string and got your list of numbers, which may be something like `{ 0, 16, 1, 17, 255 }`, you can then "execute" it.  Just step through each entry, if it's < 16 then it's a command, if it's >= 16 then it's a direction, and if it's == 255 then it's the end of the command list.  It's then up to you to drive the right pins for the right periods to execute those commands.

body:
The other answers have presented some good techniques that are flexible enough to be adapted to other, similar problems.  By contrast, the following method is specialized to work with the particular chart of joint-letters and relay-numbers mentioned in the question.  (It can be modified for other relay-number sequences, as noted in program's comments.)

Rather than requiring entry of verbose text like CCW, or obscure abbreviations like DN, OP, and CL, it accepts a + or a - to set motor direction, with “+” corresponding to choices CW, UP, and OP, and “-” corresponding to  other choices.  For example, the question's sequence “B,CCW,S,CW” could be written as any of “B-S+”, “b-s+”, “B- S+”,  “B-,S+”, etc (ie, case is ignored, and spaces and commas are ignored before a joint-letter).

Note, the code as shown assumes each command-list line starts with a number that gives desired delay time in tenths of a second.  For example, “23 e-s+” would run E down and S up for 2.3 seconds.  The command-list “47” would sit idle (no motors on) for 4.7 seconds.

    #include <ctype.h>
    void operateRelays(char *cmdList) {
      char *joints = "BSEWG", *c=cmdList, *j;
      byte relay, delaytenths= 0;

      while (*c && isdigit(*c)) // Get # of tenths-of-seconds to delay
        delaytenths = 10*delaytenths + *c-'0';

      for (; *c; ++c) {
        while (*c && !isalpha(*c)) ++c; // Ignore non-alphas before joint
        if (!*c) break;  // At end of command list, break
        for (j=joints; *j; ++j)
          if (toupper(*c) == *j) break;
        if (!*j) break;  // Ab-exit if joint-letter not found
        if (!*(++c)) break;  // Advance to + or -
        relay = 2*(j-joints) + 1 + (*c != '+'); // The last term is 0 or 1
        digitalWrite(relay, HIGH);
        // If relay numbers aren't contiguous as in question, just use
        // an array (like: byte relays[] = {2,1,5,4,6,3,7,9,10,8};)
        // and in above statement say digitalWrite(relays[relay-1], HIGH);.
      }
      delay (100*delaytenths); // Wait specified time
      for (relay=1; relay<11; ++relay) // Turn motors off
        digitalWrite(relay, LOW);
    }


body:
Should I use 2 relays, one for the hot wire and one for the neutral ?
I'm talking about 16A.

title: Controlling a 240v AC high current relay

Answers: 2

body:
As mentioned in the comments, if switching both, and the neutral relay fails open, unpredictable things may happen.

If you really want to switch both then use a two pole relay which switches both the live and the neutral together.

For instance, I use these relays:

> http://uk.farnell.com/finder/22-22-9-012-4000/relay-modular-dpst-no-12vdc-20a/dp/1169296

20A, 250VAC contact rating, double pole.

body:
Use 1 relay, more precisely a DPST (Double pole, single throw) type. You'll only need 1 signal to drive both, and be sure that both lines are switched off. Electrical installation regulations require double throw relays/switches for certain applications, e.g. in wet rooms like bathrooms.

Note that relays are more delicate devices than they appear to be. A 16A relay may not always be suitable for switching 16A. They have to be **derated** according to their type of load. And that is almost everything. Not only for capacitive or inductive loads you'll have to limit the current to a fraction of the rated 16A, but even for incandescent lighting (due to the high current peak when switching on). See the manufacturer's datasheet or application documents for the amount of derating.


body:
I'd like to write a function like this:

    void lcdPositionPrint(int row, int col,  content) {
     lcdPosition(row, col);
     LCD.print(content);
    }

but I'm not certain how to declare "content", because it might be a string, or an int, or who knows what, just as it is for the "Serial.print" function or the LCD.print() function. Is there an easy way to do this?

title: Passing arguments to LCD.print through another function

Answers: 2

body:
One way to do this is to use generics. And we also need to use an unnamed namespace to get around the IDE's "helpfulness":

    namespace {
        template<typename T>
        void lcdPositionPrint(int row, int col, T content) {
            lcdPosition(row, col);
            LCD.print(content);
        }
    }

This will cause the compiler to create one function for each type passed in `content` that the function is actually called with.

body:
There isn't really a great way to do it, but there are a few ways to get it to work. Most of the problem here is that there is actually a different `LCD.print` function for every data type. You aren't really calling the same function, your calling different functions that share the same name.

**You could use templates.** They are a powerful system built into C plus plus for generating functions and avr-gcc supports them well. With them, you can make the compiler generate all the necessary versions of your function for you. Your function would then look like this:

    template<typename T>
    void lcdPositionPrint(int x, int y, T content) throw() {
      lcdPosition(row, col);
      LCD.print(content);
    }

That part about `throw()` isn't doing anything except keeping the ".ino" preprocessor from messing the template function up. You can call the templated function like normal, or with an explicit type

    lcdPositionPrint(0,0,"hello");
    lcdPositionPrint<float>(0,0,32.0f);

**You could also use the preprocessor.** Your function is very simple, so you could just as easily make it a preprocessor macro that just places you code you want in the file whenever your "function call" appears. It looks like this:

    #define lcdPositionPrint2(row,col,content) \
        do { lcdPosition(row, col); LCD.print(content); } while (0)

The `\` there tells the preprocessor that the next line is also part of the macro, and you will need one on every line but the last of your function. Wrapping it in a `do` loop that immediately ends makes it nicely substitute into more situations. Micros don't scale up well, but they are a bit simpler for quick debugging situations. The code is duplicated in each call location instead of being bundled into functions though.


body:
Hi we are using an Arduino Micro and working with a Bluetooth device and a Rfid Scanner from Sparkfun(ID-20 LA). For that we implemented 2 SoftwareSerial objects and the Serial port for the Serial Monitor. If we use one SoftwareSerial object and the normal Serial everything works fine. For example we can send and receive things over Bluetooth. But when adding another SoftwareSerial object( Rfid then ) One of them doesn't work.

Starting with the Rfid SoftwareSerial ends up to the same result.

We've also already tried to change the ports and so one.

Every help is appreciated.
Thanks in advance.

The Code ( this is already the third programm nothing has changed )

    #include <SoftwareSerial.h>

    SoftwareSerial rf(11, 12);
    SoftwareSerial bt(8,9);

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

    }

    void loop() {
      if(Serial.available())
      {
       while(Serial.available())
         Serial.write(Serial.read());

       Serial.println("");
      }

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

       Serial.println("");
      }

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

       Serial.println("");
      }
    }

title: SoftwareSerial problems

Answers: 2

body:
Under the known limitations in the [`SoftwareSerial` documentation][1]:

> If using multiple software serial ports, only one can receive data at a time.

It's still possible to use multiple instances of `SoftwareSerial`. However, when you want to use a specific one, you need to call the [`listen()`][2] member function. This will allow it to receive data until you call that function on a different instance.

One very important thing to understand is that data is not queued in the background. If information arrives while a SoftwareSerial port is not listening, it simply gets discarded.

There may be alternative software serial libraries which suit your needs, depending on how they use interrupts. Alternatively, you could use a different Arduino which has multiple hardware serial ports (such as the Mega).

  [1]: http://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: http://www.arduino.cc/en/Reference/SoftwareSerialListen

body:
Taken from http://www.arduino.cc/en/Reference/SoftwareSerial:

Limitations

The library has the following known limitations:

    If using multiple software serial ports, only one can receive data at a time.

If your project requires simultaneous data flows, see Paul Stoffregen's AltSoftSerial library. [AltSoftSerial][1] overcomes a number of other issues with the core SoftwareSerial, but has it's own limitations. Refer to the AltSoftSerial site for more information.

If you look at SoftwareSerial's code, you'll understand the limitation:

    /* static */
    inline void SoftwareSerial::handle_interrupt()
    {
      if (active_object)
      {
        active_object->recv();
      }
    }

Basically, the code waits for an interrupt to detect state changes on the pin, and directs it to the "active" serial object.

Hope this helps.

  [1]: http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


body:
I have been trying to make my two Nrf24L01 wireless model work for few days now, to do so I follow the tutorial in the following link.

http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

I followed the link exactly, i changed nothing, expect i didn't add the bypass capacitor , as they said it will improve the performance and reduce heat, however mine is not working at all.

here is a pictures of my hardware setup ,

![arduino setup][1]
![anther picture for the setup][2]
![my whole setup][3]
![nrf24L01 model][4]

for the code i didnt change any this from the tutorial but i will past it to make it easy to follow Transmitting code

     /* YourDuinoStarter Example: nRF24L01 Transmit Joystick values
     - WHAT IT DOES: Reads Analog values on A0, A1 and transmits
     them over a nRF24L01 Radio Link to another transceiver.
     - SEE the comments after "//" on each line below
     - CONNECTIONS: nRF24L01 Modules See:
     http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
     1 - GND
     2 - VCC 3.3V !!! NOT 5V
     3 - CE to Arduino pin 9
     4 - CSN to Arduino pin 10
     5 - SCK to Arduino pin 13
     6 - MOSI to Arduino pin 11
     7 - MISO to Arduino pin 12
     8 - UNUSED
     -
     Analog Joystick or two 10K potentiometers:
     GND to Arduino GND
     VCC to Arduino +5V
     X Pot to Arduino A0
     Y Pot to Arduino A1

     - V1.00 11/26/13
     Based on examples at http://www.bajdi.com/
     Questions: terry@yourduino.com */

     /*-----( Import needed libraries )-----*/
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    /*-----( Declare Constants and Pin Numbers )-----*/
    #define CE_PIN   9
    #define CSN_PIN 10
    #define JOYSTICK_X A0
    #define JOYSTICK_Y A1

    // NOTE: the "LL" at the end of the constant is "LongLong" type
    const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe

    /*-----( Declare objects )-----*/
    RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
    /*-----( Declare Variables )-----*/
    int joystick[2];  // 2 element array holding Joystick readings

    void setup()   /****** SETUP: RUNS ONCE ******/
    {
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(pipe);
     }//--(end setup )---

     void loop()   /****** LOOP: RUNS CONSTANTLY ******/
     {
      joystick[0] = analogRead(JOYSTICK_X);
      joystick[1] = analogRead(JOYSTICK_Y);

       radio.write( joystick, sizeof(joystick) );

       }//--(end main loop )---

      /*-----( Declare User-written Functions )-----*/

      //NONE
      //*********( THE END )***********

  [1]: https://i.stack.imgur.com/L5eu9.jpg
  [2]: https://i.stack.imgur.com/YsFHC.jpg
  [3]: https://i.stack.imgur.com/KRdBz.jpg
  [4]: https://i.stack.imgur.com/o8wjR.jpg

Receiving code :

    /* YourDuinoStarter Example: nRF24L01 Receive Joystick values

     - WHAT IT DOES: Receives data from another transceiver with
       2 Analog values from a Joystick or 2 Potentiometers
       Displays received values on Serial Monitor
     - SEE the comments after "//" on each line below
     - CONNECTIONS: nRF24L01 Modules See:
     http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
       1 - GND
       2 - VCC 3.3V !!! NOT 5V
       3 - CE to Arduino pin 9
       4 - CSN to Arduino pin 10
       5 - SCK to Arduino pin 13
       6 - MOSI to Arduino pin 11
       7 - MISO to Arduino pin 12
       8 - UNUSED

     - V1.00 11/26/13
       Based on examples at http://www.bajdi.com/
       Questions: terry@yourduino.com */

    /*-----( Import needed libraries )-----*/
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    /*-----( Declare Constants and Pin Numbers )-----*/
    #define CE_PIN   9
    #define CSN_PIN 10

    // NOTE: the "LL" at the end of the constant is "LongLong" type
    const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe

    /*-----( Declare objects )-----*/
    RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
    /*-----( Declare Variables )-----*/
    int joystick[2];  // 2 element array holding Joystick readings

    void setup()   /****** SETUP: RUNS ONCE ******/
    {
      Serial.begin(9600);
      delay(1000);
      Serial.println("Nrf24L01 Receiver Starting");
      radio.begin();
      radio.openReadingPipe(1,pipe);
      radio.startListening();;
    }//--(end setup )---

    void loop()   /****** LOOP: RUNS CONSTANTLY ******/
    {
      if ( radio.available() )
      {
        // Read the data payload until we've received everything
        bool done = false;
        while (!done)
        {
          // Fetch the data payload
          done = radio.read( joystick, sizeof(joystick) );
          Serial.print("X = ");
          Serial.print(joystick[0]);
          Serial.print(" Y = ");
          Serial.println(joystick[1]);
        }
      }
      else
      {
          Serial.println("No radio available");
      }

    }//--(end main loop )---

    /*-----( Declare User-written Functions )-----*/

    //NONE
    //*********( THE END )***********

The output result on the serial is No radio available

dose anyone know where i can go from here ?
or how i can debuge such a problem ?
i dont even know if the problem is with the sender or receiver or both of them

title: Not able to make my NrF24L01 work

Answers: 2

body:
Just added a 47uf capacitor to the pin 1 and 2 in  NF24L01 ,then every thing worked fine

this is the new setup .

![enter image description here][1]

  [1]: https://i.stack.imgur.com/mrPtm.jpg

body:
If adding a 47uF capacitor between the 3.3V and GND is not enough to solve your problem, try to:

 - power the NRF24 through a 3.3V voltage regulator (like a LM1117T-3.3) and power the voltage regulator (NOT the NRF24) through the Arduino's 5V pin. Indeed, the Arduino 3.3V pin is limited to 150mA output, while the the 5V pin can provide you about 400mA.
 - don't use a breadboard: the NRF24 chip is very sensitive, so try to connect it directly to the board through jumpers or PCB / perf-board.
 - Add to your code the line:

        radio.setPALevel(RF24_PA_MIN);

and check if it works in that way; if it does, the issue is probably about the chip's current consumption.

Hope this helped


body: I found a lot of methods on the internet and I was wondering what would be the best method to send data from sensors connected to Arduino to a MySQL database in a WAMP server continuously.

title: Arduino to mysql database?

Answers: 1

body:
There is no absolute "best" way, there is only the way that "works best for your situation".

In a nutshell, the different methods that I can think of, and their pros and cons, are:

* Simple HTTP GET with parameters

Quick to implement, light weight, but not very secure or robust. Perfectly fine for things like "send the temperature once a minute" etc, but crafting very long GET requests with lots of parameters can severely impact on both your RAM and your sanity.

* HTTP POST request

Like the GET request it's fairly simple to implement, but needs more RAM since you need to know the size of the data you're sending first so you can send a `Content-length` header.  You can send much more that way though, assuming you have the resources for it.

* SOAP

This is basically HTTP POST but with a specially XML formatted body.  It has the advantage that it's a standard protocol for transferring data and commands around the place, so there are plenty of resources to help you.  The main problem is crafting the XML at the Arduino side.

* Custom TCP

Connect to a special port to communicate with your own software.  You define all of the protocol, but you have to write all (or most) of the software too.  This can be more like a serial connection to your computer but through the network.  Good for sending larger amounts of data, such as images from a camera, etc.

* Custom UDP

If you want to send lots of small values very frequently this is probably the best bet.  Harder to implement than most of the others, but the light-weight nature of UDP means you can send data much more rapidly.  Of course, with UDP, you run the risk of losing packets since it's very much a "fire and forget" protocol - you send a packet and hope it gets there.  Fine if you don't mind missing the odd bit of data, say for higher speed temperature logging.  Of course, you have to write the server side software yourself, but there's plenty of resources to help you with that online.

So it's really not a case of "best" but "most suitable".  Define what the data is and how often you want to send it, then think about how complex you are willing to get with your programming.

Nine times out of ten a simple HTTP GET request fits the bill.


body:
I am developing AVR microcontollers in Atmle Studio and sometimes I am using Arduino libraries(such as LiquidCrystal).

When I initialize `LiquidCrystal lcd(12, 11, 5, 4, 3, 2);` I don't think Arduino Libraries use registers and ports of ATmega2560, although I am building my code with the device selection ATmega2560 option of Atmel Studio. Atmel Studio works in order to program 2560 but how can I tell Arduino libraries that I am using 2560?

title: How can I indicate that I am using ATmega2560 so that Arduino libraries understand it?

Answers: 1

body:
There are two things that have to be considered here.

One is telling the code what board you are using, so it can compile in the right optional parts, and the other is getting the right pin mappings.

The first can be covered simply with a compilation flag:

    -DARDUINO_MEGA2560

That defines the macro `ARDUINO_MEGA2560` which is used in some places to know which board you are using.

Second is the pin mappings.  These are stored in the file `pins_arduino.h` and each board variant has its own copy.  You need to ensure that this file (and be sure to get the right one) is included in your code in the right places to ensure that the pins can be mapped right.  If you are including the whole Arduino core (which it sounds like you must be in order for things to even have a hope of working) then you just need to ensure that you have the compiler set up to include the right copy of the `pins_arduino.h` file.

That means making sure you have an include path in your compile command line which points to where the `pins_arduino.h` file is before anything else Arduino core related.

    -IC:\Path\to\arduino\mega2560\variant

or

    -I/path/to/arduino/mega2560/variant


body:
I am trying to use a Raspberry Pi to control a ESC and for that I am sending the instructions for the ESC using serial. My problem is that when i send the instructions i can not interoperate them, and by interoperate I mean check what the first letter is and then remove it and make the Arduino output a PWM signal. My problem is when I use the serial monitor to send an instruction it firstly comes up on several lines, and when I try and look at the first letter of the string the if statement thinks it is true for all inputs of "FirstLetter" my function to get the serial input it

    String readSerial()
    {
      char SerialInput;
      String Data = "";
      if (Serial.available())
      {
        SerialInput = Serial.read();
        Data.concat(SerialInput);
        //Serial.println(Data);
      }
      return Data;
    }

the function that should interoperate  the information from readSerial() is

    void DecodeInput()
    {
      String input = readSerial();
      if (input != "")
      {
        char FirstLetter = input.charAt(1);
        if (FirstLetter = 'U')
        {
          Serial.println("Hello World");
          //input.setCharAt[0, '');
          //SetPower('U', Power);
        }

title: Reading and interpreting Serial information

Answers: 2

body:
Two things immediately jump out at me:

    char FirstLetter = input.charAt(1);

charAt(1) is the *second* letter, not the first - the first is charAt(0).

    if (FirstLetter = 'U')

That is saying "If I have been successful in assigning the value 'U' to FirstLetter then..." - "=" is assignment, you need "==" for comparison.

Also your `readSerial()` function is complete junk.  It's not doing anything at all like you think it is.  You should read this to better understand Arduino serial reading: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

body:
You may want to look at the Firmata protocol, and not re-invent the wheel. Although doing so (re-inventing the wheel) is a good learning exercise, so is understanding something already written.

[http://www.arduino.cc/en/Reference/Firmata][1]

Then move on to the [cool stuff][2] that uses it.

![enter image description here][3]

  [1]: http://www.arduino.cc/en/Reference/Firmata
  [2]: http://cylonjs.com/
  [3]: https://i.stack.imgur.com/ZlA4M.png


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

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

        int pulses, A_SIG=0, B_SIG=1;

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

    void loop(){

    }

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

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

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

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

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

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

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

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

title: Reading quadrature encoder

Answers: 2

body:
    volatile long rawTacho[2];  // interrupt 0 & 1 tachometers

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

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

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

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

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

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

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

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

  [1]: http://forum.freetronics.com/viewtopic.php?f=6&t=5387


body:
I want to make a large clock, 16 inch x 7.5 inch, which will display dd Month yyyy.
What would be the best way to do this?
Does Arduino have a built in clock, and I'd just need logic to turn on/off LEDs on a display that already has dd Month yyyy? Do such displays exist which I can connect to Arduino?

title: Creating a clock using Arduino

Answers: 4

body:
Usually displays with pre-determined shapes for numbers and/or letters are LCD or quite specific parts.
It's entirely doable to just use standard Alpha-Numeric LED displays, there's many tutorials and explanations to be found, if that's something you think you need, you can ask more directly towards that and many of us will probably be happy to explain.

The Arduino has its own little clock frequency. Most are probably powered by some manner of crystal making them quite accurate. Some may have an actual watch crystal running some kind of real-time timer/clock. These matters are device dependent and cannot be answered by me, as I never used an Arduino.
In the basis every Atmel (the controller brand Arduinos use) can be used to maintain a clock and calendar, even the Tiny10 can, given a stable enough external clock source.

On most simpler Atmels (and as such simpler Arduinos) you will have to maintain the numbers and how they translate to the displays yourself, that last part especially if you want your own design in the display. But you'll probably be able to get a reasonably accurate pulse that you can use to update the values with the right interval.
On the larger/more complex chips and/or Arduinos you might get a (near) complete calendar unit that can basically maintain itself and allow you to just read the values. But then those will be more expensive and able to do many, many much cooler things, so that might be a bit of a waste for just a clock and doing the calendar stuff yourself is very good exercise for getting to know the processors you are working with.

For more assistance you will need to be much more specific about what Arduino/Atmel you are using and exactly what manner of display you want: Are blocky number/letter like those in radio's and alarm clocks okay, or do you want something self-designed or more flowy? Are you willing to actually use a dot-type display and learn to use that (no that hard, to be honest, but very different from segment), allowing you to display anything that fits the dots? Like smiley-like graphics, Chinese characters to some extend, etc.

body:
Presuming you intend to have a more or less standard clock the hardest part of project will be accurate timekeeping. This functionality is generally reffered to as RTC i.e. Real Time Clock.

This is probably best offloaded to a dedicated IC, this provides many benefits. The foremost is that small inexpensive modules can be bought that include, a reasonably accurate crystal, the timekeeping IC and a backup battery, so your clock doesn't forget the time when unplugged.

A good place to get started would be [here][1] it goes over using one such chip to get the time (and date).

From there you can apply your own creativity for the clock interface.

One possible option is making a [wordclock][2] interface but setup for dates.

  [1]: http://www.pjrc.com/teensy/td_libs_DS1307RTC.html
  [2]: http://www.instructables.com/id/My-Arduino-WordClock/

body:
It is possible to use the RTC. Another option is to use the Arduino Yun. This has a OpenWRT (Linux) running alongside the Atmel and is a little bit more expensive than the cosyt of the RTC and an Arduino. However, you can query the Linux side for the time with the Arduino command:

    String GetDateAndTime (void) {
      Process time;
      String junkString = "";
      time.runShellCommand("date +\"%F %T\"");
      while(time.available()) {
        char c = time.read();
        junkString += c;
      }
      junkString = junkString.substring(0,junkString.length()-1);
      return(junkString);
    }

And you can update the Linux clock periodically using the code:

    /**************************************************************************/
    // Update Clock on the OpenWRT Side using NTP
    // command kinda swiped from:
    // http://karlduino.wordpress.com/2014/01/14/set-clock-on-arduino-yun/
    void forceNTPUpdate()
    {
      Process date;
      String junkString;
      date.runShellCommand("ntpd -qn -p 0.pool.ntp.org");
      junkString = "";
      while(date.available()) {
        char c = date.read();
        junkString += c;
      }
    }

Update the clock when the code starts to set the time and update as needed  to keep things as accurate as you like.

body:
If you are willing to go the “barebones” route, you can turn an
ATmega328P (the MCU at the heart of the Arduino Uno) into a very
accurate RTC by hooking a watch crystal to it's clock pins. Given proper
calibration, you can get an accuracy of **a few seconds per year**.

This would require some coding though, and is not as straightforward as
using an off-the-shelf RTC. C.f.
[this answer](https://arduino.stackexchange.com/a/9039) for the details.


body:
I wrote a simple code on lillypad with fdti module as below:

    void setup(){
    Serial.begin(57600);
    }
    void loop(){
     Serial.println("ddd");
     delay(500);
    }

but it gives wrong characters at serial port window of arduino ide at 57600 baudrate. But I changed baudrate to 115200 at same window it gives right string as "ddd". Other baudrates do the same thing. What is the solution or where is the problem. I couldnt understand why baudrate shift occurs

title: lilypad works with wrong baudrate

Answers: 1

body:
The baud rate shift occurs because of a mismatch between the speed your program thinks the chip is running at and the speed the chip is actually running at.

You may also have noticed that `delay(500)` is too fast and actually lasts as long as `delay(250)` would.

By the numbers involved it looks like the board is running twice as fast (115200 / 57600 = 2) as your board definition says it is - maybe you're using an 8MHz definition for a 16MHz board, or a 1MHz definition for a 2MHz board, etc.

Make sure you have the right board definition selected in the IDE for your board.


body: Arduino Mega ADK is working well but it is not working circuit in which pull-up/down resistors. It is generating wrong results. I guess, pull-up/down resistors fried. What can i do?

Answers: 1

body:
If you want internal pullup or pulldown resistors on input pins, you can use external ones to do the same job as internal ones if you wish to. Generally, if you use say 100 k Ohms from a pin to V+ or ground then it will act as a pullup or pull down respectively on an input pin, but have much effect on an output pin - which is what you want to happen.

However, it is unlikely that 'fried internal resistors is the reason for code not working and, if this is the case, there is probably unknown and unknowable other damage as well. Pull up/down resistors are usually not actually resistors. They are FETs with high Rds_on values that look resistor like when on. Anything that "fries" them has a reasonable prospect of doing other damage as well.


body: Is there any limit on the number of `Wire.write()` commands consecutively in between the `Wire.beginTransmission()` command and the `Wire.endTransmission()` command for the Arduino Wire library?

title: Arduino I2C maximum number of writes per transmisson

Answers: 3

body:
A quick look at the source code implies that there is a fixed length buffer of 32 bytes:

From the header file `wire.h`:

    #define BUFFER_LENGTH 32

And from the implementation of the `write` function:

    size_t TwoWire::write(uint8_t data)
    {
      if(transmitting){
      // in master transmitter mode
        // don't bother if buffer is full
        if(txBufferLength >= BUFFER_LENGTH){
          setWriteError();
          return 0;
        }
        // put byte in tx buffer
        txBuffer[txBufferIndex] = data;
        ++txBufferIndex;
        // update amount in buffer
        txBufferLength = txBufferIndex;
      }else{
      // in slave send mode
        // reply to master
        twi_transmit(&data, 1);
      }
      return 1;
    }

body:
<!-- language-all: lang-C++ -->

There are **five** buffers used by the TWI and Wire library. They are defined as 32 bytes.

In wire.h:

    #define BUFFER_LENGTH 32

In Wire.cpp:

    uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
    ...
    uint8_t TwoWire::txBuffer[BUFFER_LENGTH];

In twi.h:

      #define TWI_BUFFER_LENGTH 32

In twi.c:

    static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
    ...
    static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
    ...
    static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];

So immediately you are using 5 x 32 bytes (160 bytes).

---

You could increase that to (say) 64 bytes, bearing in mind your 160 byte overhead is now 320 bytes, and you don't have a lot of RAM.

The comments about `endTransmission()` are correct. After a `Wire.beginTransmission()` nothing is actually transmitted until the `endTransmission()` call. This lets you fill up the buffer at your leisure, and then let the library do the writes in a fairly timing-specific way.

---

### Reference

* [I2C](http://www.gammon.com.au/i2c)
* [Wire Library](http://www.arduino.cc/en/Reference/Wire)

body:
The buffer size can be increased.

Should go to the twi.h fil, Wire.h file and set the desired length of the variable: BUFFER_LENGTH


body:
I have two Arduino boards and want to make them communicate with each other over serial. The code I have used for the two boards is almost identical.

- Every one second the "A" board sends a "ping" message over serial.
- The "B" board receives the "ping" message and responds with a "pong" one.
- The "A" board receives the "pong" message and prints it on screen.

**Board A - ping code**

    String inputString = "";
    boolean stringComplete = false;

    void setup() {
      Serial.begin(9600);
      inputString.reserve(200);
    }

    void loop() {

      Serial.print("ping");

      if (stringComplete) {
        Serial.println(inputString);
        inputString = "";
        stringComplete = false;
      }
      delay(1000);
    }

    void serialEvent() {
      while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inChar == 'g') {
          stringComplete = true;
        }
      }
    }

**Board B - pong code**

    String inputString = "";
    boolean stringComplete = false;

    void setup() {
      Serial.begin(9600);
      inputString.reserve(200);
    }

    void loop() {

      if (stringComplete) {
        Serial.println("pong");
        inputString = "";
        stringComplete = false;
      }
    }

    void serialEvent() {
      while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inChar == 'g') {
          stringComplete = true;
      }
     }
    }

The code seems to work, but not exactly as expected. I initiate the serial monitor of the board "A" and expect to see every one second:

> pingpong

Instead I see this:
> pingpong
>
> pong
>
> pong
>
> ....

which means that the pong message is repeated more than one time per second. But I want the "B" board to transmit the "pong" message only when it receives the "ping" one.

Why is this happening? Is there an error in the code? Is there a detail about the serial protocol which escapes me?

Any thoughts would be appreciated.

title: ping pong with two Arduinos over serial

Answers: 1

body:
The problem is with your protocol and also with how you are using the serial.

You are using the same serial channel both for your communication protocol *and* for the reporting of the results.  What you see the B end sees.

So A sends `ping`, and when it sees the letter `g` it responds with `pong`.  You then print that `pong` to the serial, so end B sees `pong`. It gets the character `g` and thinks "That was a ping, I'll respond with a pong", so it does - it sends `pong`, which you then receive and duly print - starting the sequence over yet again.

You either need to separate out the communication and the reporting, or make your protocol look for the whole string "ping" so it never inadvertently responds to a "pong" when it shouldn't.

Here's a good resource about reading serial strings on the Arduino: http://hacking.majenko.co.uk/reading-serial-on-the-arduino


body:
This is probably a beginner question. You've been warned.

I recently purchased a touchscreen (http://www.adafruit.com/products/1651#tutorials) specifically because it left so many pins open to work with and I needed to hook up one, possibly two more items to my Arduino. However the touchscreen fits over the Arduino and covers all the pins.

**How do I access the pins that the LCD isn't using?**

To be specific, I will be adding a Galvanic Skin Sensor on two analog pins.

title: 2.8" TFT Touchscreen Prohibits Access to Unused Pins

Answers: 4

body:
Several options:

1. Use wires to connect it rather than sticking it directly onto the Arduino.

2. Use a header extension to lift the display away from the other headers.

3. Use right-angle headers on the other pins.

body:
Dupont jumper cables are your friend. The most useful ones are male-to-female:

![enter image description here][1]

You can end up with a bit of a tangled mess though when you have a number of shields all side by side.  Not a lot you can do about it though.

  [1]: https://i.stack.imgur.com/zXYaT.jpg

body:
Really I'm just posting to have participated in the forum. Actually I'm new to arduino, and don't even know how many pins the screen actually uses. My version of the screen is a Pixnor screen made by someone who does not really provide technical description, examples, etc.,, and some of the pins are different, or perhaps the entire chip driving the shield is different, so none of the adafruit sketches work. I haven't figured out anything more than how to hook up the touch to an x,y coordinate serial read,, there's an example somewhere that leaves all of the pins unplugged, with the exception of the touchpad data wires, and lets you play on a dark screen with the coordinate plane.

but anyway, my first thought was, really the touchscreen should plug into a protoshield, which would allow you to have a pin-layout which runs to a protoshield, and then your screen would be fixed over that layout, when would then plop onto your arduino, or back off again without disassembling your sensor/input layout. (which means you can still rig up some experiment with the arduino without having to rerig up your screen and sensors.) ,, So I think I'm going to go about getting more proto-shields.

body:
get a Protoshield, a good one and put it between the arduino and the shield
[![Proto shield that will work][1]][1]

  [1]: https://i.stack.imgur.com/b27ia.jpg


body:
Is it possible to run Arduino on a Particle Photon?

I want complete software control over the device so I can connect it to the internet and do stuff without going through Particle's cloud, logins, etc.

title: Compatibility between Particle Photon and Arduino

Answers: 1

body: You can use the new particle dev platform to do this https://www.particle.io/dev


body:
I'm a teacher, working on eliminating some difficulties of Arduino in the name of getting to the fun stuff. Namely, I am building a small Arduino powered device that will collect simple data from sensors like a DHT11, or an accelerometer. That being said, I want to pass simple settings (sample rate, sensor type, etc.) into the device with out reprogramming the board out right. I'm worried I'm over thinking the challenge. Initially, I wanted to pass the settings over serial in Python script, then save the settings to EEPROM and read them when rebooting...but sending strings over serial from Python is proving to be challenging, let alone the EEPROM.

Long term, this will run on an ESP8266 and I'd try to make a simple interface for entering the SSID and password for the Wifi network we want to connect to. Simply plug in the board over USB, run some simple little Python app that asks for SSID, password, maybe sample rate, sensor type and hit configure.

Is there an easier way to build a user interface for adjusting variables in code already running on an Arduino?

title: Adjusting variables in code without reprogramming?

Answers: 3

body:
Take a look at [firmata][1], which allows you to remotely set pins.  There are some robotic frameworks built around it such as as [Cylon.JS][2] that are doing similar things, but you are not over thinking it. If anything probably under thinking it.

The Arduino programming environment is about as simple as it gets. It would be hard to have something easier.  Perhaps some of the Graphic interfaces like those with a LEGO robotics set would be closer to what you want?

![enter image description here][3]

  [1]: http://www.arduino.cc/en/Reference/Firmata
  [2]: http://cylonjs.com/
  [3]: https://i.stack.imgur.com/NWdBb.jpg

body:
If the number of choices is limited (device types, a few selections of sample rate), you might consider a bank or two of DIP switches.

![enter image description here][1]

  [1]: https://i.stack.imgur.com/y1Qf9.png

body:
To avoid the serial input and hit the ground running; you could add a simple hardware input like a potentiometer, rotary encoder, or push button that cycled through settings. I would use the Arduino Serial Library to make the configuration viewable on a computer in the IDE serial monitor or terminal. As long as you pull up/down the buttons and separate the inputs properly, a push button and rotary encoder would be easy to keep modular so that it could be safely plugged in and unplugged without an issue. You could also make an interactive menu over the serial interface which asks you for each parameter. The simplest way would be to detect a button press in your application which would take you to 'config mode', which prompts the user for input via the serial monitor. Once everything is entered, save to EEPROM and restart.

 - [Arduino Serial Library][1]
 - [Arduino Serial Streams][2]

If you are determined to take the Serial scripted approach for programming, and are having difficulty with Python, you could repost or update your question to include your code and explain where you are having trouble, or use a different language. I prefer C#, because I use it for so many different things (From websites to XBOX games), and it lends itself well to rapid development. Java would be another good choice particularly if you would like to integrate with Android ;). All of these are easy to integrate with a GUI.

It sounds like you are having difficulty dealing with strings - and don't feel bad about this, strings can be a complex thing because of how they are construed and work. Check out some examples, and re-implement them to suit your application. Try breaking your strings up into characters (which are a byte in size, easy to fit in EEPROM!) and send them byte by byte - this might be simpler.

 - [Arduino and C# Communication][3]
 - [A better C# Example.][4]
 - [Arduino and Java Communication][5]
 - [Arduino and Python Communication][6]

Saving to EEPROM is trivial and well covered in the Arduino documentation. One thing to keep in mind is that the EEPROM is accessed and used in bytes! What does this mean? - Well, if a larger variable is to be stored, like an int (16 bit on Arduino Uno) it must first be split in half. To do this you would use bit shifting. To give you a quick idea on how this is done, see functions below - note this assumes you only ever save integers to EEPROM (this is in the way I choose to address the memory):

    // Include EEPROM library
    #include <EEPROM.h>

    // location is an int from 0-511 using Arduino Uno with 1KB of EEPROM
    void SaveValue(unsigned int location, unsigned int value)
    {
        // Find addresses to store each half of the integer
        unsigned int saveLocationLower = location * 2;
        unsigned int saveLocationUpper = saveLocationLower + 1;

        // Split the integer into two parts
        byte lowerValue = value;
        byte upperValue = (value >> 8);

        // Save both parts
        EEPROM.write(saveLocationLower, lowerValue);
        EEPROM.write(saveLocationUpper, upperValue);
    }

    int LoadValue(unsigned int location)
    {
        // Find both locations to read using same method as above
        unsigned int saveLocationLower = location * 2;
        unsigned int saveLocationUpper = saveLocationLower + 1;

        // Read both locations
        byte lowerValue = EEPROM.read(saveLocationLower);
        byte upperValue = EEPROM.read(saveLocationUpper);

        // Assemble both halves and return value
        return lowerValue + (upperValue << 8);
    }

 - [Arduino EEPROM Read][7]
 - [Arduino EEPROM Write][8]

If you are feeling really outgoing and adventurous, and have good luck with the C# route - you could check out Microsoft's latest Arduino offerings - they are pretty cool. It makes it easy to integrate Arduino devices with Windows 10 and Phone apps.

 - [WIndows 10 IOT, Getting Started][9]

  [1]: http://www.arduino.cc/en/reference/serial
  [2]: http://www.arduino.cc/en/Reference/StreamReadString
  [3]: http://playground.arduino.cc/Csharp/SerialCommsCSharp
  [4]: http://forum.arduino.cc/index.php?topic=39811.0
  [5]: http://playground.arduino.cc/Interfacing/Java
  [6]: http://playground.arduino.cc/interfacing/python
  [7]: http://www.arduino.cc/en/Tutorial/EEPROMRead
  [8]: http://www.arduino.cc/en/Tutorial/EEPROMWrite
  [9]: http://ms-iot.github.io/content/GetStarted.htm


body: I've recently bought an Arduino Pro Mini, the 3.3V and 8MHz version. The first time I powered it, using the VCC pin, all worked. But, as soon as I attempt using the RAW pin instead, nothing lights up... Is my regulator broken ? Or is this a typical issue ?

title: Unable to power an Arduino Pro Mini through the RAW pin

Answers: 1

body:
I am not completely familiar with that specific board, but according to the schematic there is a solder jumper which is used to isolate the RAW voltage regulator from the rest of the system "for low power applications".

![enter image description here][1]

I don't know off hand if that comes pre-soldered or not, but check it to make sure it is connected, otherwise the RAW input will do nothing.

  [1]: https://i.stack.imgur.com/qoVld.png


body:
Is there a way to use the atmega 32u4 breakout board to make a mp3 player without the mp3 shield?

![atmega 32u4 breakout from adafruit][1]

  [1]: https://i.stack.imgur.com/L56Jq.jpg

title: How do I make a atmega 32u4 mp3 player?

Answers: 1

body:
You don't.

A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding.  And even if you do decode to a linear PCM format, you do not have a good way to output it.

You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity.  You will also end up with a low sample rate, making it hard to avoid audible artifacts.

The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.

If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.


body:
I created a shield for Arduino on a soldering board. The next step shall be to implement the circuit on a PCB. I'm new to this, so I'd like to know what the basic steps in designing a PCB are.

More specifically,

1. What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?

2. Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Of course, any pointers to good tutorials on the Web will be appreciated,  too!

title: What are the basic steps to make a printed circuit board?

Answers: 2

body:
>  What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?

There are plenty of good free ones, or free versions of commercial ones. Use the one that best suits your way of working - they are all different, try some out and find out which you like best.  I use a free one for all my work (but then I am a FOSS junkie).

> Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Generally, no.  It'd be just too costly.  There are small quantity houses around though, and I often use iTead for my prototyping, since they will do batches of just 10 boards at a reasonable cost.

The basic steps in designing a PCB though are:

1. Design it as a schematic
2. Lay it out as a PCB design
3. Get a prototype made
4. Build it
5. Correct the mistakes
6. Go back to 3

If you only want one circuit and it is a pretty simple one you might want to give making the PCB yourself a go - it's quite rewarding and if nothing else gives you good insights into PCB design requirements and how best to lay out a PCB and the tracks for a good reliable etch.  If you have a laser printer the [Toner Transfer](http://hacking.majenko.co.uk/toner-transfer-etching-part-1-designing-the-circuit) method of home PCB production is good.

body:
Software packages are, amongst others

 - [Fritzing](http://fritzing.org/home/) (more target at beginners)
 - [Eagle](http://www.cadsoftusa.com/download-eagle/freeware/) (free for board of size 100 x 80 mm (4 x 3.2 inches)).
 - [KiCad](http://www.kicad-pcb.org/display/KICAD/KiCad+EDA+Software+Suite) (open source)

Companies that make you pcb in small quantities are e.g.

 - [OSHPark](https://oshpark.com/)
 - [seeedstudio](https://www.seeedstudio.com/service/index.php?r=pcb)
 - [Dirt Cheap Dirty Boards](http://dirtypcbs.com/)

I personally create my own double layer PCBs at home. I first started with the toner-transfer method, but now use photo lithography. I etch in Hydrochloric acid and hydrogen-peroxide. I can have a finished board in 1-2 hours, instead of having to wait a week or so. Great learning experience.


body: I've recently purchased an Arduino Pro Mini, 3.3V version. I've planned to use it in a diy remote: I've empty a ps2 remote, just left the buttons, and the board will be inside. The remote will be wireless: I use an xbee, which also fit inside the ps2 controller. To power it, I use a one cell Lipo, which will empower the Arduino and the XBee, here comes my issue: As you've seen, there will be many things an a single ps2 controller, so I try to minimize connections and external components. But, the XBee will take more than the maximum 150mA provided by internal regulator of the Arduino. So, either I use an external regulator, or I directly plug the lipo in the VCC pin if the Arduino. Can the board survive? If the voltage is greater than 3.3V, will it damage the board?

title: Powering an Arduino Pro Mini directly from a LiPo

Answers: 1

body:
The only thing about the 3.3V Pro Mini that is actually 3.3V is the 3.3V regulator.  The main chip (pretty much the only other component) is good for anything from 1.8V up to 5.5V.

Running direct from a 3.7V LiPo or Li-Ion will be perfectly fine.  You might want to disconnect or otherwise disable the regulator though to reduce current consumption - the latest Minis have a solder jumper *SJ1* for doing just that, but older versions you may want to actually cut the 3.3V OUT pin of the regulator or de-solder it entirely.