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

You can use the inbuilt analog comparator to generate an interrupt when a certain threshold is reached. Example circuit (reference voltage on D7, voltage under test on D6):

[![Analog comparator schematic][1]][1]

---

Example code for the Uno:

    volatile boolean triggered;

    ISR (ANALOG_COMP_vect)
      {
      triggered = true;
      }

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ("Started.");
      ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
      ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
            | bit (ACIE)    // Analog Comparator Interrupt Enable
            | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
       }  // end of setup

    void loop ()
      {
      if (triggered)
        {
        Serial.println ("Triggered!");
        triggered = false;
        }

      }  // end of loop

---

The incoming voltage is on the AIN0 (positive) pin which is pin 12 on the actual chip, and D6 on the Arduino board. The reference voltage (negative) pin is pin 13 on the chip, and D7 on the Arduino.

My example does not address the issue of transmitting the results, but that is the easy bit. You might need to build in a test so that you don't transmit the information thousands of times a second.

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


sender: user

message:
Suggest me some good seller for Arduino UNO

I want to start a new project with arduino uno and want to make some amazing mini projects, but i am confused that from where should i buy. So please suggest me some affordable robotic stores.

sender: assistant

body: I recently bought some arduino nano V3 on Aliexpress. It cost me €1.75,- so I immediately bought 4 :P arrived within 10 days. Also the arduino uno R3 (non-official) is only €3,-. Worth the try? I would say definitely, because if you need it for a project you want to leave it in not take it out because you have another idea. Hope this helps.


body:
***I would comment, but my rep is not high enough so consider this a comment:***

Welcome to StackExchange. You should maybe take a look at some guidelines on how to ask good questions.

**First of all:** mind your tune! ASAP in capitals is very impolite and implies a request we MUST fulfil - no we don't. Try to use please and thank you and everyone will be happy.

**Second:** this is a Q&A Site to help people now and in the future, so most of the time questions like: where can I buy this or what book is good are not what this is made for because they won't be valid for very long and have been asked many times before (but answers lost their validity as mentioned above).

**and last but not least:** Google it. Ebay, Aliexpress, Amazon... whatever you fancy. There are many Arduino clones for low prices around. I bought a few UNOs for like 6€ each. They work fine.

With that in mind: welcome again. I hope you find many useful answers around.


message:
How can I see the mySerial.print( ) through the serialmonitor on IDE?

I made an object named "mySerial" like this.

<!-- language: c -->

    SoftwareSerial mySerial(2,3) //pin 2 = RX, pin 3 = TX

also I made pin 13 periodically(0.5 seconds) blink(HIGH/LOW),
then the signal from pin 13 goes directly to pin 2 and pin 0(basic RX pin of UNO). I connected pin 0,2,13 directly with jumper wire.

and in the setup(), I wrote

<!-- language: c -->

    Serial.begin(9600);

    mySerial.begin(9600);

and in the loop(), I wrote

<!-- language: c -->

    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(500);

    if(mySerial.available()){
        mySerial.println("mySerial!");
    }
    if(Serial.available()){
        Serial.println("Serial!");
    }

when I compile this code and operate arduino,
I can only see the "Serial!" on the serialmonitor.
I think this means that the pin 0 can recognize the signal but the pin 2 cant'
How can I solve this problem?

I can't find what I've missed. Please help me guys!

body:
Not the most scientific of approaches, and fundamentally flawed at any rate.

You've toggled the input twice over the period of one second, hardly an emulation of any serial port transmission and so one is letting you know there's been a change of state, the other is letting you know that it hasn't received any valid data.

In any case, when you attempt to read the port both will/should correctly give you nothing as a result because there was never anything there to begin with, nor is there anything coming in at the time.

If you want to test serial port comms like this, you are going to have to make a sketch for each scenario and use a real device to test it (like your actual serial port thru the Arduino IDE). Run some test, print the results and upload your second sketch and do it again.

You could even get a bit fancy and have a bit of fun with this and send a command to the arduino to turn off one serial port and turn the other one on, but that's got nothing to do with what you asked, so I won't be writing the code for that here ;)


message:
PWM help (input changing duty cycle)

Is there a way to adjust the duty cycle (PWM) based upon input gained by a sensor. For example, if the sensor picks up a really high value, it would increase the duty cycle for an LED making it brighter. Can we also do this task without a potentiometer? Can all of this be done "hands-free" by the Arduino?

body:
The example at the bottom of this Arduino reference page does exactly that. If you want to change the way the value varies, you can just modify the variables in a loop or in whatever approach you prefer instead of analogread'ing it.

https://www.arduino.cc/en/Reference/AnalogWrite


body:
There is a simple project that can be done with a photo-resistor for an analog input, a light levels sensor circuit, and an LED for an output.

The software requirement is to have a loop with a delay that reads from the analog pin the photo-resistor is attached and use that value to set the Duty Cycle for the PWM output pin driving the LED illumination level.

You can then test by shading the photo-resistor from the ambient light (I used a sheet of paper rolled up into a tube and placed over the photo-resistor on the breadboard), putting it into darkness, and by using a flashlight to provide more light than ambient in order to test the range and watch the LED dim and brighten.

I have done this project with a Raspberry Pi, which required an MCP3008 Analog to Digital Converter to interface to the photo-resistor circuit since the Pi has only digital pins. Arduino has analog pins so the ADC is not necessary.

The project that I did with my Raspberry Pi is at URL: https://github.com/RichardChambers/raspberrypi/tree/master/project08 with C source code and a link to the manufacturer of the experiment kit I am using which has the details for the actual circuit. What I did was to make the LED illumination level track to the inverse of the value reported by the photo-resistor circuit. So when the light level was low as reported by the photo-resistor then I made the LED brighter.


message:
Arduino : distance measurement between fixed points

I am creating a moving robot which needs to know its exact position on the map(known before, start point also known). My ideas were :

* GPS : this is not accurate enough for me, does not work indoors
* Acc + GYRO + Compass(Magnetometer): MPU-9150 : from that values I could compute the position but as small errors are continuously added after a while it becomes very inaccurate

Finally my idea is to put some fixed points into the area and robot can periodically check where they are and compute its position accurate.

Although I did some googlin' I could not find any appropriate sensor pair to do this. My idea is:

* one(more if no other option) sensor on robot covering 360 degrees
* few fixed points which sends a signal; each different one - let's say : I am the point one. I am the point two etc.
* sensor on a robot is receiving those signals and give me some meaningful value e.g. time from which I can compute the distance from each of the fixed point.
* 10+ meters maximum range is fine for me
* must be cheap (less than 30$ for all)

Questions:

* Do you have any idea of such sensor pair ?
* Or other solution which would fit to my needs?

Bonus:
* The best would be if the fixed points were passive and just reflected the signal sends from robot - but I have no clue if such a thing exist :-)

Thanks in advance for any answers/comments.

body:
Seems to me you are looking for some kinda of SLAM thing. Depending on your knowledge in control theory and your precision goals you can go from simple rotary encoders on wheels to multiple sensor fusion like Extended Kalman filters ([example videos](https://www.youtube.com/watch?v=WRwLwovntvk&list=PL2FC300FEFF72587A&index=1)). Probably the most precise thing you can have is sensor fusion with LIDAR (can be achieved precisions like 1cm), however the price range is way to far from described.

I would start with a small approach and go from there depending on the results I'd get:

 - rotary encoders (easy to calibrate and can be precise enough as a starting point)
 - 9DOF IMU (use a Extended Kalman filter or similar to make an AHRS correction). And in this part I have many advices. You have suggested MPU-9150. I'm not familiar with it but looking at datasheet it seems very good, specially because gyro comes factory calibrated. In past I've used razor IMU / GY-85 (adlx345 + ITG3200 + HMC5883L) and gyro was very precise and low noise. Hope Invesense used the same sensor in MPU . First in hardware: Acc are easy to calibrate just use gravity. Gyros are easy to calibrate but hard to do. Why, because it may be hard to get something that spins at constant RPM and know that value. But as I've said, according to datasheet, MPU comes factory calibrated. Magnetometers calibration can be a bit tricky. Bottom line is you get readings from various points of your robot  in 3D space. you plot all and you will get an ellipsoid. Then you find a transformation equation that maps the ellipsoid into a perfect sphere take a look [this article](  http://www.freescale.com/files/sensors/doc/app_note/AN4246.pdf). Your concerns about Angle random walk can be minimized with kalman filter and similar. [This page](http://www.x-io.co.uk/open-source-imu-and-ahrs-algorithms/) provides much great information and examples in how to make a good AHRS. Mr. Madgwick wrote a really nice algorithm that implements the IMU  filter and have it also written in C (nice for Arduino).

After integrate all things with Kalman and see the results, if things are not good enough, you can add more sensor and provide a better estimation for example: sonars, rangefinders, landmarks with image processing and as suggested also, RSSI and triangulation.

These links might help you in finding your way:

 - [Introduction to Kalman Filters and SLAM][1]

 - [Indoor Location Tracking using Received Signal Strength Indicator][2]

  [1]: http://web.eecs.utk.edu/~leparker/Courses/CS594-fall08/Lectures/Nov-20-Localization-Mapping-III.pdf
  [2]: http://cdn.intechopen.com/pdfs-wm/13525.pdf


body:
I've been working on this also, and have not found a 100% satisfactory solution. Some ideas I've been throwing around include:

* Using an optical mouse to measure ground distance more accurately. This also subject to cumulative errors.
* Some sort of radio transmitters
* A pulse from a magnet, with a compass - these can be highly directional, and could possibly be strength-based, too.
* I read about one robot competition which had a fixed, overhead camera, picking up infrared LEDs; this is processed by a computer, which would then send the data back (e.g. for bluetooth) to the robot.
* The same infrared camera trick, but reversed: a camera pointing up, looking for fixed constelation of infrared LEDs on the ceiling - I would expect this to require more processing than an Arduino has, possibly a raspberry pi could do the trick?


message:
Using Arduino for simultaneous lighting effects

I am building a computer for my son (me).  I'm trying to spark his interest in computer technology, so my idea is to drive multiple case lighting effects with a microprocessor or controller.  I went with the arduino over the pi because of simplicity of the system.

There are several lighting effects I want to drive, simultaneously, and that's where I'm wondering if the arduino is well suited, because the effects need to make use of delay(), and with it being single threaded I'm struggling to figure out how to make each output operate independently.

To give you an idea of what the microcontroller needs to drive simultaneously:

1.  Flicker pattern using random delay values for outer case lighting
2.  Heartbeat pattern for CPU cooling block
3.  Blacklight / UV LED lighting for coolant lines.
4.  Strobing LEDs aimed at the fans to make them look stationary.

Trying to run all these effects in a linear loop with delay() operators just doesn't seem to be feasible.

Do I need to get an UNO for each effect?  Or is there a way of making these outputs operate independently?

body:
Avoid delay() and use specific times of next actions and compare them to millis().  For a random time, set something like:

    now=millis();
    ...
    if(nextFlicker < now) {
       toggleFlicker();
       nextFlicker=now+random(10000);
    }
    if(nextPulse < now) {
       nextPulse=now+ isPulseOn? 100 : 1000 ;
       togglePulse();
    }

    ...

If you are running more than the 50 day roll-over time of millis(), you may need some care to handle the overflows.  See http://playground.arduino.cc/Code/TimingRollover

For the strobing leds, investigate the timer-controlled outputs outputs.


body:
Base the pattern on time, instead of using delays. E.g. if the current time in seconds if odd, the led should be on. If it's even it should be off. This creates a blinking led effect without using any delay.

Some example code:

    long seconds = millis()/1000;
    if( (seconds % 2)==0 )// even
      digitalWrite(led, HIGH);
    else // odd
      digitalWrite(led, LOW);

E.g. to have it blink faster, change `1000` to a lower value.

E.g. to make the led be on shorter than of change `%2` to e.g. `%4` (i.e. 1 second on, 3 seconds off)

etc.


message:
How do I set a constant in setup() that I can use in loop()?

I am new with coding, and I was wondering how I could run something once and define it as a constant. Here is my code:

    int sensorValue1 = analogRead(A0);
    int sensorValue2 = analogRead(A1);
    int g0 = 9.81*9.8;
    int h1 = 48;
    int R = 287.06;
    int a = -0.0065;

    void setup() {
        Serial.begin(9600);
        int p1 = (1.09512*sensorValue2-22.105)*133.3225;
        int t1 = (-0.08126*sensorValue1+65.6597)*274.15;
    }

    void loop() {
        String t = "Temperature:    ";
        String tt = " Celsius";
        String p = "Preassure:    ";
        String pp = " Pascal";
        float celsius = -0.08126*sensorValue1+65.6597;
        float kelvin = celsius*274.15;
        float pascal = (1.09512*sensorValue2-22.105)*133.3225;
        float height = (t1/a)*((pascal/p1)^((a*R)/g0))-1)+h1;
        Serial.println(t+celsius+tt);
        Serial.println(p+pascal+pp);
        Serial.println(kelvin);
        Serial.println( );
        Serial.println(height);
        delay(1000);
    }

body:
You can define Constants using the "const" keyword. Ex:

        const float pi = 3.14;
        const int foo = 12;

https://www.arduino.cc/en/Reference/Const


body:
You can't, and there's other things wrong with your code.

    int sensorValue1 = analogRead(A0);
    int sensorValue2 = analogRead(A1);

Calling functions from the global scope is an incredibly bad idea.  Those are run *before* the board has been properly initialized, and the results you may get from it are not guaranteed in any way, shape, or form.  Instead you must call functions like `analogRead()` from within another function, like `setup()`, or `loop()`.

As for `const` - a `const` is just that - a constant value that can **never** change.  You can only assign a value to it at the moment of creation.

And that means that you can only use it within the *scope* it was defined within.  As you can't do that in the global scope (see above) then you *cannot* use a constant.

So just use a normal global variable.  It will only change when you tell it to change.  Using a `const` only makes sense when you have a *numeric literal* that you want to refer to by name. Using `const` doesn't protect the variable from being changed at run-time by memory leaks, etc, it just protects it from attempts to modify it at compile time - and if possible replace it with the numeric literal that it refers to.

So in summary just use:

    int sensorValue1;
    int sensorValue2;
    int p1;
    int t1;

    void setup() {
        sensorValue1 = analogRead(A0);
        sensorValue2 = analogRead(A1);
        p1 = (1.09512*sensorValue2-22.105)*133.3225;
        t1 = (-0.08126*sensorValue1+65.6597)*274.15;
    }
    ... etc ...

**HOWEVER**: Your program methodology is also completely flawed.  You read the analog values once, and do calculations with them once, then repeatedly display the same values over and over again.

You **must** perform a *new* `analogRead()` of your sensors every iteration of `loop()` in order to update the values in your variables.


message:
Convert INT to Array of Strings

My sensor outputs an int. I would like this to be an array of strings so I can send it with my 433MHz transmitter.

Converting an int to a string to an array of strings seems to be extremely complicated. I've tried multiple approaches.

The error is always:

> array must be initialized with a brace-enclosed initializer

    #include <VirtualWire.h>

    const int led_pin = 11;
    const int transmit_pin = 12;
    const int receive_pin = 2;
    const int transmit_en_pin = 3;
    int mostureSensor = 0;

    void setup()
    {
      // Initialise the IO and ISR
      vw_set_tx_pin(transmit_pin);
      vw_set_rx_pin(receive_pin);
      vw_set_ptt_pin(transmit_en_pin);
      vw_set_ptt_inverted(true); // Required for DR3100
      vw_setup(1000);   // Bits per sec
    }

    byte count = 1;

    void loop()
    {
      // read the input on analog pin 0:
      String sensorValue = String(analogRead(mostureSensor));

      char charBuf[7];
      char msg[7] = sensorValue.toCharArray(charBuf, 7);

      //char msg[7] = {'h','a','l','l','o',' ','#'};
      Serial.println("sending");
      msg[6] = count;
      digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
      vw_send((uint8_t *)msg, 7);
      vw_wait_tx(); // Wait until the whole message is gone
      digitalWrite(led_pin, LOW);
      delay(1000);
      count = count + 1;
    }

body:
toCharArray is a method. It will copy the value from SensorValur to charBuff, it won't return the char array.

Line:

     char msg[7] = sensorValue.toCharArray(charBuf, 7);

Should be:

     sensorValue.toCharArray(charBuf, 7);

charBuf will already have the sensorValue copied.

Check more about "toCharArray" method :

https://www.arduino.cc/en/Reference/StringToCharArray


message:
Arduino sketch does not repeat

I have a Problem with my code.

My Goal is to receive a Ethernet message via UDP and send the message back via CAN.

It works fine but only with the first packet I send. When I send the same packet again there is no Response as you can see in the screenshot.
I´m using the Arduino Due with a Transceiver. The Programm which sends and reads the Messages is Vector Canoe

    #include "variant.h"
    #include "due_can.h"
    #include "Arduino.h"

    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 1, 177);

    unsigned int localPort = 8888;      // local port to listen on

    // buffers for receiving and sending data
    char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

    EthernetUDP Udp;

    void setup() {

    Can0.init(250000);
    Serial.begin(9600);

    Ethernet.begin(mac, ip);
    Udp.begin(localPort);

    }

    void loop() {

        int packetSize = Udp.parsePacket();
        Udp.read(packetBuffer,packetSize);

       if (packetSize)
      {

        int Canframestosend= packetSize/8;    //Divides the Ethernet packet by 8 to match with CAN packet
        int count =0;
        int Rest=packetSize%8;                //Needed if the Ethernet packetsize isn´t a multiple of 8

        for(int j=0;j<=Canframestosend;j++){

        CAN_FRAME NewFrame;                   //CAN frames which are sent
        NewFrame.id=0xFA;                     //ID of the frames
        NewFrame.length=8;                    //Maximum of bytes a Can frame can have

        for (int i=0;i<8;i++){

           NewFrame.data.byte[i] = packetBuffer[count]; //Write the Ethernet info byte by byte on the CAN frames
           count++;
           }
        if(packetSize<count){
          NewFrame.length=Rest;                         //Shortens the last frame to avoid unnessecary zeros
          }
           Can0.sendFrame(NewFrame);

          }

       }
       delay(10);
    }

Maybe there is an endless Loop but I don´t know which and why.

Hope anybody can help me with that!
[![enter image description here][1]][1]

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

body:
I'd guess it's in the if(packetsize) logic -- if you get a packetsize of zero, you still try to read into a zero-size buffer and who knows what would happen.  Move the read inside the if(){...}

See https://www.arduino.cc/en/Reference/EthernetUDPRead

Also, you want to limit the reading to the UDP_TX_PACKET_MAX_SIZE size of the buffer, not to the size of the packet.

Update: The UDP_TX_PACKET_MAX_SIZE is only used in the user code, and nowhere else within the Ethernet Library.  You could use a larger buffer if you need to by defining and allocating a larger buffer and specifying its size in  EthernetUDP.read()  (see https://www.arduino.cc/en/Reference/EthernetUDPRead).


message:
Including Class with .h and .cpp files

I am trying to use a class in .ino file. The code is:

 .ino file

    #include <LED.h>

    int Pin1 = 13;
    int Pin2 = 12;
    int Pin3 = 11;
    LED led;
    void setup() {
      pinMode(Pin1,OUTPUT);
      pinMode(Pin2,OUTPUT);
      pinMode(Pin3,OUTPUT);
      digitalWrite(Pin1,LOW);
      digitalWrite(Pin2,LOW);
      digitalWrite(Pin3,LOW);
    }

    void loop() {
      led.on(Pin1);
      delay(2);
      led.on(Pin2);
      delay(2);
      led.on(Pin3);
      delay(2);
    }

.h file

    #ifndef LED_h
    #define LED_h

    class LED{
    public:
        void on(int);
        void off(int);
    };

    #endif

.cpp file

    #include <stdio.h>
    #include <Arduino.h>
    #include "LED.h"

    void LED::on(int PIN){
        digitalWrite(PIN,HIGH);
    }

    void LED::off(int PIN){
        digitalWrite(PIN,LOW);
    }

Arduino compiler picks the object declaration error:

LEDC:6: error: 'LED' does not name a type

LEDC.ino: In function 'void loop()':

LEDC:17: error: 'led' was not declared in this scope

How should I declare objects in Arduino then?

The way that I am putting the files in folders is like the attached image:

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

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

body:
That version of the IDE (it seems to change from version to version) differentiates between includes with `<...>` and includes with `"..."`.

If you use `<...>` it only looks in the system and library areas.  If you use `"..."` it also looks inside your sketch.

So in your main INO file change the LED include from:

    #include <LED.h>

To:

    #include "LED.h"

and it should compile.


body:
All you need to do is this in the (.ino)

    #include <LED.h>

    int Pin1 = 13;
    int Pin2 = 12;
    int Pin3 = 11;
    LED led1;
    LED led2;
    LED led3;
    void setup() {
      pinMode(Pin1,OUTPUT);
      pinMode(Pin2,OUTPUT);
      pinMode(Pin3,OUTPUT);
      digitalWrite(Pin1,LOW);
      digitalWrite(Pin2,LOW);
      digitalWrite(Pin3,LOW);
    }

    void loop() {
      led1.on(Pin1);
      delay(2);
      led2.on(Pin2);
      delay(2);
      led3.on(Pin3);
      delay(2);
    }


message:
How to make data sent by Python (via serial connection) wait for Arduino to finish current task?

I am trying to make my Arduino micro-controller and my Mac talk together, and I have created a functional serial connection. My computer is sending data to my Arduino, and my Arduino is sending a `1` when it is ready to receive a new piece of data.

I have created an `if-else` statement (Python script below), which is either sending a new line of data to the Arduino or waiting for the Arduino to be ready for receiving a new line of data.

The problem is that `ser.read()` in the first part of the Python script always returns `1`, which means that the script is sending the individual data lines faster than the Arduino connected stepper motors can possible react.

In the Arduino script you can see that I am sending the state-status in the first line of the `serialEvent()` function, which in my world should let the Arduino finish its job, before a new "task" is coming. However, it is for some reason not working. Can anybody help me out here?

**Python script**

    import os
 import time
 import serial

 # Name of csv file with drawing coordinates
 csvFile = "scaled_coordinates.csv"

 # Create serial connection
 ser = serial.Serial(port='/dev/tty.usbserial-A9005bDh', baudrate=9600)

 wd = os.getcwd()
 myFile = open(wd + "/coordinates/" + csvFile)

 state = '1'

 while True: # Exits when there is no more lines to read
        print "test"

  if state == '0': # Wait for Arduino to be ready
   state = ser.read()

  elif state == '1': # Send one more line to Arduino
   line = myFile.readline()
   if not line:
    break
   print line
   ser.write(line)
   state = '0' # Wait for Arduino before reading next line

    ser.close
 myFile.close

**Arduino `loop` function**

    void loop() {
      serialEvent(); // Call the serial function
      if (coord_complete) {
        // Steps to move from currrent to new point
        target1 = steps(x_current, y_current, x_new, y_new, 1);
        target2 = steps(x_current, y_current, x_new, y_new, 2);

        // Start moving
        stepper1.move(target1);
        stepper2.move(target2);

        // Update current position
        x_current = x_new;
        y_current = y_new;

        // Reset variables
        x_complete = false;
        y_complete = false;
        coord_complete = false;
      }

      // Stay in while loop until steppermotors is done
      while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
        stepper1.run();
        stepper2.run();
      }
    }

**Arduino `serialEvent` function**

    void serialEvent() {
      // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
      if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
        Serial.write('1'); // Tell Python that Arduino is ready for one more line
      }

      while (Serial.available() && coord_complete == false) {
        char ch = Serial.read(); // Get new character
        // EDIT : REMOVE THIS LINE //
        Serial.print(ch);

        // If digit; add it to coord_string
        if (isDigit(ch)) {
          coord_string[index++] = ch;

        // Else if ch is ","; then rename to x_new
        } else if (ch == ',') {
          coord_string[index++] = NULL;  // Finish coord_string
          x_new = atoi(coord_string);    // Convert to integer
          x_complete = true;             // Change x_complete to true
          index = 0;                     // Reset index
          memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string
        // Else if ch is a new line; then rename as y_new
        } else if (ch == ';') {
          //Serial.write('0');
          coord_string[index++] = NULL;
          y_new = atoi(coord_string);
          y_complete = true;
          index = 0;
          memset(coord_string, 0, sizeof(coord_string));
        }

        // Ends while-loop when true
        coord_complete = x_complete * y_complete;
      }
    }

## Edit ##

I have changed a bit in the first few lines of the `serialEvent` function (See comments).

Here is a sample of the text file I am reading from:

    239,275;
    1100,275;
    300,400;
    200,400;
    200,300;

body:
> If I'm getting things right, your program fails in the above:
>
> when you send the first message in python, you set state = 0. In
> arduino you enter the serialEvent function and while is triggered. You
> get the first char and send it through Serial.print (but this char
> will be send to python!!!). **For the sake of example let's say the
> first char you get from cvs is '2'**. At this point let's hold on a
> sec and look what happens in python. State was '0' but as you have
> used in arduino `Serial.print(ch);` now state will be updated with
> '2'. This will cause no more triggers of the if-else statements in
> python.
>
> edit:
>
> By now, and also as a debug, add this lines at your code:
>
>     if state == '0': # Wait for Arduino to be ready
>         state = ser.read()
>         if state != '1':
>             print "state: " + state
>             state = '0'
>
>
> However if csv file contains '1's values this will also cause a
> problem. Do you really need that `Serial.print(ch)` in arduino?

**EDIT** The new version since comments
Basically if you are trying to do things before new coordinates, you have to do things in a sequential way. You only ask for info after making all the moves. This is the code I've used to test.
**Note:** I had to adapt your code because was missing the complete arduino code to test it. So I kinda simulated the motor moving etc with delays. Please adapt to your original code

<!-- language: c -->

    #include <string.h>

    bool coord_complete = false;
    byte stepper1_disToGo = 0, stepper2_disToGo = 0;
    // debug things
    int led = 13;
    bool led_state = true, x_complete, y_complete;
    char coord_string[256];
    int index = 0, x_new = 0, y_new = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(led, OUTPUT);
      memset(&coord_string, 0, sizeof(coord_string));
    }

    void loop() {

      serialData(); //ask and process more data

      /*
        // Steps to move from currrent to new point
        target1 = steps(x_current, y_current, x_new, y_new, 1);
        target2 = steps(x_current, y_current, x_new, y_new, 2);

        // Start moving
        stepper1.move(target1);
        stepper2.move(target2);

        // Update current position
        x_current = x_new;
        y_current = y_new;

        // Reset variables
        x_complete = false;
        y_complete = false;
      */
      delay(2000); //replace to simulate actions
      stepper1_disToGo = 10;
      stepper2_disToGo = 10;
      coord_complete = false;

      // replaced to simulate
      /*
        // Stay in while loop until steppermotors is done
        while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
        stepper1.run();
        stepper2.run();
        }
      */
      while ((stepper1_disToGo != 0) || (stepper2_disToGo != 0)) {
        stepper1_disToGo --;
        stepper2_disToGo --;
        digitalWrite(led, led_state); // is moving!!!!
        delay(100);
        led_state = !led_state;
      }
    }

    /*
       you try to use the serialEvent  but the structure of
       your code and the verifications make it act like sequential.
       If you only want to make things after all steps are done there
       is no need for the serialEvent function
    */
    void serialData() {
      /*
         This will never be false because you are stuck in the while

        // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
        if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
        Serial.write('1'); // Tell Python that Arduino is ready for one more line
        }
      */
      //EDIT: wait for info
      while (Serial.available() < 1) {
        Serial.write('1'); /// Tell Python that Arduino is ready for one more line
        delay(500);// ask for info sometimes
      }
      while (Serial.available()) {
        char ch = Serial.read(); // Get new character

        // If digit; add it to coord_string
        if (isDigit(ch)) {
          coord_string[index++] = ch;

          // Else if ch is ","; then rename to x_new
        } else if (ch == ',') {
          coord_string[index++] = NULL;                   // Finish coord_string
          x_new = atoi(coord_string);                     // Convert to integer
          x_complete = true;                              // Change x_complete to true
          index = 0;                                      // Reset index
          memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

          // Else if ch is a new line; then rename as y_new
        } else if (ch == ';') {
          coord_string[index++] = NULL;
          y_new = atoi(coord_string);
          y_complete = true;
          index = 0;
          memset(coord_string, 0, sizeof(coord_string));
        }
        //EDIT: change to AND verification
        // Ends while-loop when true
        coord_complete = x_complete && y_complete;
      }
    }

The structure of your loop should be:

 1. ask for data and wait for it
 2. Read data and parse it
 3. Calculate steps needed
 4. move servos till new positions
 5. repeat

this should be your new code more or less if no mistakes were made because can't really test this version (is missing the variables declarations setup, includes etc...)

<!-- language: c -->

    void loop() {

      serialData(); //ask and process more data
      // Steps to move from currrent to new point
      target1 = steps(x_current, y_current, x_new, y_new, 1);
      target2 = steps(x_current, y_current, x_new, y_new, 2);

      // Start moving
      stepper1.move(target1);
      stepper2.move(target2);

      // Update current position
      x_current = x_new;
      y_current = y_new;

      // Reset variables
      x_complete = false;
      y_complete = false;
      coord_complete = false;

      // Stay in while loop until steppermotors is done
      while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
        stepper1.run();
        stepper2.run();
      }
    }

    void serialData() {

      //EDIT: wait for info
      while (Serial.available() < 1) {
        Serial.write('1'); /// Tell Python that Arduino is ready for one more line
        delay(500);// ask for info sometimes
      }
      // we got info!!!
      while (Serial.available()) {
        char ch = Serial.read(); // Get new character

        // If digit; add it to coord_string
        if (isDigit(ch)) {
          coord_string[index++] = ch;

          // Else if ch is ","; then rename to x_new
        } else if (ch == ',') {
          coord_string[index++] = NULL;                   // Finish coord_string
          x_new = atoi(coord_string);                     // Convert to integer
          x_complete = true;                              // Change x_complete to true
          index = 0;                                      // Reset index
          memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

          // Else if ch is a new line; then rename as y_new
        } else if (ch == ';') {
          coord_string[index++] = NULL;
          y_new = atoi(coord_string);
          y_complete = true;
          index = 0;
          memset(coord_string, 0, sizeof(coord_string));
        }
        //EDIT: change to AND verification
        // Ends while-loop when true
        coord_complete = x_complete && y_complete;
      }
    }


message:
How to flash the "atmega328" with AVRDUDE?

I have an external device using an **ATmega328**, not a **ATmega328-P** as used by the Arduino Uno.

Now I want to use **AVRDUDE** and an Arduino Uno to flash a hex file on this chip. Therefore I removed the ATmega that came with the Arduino and popped in the one without the "-P".

With the Arduino IDE, it doesn't work, so I tried AVRDUDE:

    avrdude -c arduino -P com3 -p ATMEGA328 -b 19200 -U flash:r:sdint.hex:r

However, I'm doing something wrong here, because it does not work:

> avrdude: stk500_recv(): programmer is not responding

> avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

> avrdude: stk500_recv(): programmer is not responding

> avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

> ...

**What commandline should I use to flash an Arduino Uno with an ATmega328?**

body:
This seems to be quite a common problem, and there are a number of problems, each with their own solution.

 - Make sure you have selected the right chip
 - Make sure you have selected the right serial port (when you unplug your board, it should disappear).
 - Make sure you do not have anything plugged in to the tx & rx pins (usually 0 and 1).
 - Make sure your Atmega chip has a bootloader on it
 - Try another cable
 - There may be a problem with your computer - try another computer
 - If using another helps, try reinstalling the USB serial driver
 - Try unplugging the Arduino board, holding down the reset switch, then plugging it in (still holding down reset); continue to hold down reset for about 5 seconds.
 - make sure nothing else is trying to use your serial port
 - Does your chip have a bootloader? Chips bought as part of an Arduino will, otherwise, it almost certainly doesn't, unless it specifically says (in the description of what you bought).

If it does not have a bootloader (or may not have a bootloader) you will need to set this up. You can either use the instructions here: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard (which I never got working) or you can use an ICSP like the http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY_2xifXs (which is what I use) - works great. They can be had for a few dollars from China.


message:
Building an adjustable low frequency PWM controller with Arduino

I am looking for a way to create an adjustable PWM controller capable of modulation frequency from 0-100 (more preferably 0-1000) Hz, duty cycle from 0-100%, and able to accept a voltage range of 5-30V DC. I have looked through Sparkfun and Adafruit for product or PWM shields capable of this and I have yet to find one. Some servo shields can be programmed down to 50Hz and arduino itself can be slowed to like 30Hz using timer0 and timer1 changes. However none of these options make it easy to vary frequency and none of them can accept much more than 6V.

I have searched far and wide and found a few interesting things:

1) [http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/][1]

 This instructable shows an analog un-sensored PWM driver. It would get the job done here however, I need a way to read my Frequency and Duty Cycle

2) [https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/][2]

Here there is a way using pulsein() and other arduino functions to read both frequency and duty cycle as seen above. But then this is also assuming you're PWM voltage is 5V. So maybe you use a 5V regulator on the signal into the arduino? Would something that simple work or would it skew the signal and prevent accurate measurements?

Obviously, if anyone has a better idea I'm open to it. I've been searching for a solution for some time. The trouble really seems to be the low frequency PWM request.

  [1]: http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/
  [2]: https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/

body:
The ATmega328 in the Arduino Uno has a 16-bit timer (Timer/Counter 1) which can do PWM. It has a prescaler that can divide by 1024.  The lowest frequency that it can generate is about 0.12 Hz:

    16MHz / 1024 / 65535 / 2 = 0.1192 Hz

We change the PWM frequency by changing the "top" value. For higher frequencies, lower the top value, and/or pick a smaller prescaler.

(And, really, what does 0 Hz PWM even mean?!? :-)

The duty cycle can vary from 0-100%, with the resolution changing with the specific frequency you generate.

As for the high-voltage... use a motor driver, or darlington, or hexfet, or whatever...

I'm confused as to why you're reading the frequency. With the 16MHz crystal, you set it and you get what you asked for (within the crystal tolerances, temperature, etc.)

At least, that's how I think it works.
Good luck!


body:
Your question is so close to my own project, for a second I thought it was something I posted awhile back, go figure.   I don't expect you to gain from my answer, me coming along to find your question some 2 years, 5 months later. It may be of help to others who pass by this way in the future. I am currently working on the exact same variable duty cycle controller and will offer up my findings.

The following programming code is the result of apx. 5 months of study into the Arduino programming as well as a long failing attempt at getting control through a series of 555 timer chip builds. I shit canned the 555 timer chip & Darlington transistor method. I thought it was too crude, and all 'engineering' schematics never allowed me to have anything more than a 50% duty cycle control. I wanted control over all PWM variables. Today I will be purchasing a metal case, or making one that can hold apx. 5-6 potentiometers allowing me to adjust every possible variable within the PWM domain of parameters (there are more variables than what I have in this code below). I will give you some details in the code first, that will give you some idea of the obsessively precise control I'm demanding from my PWM project:

Getting into the heart of the variable HIGH/LOW control. Be sure to read everything you can to understand fully why these functions are needed. Also, know that with 10 bits the 1023 value allows a resolution of .0043 volt increments (really nice):

    void loop()
    {
    Potentiometer1 = analogRead(PotHzHIGH);
    Potentiometer1 = map(Potentiometer1, 0, 1023, 1023, 0);
    Potentiometer1 = constrain(Potentiometer1, 500, 1023);

    Potentiometer2 = analogRead(PotHzLOW);
    Potentiometer2 = map(Potentiometer2, 0, 1023, 1023, 0);
    Potentiometer2 = constrain(Potentiometer2, 500, 1023);

    Potentiometer3 = analogRead(Pot5Volts);
    Potentiometer3 = map(Potentiometer3, 0, 1023, 1023, 1023); //Hold at 12Volts
    Potentiometer3 = constrain(Potentiometer3, 0, 1023);
    //Potentiometer3 can either be locked at 12volts with the map function, or
    //you can use a Potentiometer to varry the voltage. I illistrate the
    //constant at 12 volts with the map function - low/high both set to
    //1023 & 1023

    digitalWrite(PotHzHIGH, HIGH);
    //turn it ON delayMicroseconds(PotHzHIGH);
    //Keep ON for Potentiometer1=PotHzHIGH Microseconds
    //1000 microseconds = 1millisecond; 1000ms = 1second

    digitalWrite(PotHzLOW, LOW);
    //turn it OFF delayMicroseconds(PotHzLOW); //Keep OFF for
    Potentiometer2=PotHzLOW Microseconds
    //1000 microseconds = 1millisecond; 1000ms = 1second;
    //Largest value within the delayMicroseconds function: 16383microseconds
    //Largest value when converted to milliseconds is 16.383ms, or axp. 1/20th of
    //...a second

}

    //other things to understand about the above program. It is possible to
    //have the LOW written with: delayMicroseconds(PotHzLOW+100);
    //or delayMicroseconds(PotHzLOW*1.1);
    //You can add an additional potentiometer to be the multiplier of the LOW.
    //these added controls prevent the LOW from ever being less than the high.
    //this can come in handy if you wish to work within duty cycles that are
    //between 1% & 50%. It is of interest to me because I am dealing with
    //high frequencies.

timkasey1@gmail.com


message:
Arduino and WS2812 RGB LED Strip "freezing"

I have been working on a project as a gift for my girlfriend for Christmas which involves some a bunch of standard "white" LEDs controlled by shift registers and darlington arrays, and also some RGB LED strips (WS2812B strip, 29 LEDs on strip). Everything is going fine with the white LEDs, but not so much with the RGB ones.

If I leave the RGB leds running for a while all of the LEDs on the strip turn red, except for the first one, which continues to change color. I am not sure how long "a while" is because in "short term" testing, approximately running continuously for an hour, it works fine and all of the LEDs change appropriately, but if I leave it running overnight I wake up with the issue of all red and one single RGB "working". I then have to reset to get it working again. These RGB LEDSs need to be run for long periods (24 hours) of time without "freezing". The rest of the program (with the normal LEDs) continues to work fine despite the RGB ones not.

Let me explain how I am controlling them. `V_rgb` is 5V (5V - 8A power supply), which it is also grounded to. Then the data line, `C`, is connected to an Arduino Uno, on pin 12, which is a PWM pin.

In software, I am using a Adafruit Neopixel Library to control the RGB LEDs and write their respective colors, based off the examples given in their git repo and the tutorial [here](http://www.tweaking4all.com/hardware/arduino/arduino-ws2812-led/).

I have pasted my code below in case that may help, but honestly I am not sure if it is software or hardware related. (unrelated code has been removed)

    #include <Adafruit_NeoPixel.h>
    #define rgbPin 11
    #define numRGBleds 29

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(numRGBleds, rgbPin, NEO_GRB + NEO_KHZ800);
    int colorStep = 0;
    int rgbIndex = 0;

    void shiftColor() {
      int i = 0;
      for (i = 0; i < numRGBleds; i++) {
        int idx = (rgbIndex + i) % numRGBleds;
        int colorVal = round(i * colorStep);
        strip.setPixelColor(idx, Wheel(colorVal & 255));
      }
      strip.show();
      rgbIndex++;
    }

    uint32_t Wheel(byte WheelPos) {
      WheelPos = 255 - WheelPos;
      if (WheelPos < 85) {
        return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
      } if (WheelPos < 170) {
        WheelPos -= 85;
        return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
      }
      WheelPos -= 170;
      return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
    }

    void setup()
    {
      strip.begin();
      strip.show();
      rgbIndex = 0;
      colorStep = 255 / (numRGBleds - 1);
    }

    void loop()
    {
      shiftColor();
      delay(1000); // Redo every second
    }

My thoughts of what it could be are the following, let me know if any make any sense or are known issues:

 - Having issues with `micros()` value rollover
 - Overheating
 - Noisy power supply
 - Defective LED strip
 - black magic?

Thanks in advance for any help.

**UPDATE**

My current solution to the problem is to just reset the board using the watchdog functionality. It reboots in a few milliseconds and sometimes flashes in the process, but I would like to figure out the real problem.

**UPDATE #2**

So with the reset solution, I left it running overnight and it did not freeze which leads me to think it is definitely a software, not hardware, issue. I have changed some of the wiring and coding to make sure the watchdog reset is not noticeable. It resets every half hour or so. This will make sure all of the memory is cleaned, except stuff I store in the EEPROM (which I do use to make the reset less noticeable). This reset delays processing by a few milliseconds, but time is not critical, so it is not a big deal.

I still however, would like to know a more elegant way of doing this. The software reset is a bit "hacky"

body:
Try changing `rgbIndex++;` to `rgbIndex=(rgbIndex+1)%numRGBleds;`. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.

Also try changing delay(1000) to delay(1). That way the problem might pop up a lot faster.


message:
Yun availability

I am starting a project that may need a lot of Arduino Yuns in the future, but today I found that they are not available on the official Arduino store.

What's the story on the Yun? Is it being replaced by something newer? Also, how can I evaluate the longer-term availability of this board?

In case it's helpful, I need the dual-processor setup, wifi capability, and extra storage of the Yun.

body:
In short: Who knows?!

With all the in-fighting between the two Arduino factions (Arduino.cc and Arduino.org) it's anyone's guess what boards are going to be available this time next year, and of those that are available which of the two factions will be producing and distributing them.


message:
Identifying Arduino-compatible board signatures in code

I am developing libraries for compatibility across a number of Arduino/compatible boards. I know that Arduino boards can be identified by the test "#if defined (__AVR_ATmega328P__)" and compatibles as well: #if defined(__TM4C123GH6PM__).   There are a few lists of these IDs on the web but are all outdated. I have searched various cores and library code and do not see where these defines are actually defined.

Nick Gammon's [Sketch to detect Atmega chip types][1] identifies the chip type. What I'm looking for the board type to define pin configurations, etc.

Where and in what format are board signatures stored? Is there c++ code that can find the board signature? Does anyone know of a site where these signatures are stored and updated by the Arduino community?

  [1]: http://www.gammon.com.au/forum/?id=11633

body:
In the `boards.txt` file each board has a board type definition, such as:

    uno.build.board=AVR_UNO

When you compile your sketch that is adapted into a "board" define by prepending `-DARDUINO_` to it and adding it to the compilation command line - so that one becomes the same as `#define ARDUINO_AVR_UNO`.  You can, of course, test for it with:

    #ifdef ARDUINO_AVR_UNO
    ....
    #endif

The location of the `boards.txt` file varies with different versions of the IDE, but every installed core will have one.  Look around in your Arduino program folder in the `hardware` subdirectory.


message:
Why does an LED sometimes flash when increasing brightness?

This is admittedly a cross-post from [LED fade malfunction (random flash) ][1] but I can't get an answer on the Arduino forum.

I was mucking around with some very basic code and I noticed that when repeatedly holding an LED at 0 brightness for 1 second and then fading in to full brightness, a small flash would occasionally happen at the beginning of each fade (seemingly random).

    int led = 11;
    int brightness = 0;

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

    void loop()
    {
      if(brightness >= 256) //checks if brightness has passed 255, resets to 0
      {
        analogWrite(led, 255);
        brightness = 0;
      }
      analogWrite(led, brightness);
      if(brightness == 0)
        {
          delay(1000); //LED off for 1 second
        }

      brightness+=1; //increment brightness
      delay(20);
    }

So, the thing that has me completely perplexed is that I can use a different piece of code (below) and the flash goes away!

    int i = 0;
    int led = 11;

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

    void loop()
    {
    analogWrite(led, i);
    delay(6);
    if(i%6 == 0)
    {
      i = 0 ;
      delay(1000);
    }
    i++;
    }

Has anyone got any clue as to why this would happen? Both programs have basically the same code, except for that i is reset to 0 in the first program whereas in the second, i keeps incrementing past 255 so that analogWrite 'overflows.' I think it must be a firmware, (or maybe a software?) problem.

There is a video on youtube of it happening here, [Arduino - fading LED problem][2].

  [1]: http://forum.arduino.cc/index.php?topic=360468.0
  [2]: https://www.youtube.com/watch?v=mbBJWjYScng

body:
<!-- language-all: c -->

According to the links you provide from the arduino.cc forum the question is more or less answered. If not that important, just avoid `analogWrite(led,0)` and make it `analogWrite(led,1)`

if you still want that `analogWrite(led,0)`, I've tested your code with the advice and it seems to work OK when changing the register manually:

    #include "wiring_private.h"

    int led = 11;
    int brightness = 0;

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

    void loop()
    {
      if (brightness >= 256) //checks if brightness has passed 255, resets to 0
      {
        brightness = 0;
        sbi(TCCR2A, COM2A1);
        OCR2A = 0; // set pwm duty
      }

      analogWrite(led, brightness);
      if (brightness == 0)
      {
        delay(1000); //LED off for 1 second
      }

      brightness += 1; //increment brightness
      delay(20);
    }

#Edit: to explain what those "strange codes" are
I'm not very expert in this field to explain how exactly this works but basically `sbi` is function defined in a macro by Atmel (?), it stands for "**s**et **b**it **i**n" and is used to change registers of ATmega chips. So basically what I did was change register defined by the macro `TCCR2A` (why? because it is the register that controls PWM in pin 11) and pass the bitmask `COM2A1` (this is a mode of compare defined in datasheet) and `OCR2A` is a register used to store the compare value that defines duty cycle. Imagine a counter that every time it receives a tick from a signal clock it compares the value of the counter with the value stored in `OCR2A` and it sets the pin high or low if that value as been passed or not (more or less like this, depending on the mode stored on `TCCR2A`).

But in fact I've not done some black magic. I just looked into the code of `analogWrite()` and that is the way they use to set a value of PWM in pin 11:

    void analogWrite(uint8_t pin, int val)
    {
     // We need to make sure the PWM output is enabled for those pins
     // that support it, as we turn it off when digitally reading or
     // writing with them.  Also, make sure the pin is in output mode
     // for consistenty with Wiring, which doesn't require a pinMode
     // call for the analog output pins.
     pinMode(pin, OUTPUT);
     if (val == 0)
     {
      digitalWrite(pin, LOW);
     }
     else if (val == 255)
     {
      digitalWrite(pin, HIGH);
     }
     else
     {
      switch(digitalPinToTimer(pin))
      {

    ...

              #if defined(TCCR2A) && defined(COM2A1)
       case TIMER2A:
        // connect pwm to pin on timer 2, channel A
        sbi(TCCR2A, COM2A1);
        OCR2A = val; // set pwm duty
        break;
        #endif
    ...

    }

So basically I just used that info to set the register to zero, as suggested from the arduino.cc forum link that you have.

If you want to know more about PWM in Arduino, [this site](http://www.righto.com/2009/07/secrets-of-arduino-pwm.html) has a lot of info and explains a lot of the modes of registers also.


message:
Newbie - What is the Difference Between Power Supply's GND and Arduino's GND?

I am new to electronics and Arduino.

What is the difference between power supply ground and Arduino's ground. If I connect my LED cathode to power ground, it doesn't work. But if I connect it to Arduino ground, it works. Aren't all ground the same?

Please see picture below.

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

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

body:
I would expect there to be no difference between the grounds in your circuit, and after looking over the [schematic for the board][1], it appears that all of the grounds are common.

I think the most likely explanation for what you're seeing is a quirk in the breadboard. It may be that the side busses are split at the middle of the board, or perhaps there was just a bad connection somewhere on the ground bus on that side of the board.

One way you could troubleshoot it further would be by jumping the ground side of the LED to the power supply ground. Start with the ground on the regulator and then work out until you find the spot where you loose continuity.

[1]: https://www.adafruit.com/images/product-files/2377/Arduino-Pro-Mini-v14.pdf


body:
I agree with the other answers.  On rare occasions, TO-xxx packages have bizarre pinouts, but the 78xx series does, in fact, have ground on the middle terminal.  This is surely a split power supply in your breadboard power busses, or else a bad breadboard.  Many breadboards have splits in the power rails halfway down.  I've also seen some with splits more often than that, perhaps as much as disconnects every 5 (or 5 pairs of) contacts.  I have a breadboard, for example, which allows for 6 different voltages, all in a single line, from various connections to a battery pack.  I'd recommend buzzing the breadboard before starting to use it.

I've also had breadboards whose contacts fail after using larger AWG wires in particular holes (or forcing odd connections, such as machined contacts on IC's or sockets, or larger stamped rectangular pins on a TO package such as this) into breadboard holes. The last thing you want to worry about when building a prototype of a new design is whether or not the wiring under the breadboard works.

Many multimeters have a continuity test capability for diagnosing problems such as these, BUT make sure no power is connected (or you could damage the meter on this setting).


message:
Library to correct time for DST

I am using a Uno as a data logger with a DS1307 RTC and the following libraries Time.h DS1307RTC.h

The DS1307 does not have any support for DST and neither library includes Time Zone.

Are there any libraries which adjust for DST?

----------

I used the `Timezone` module to correct my times for DST.
It took a little time to sort it out, so I though I would post the steps I followed.

Customise `WriteRules` for my Timezone.
I copied rule from `WorldClock`.
NOTE also need to modify Timezone in setup(void)
Run `WriteRules.pde` to write rules to EEPROM address 100

Run `TimeRTCSet.pde` to set RTC time to UTC.
Start Serial Monitor.
In Terminal send time to Arduino

 date -u +T%s > /dev/tty.usbmodemFA131

Run `HardwareRTC.pde` to demonstrate time display in UTC & local

I modified my sketch by including the following code:-

    #include <Timezone.h>    //https://github.com/JChristensen/Timezone
 ⋯
 Timezone myTZ(100);       //assumes rules stored at EEPROM address 100
 TimeChangeRule *tcr;        //pointer to the time change rule, use to get TZ abbrev
 time_t utc, local;
 ⋯
    utc = now();
    local = myTZ.toLocal(utc, &tcr);

body: You could use the [Timezone library](https://github.com/JChristensen/Timezone).


message:
Why can't I include a library in another one?

I am trying to create a new library that uses another existing library.

The original library declares a way to create an object called Multiserial that can be created in the main file and the program is correctly compiled.

However, when I include this library in a second one and I try to build the program, then the IDE returns an error that says:

> In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:27:0,
                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:26,
                 from MultiSerial.h:17,
                 from maqMODBUSmst.h:5,
                 from maqMODBUSmst.c:1:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Printable.h:25:1: error: unknown type name 'class'
 class Print;

Even if the library only contains the include of the first one.

body:
Nested includes lead to these convoluted error messages and are in general, a PITA for the next reader to follow & understand. It is better practice for the dependent library to test, at compile time, for the existence of its required libraries and for each one found missing, issue:

    #error DepLibe.h: Missing required include file ReqLibe.h
Most .h files guard against multiple-inclusion by

    #ifndef _REQLIBE_H_
    #define _REQLIBE_H_
    // library definitions here
or some variant of it. DepLibe.h can test for these guard symbols. DepLibe.h should document the dependencies in prominent comments.


message:
Arduino graphic interface

I succeeded in programming a system of thermoregulation using Arduino.  This system holds the temperature of a plate at 37°C. I used a PID corrector to realize this.

What I want to do now is make a graphic interface that can communicate with the Arduino, allowing me to see a graph of the temperature.

I would like an explanation of how to send temperature data to a graphic interface using Arduino Uno.

body:
It all depends on what graphical interface.  There's many ways of doing it.  You have TFT screens that the Arduino controls directly (take a look at UTFT for example), or serially connected displays (such as the ones offered by 4D Systems).

First you need to decide what kind of display device you want to use - and that is deciding:

1. What your budget is
2. How many Arduino resources you can dedicate to the interface
3. What IO you have available on your Arduino

And more.


body:
There are two main possibilities.

The first one is to make a GUI on the Arduino itself. Add a TFT screen, touchscreen if you want the user to interact, or a non-touchscreen (cheaper) if you just want to display. Then, within your Arduino code, you can display the temperature data, and if you go the touchscreen route, interact with the user.

I own a couple of [Arduino Esplora][1] devices, and they would be near perfect for this, as they have a non-touch TFT screen, a joystick, buttons and a pot. All the equipment you need to display the temperature. Oh, and it has temperature and light sensors onboard.

[![My Esplora Sketch][2]][2]

The second way would be to make a GUI on your desktop/laptop machine. In your Arduino code, you could send your temperature data through USB (Serial), Bluetooth (SoftwareSerial), WiFi, Ethernet, nRF, etc etc etc. If you don't mind having the Arduino tethered to your computer by a cable, USB<-->Serial is the easiest solution. The software on the computer listens on a serial socket and when it receives temperature data, it displays it within its GUI.

HTH

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardEsplora
  [2]: https://i.stack.imgur.com/8k8mC.jpg


message:
Arduino due dying after connection, gets hot

I have an Arduino Due (made in Italy) which suddenly (after working nicely for some time) started a new behavior: If I connect it to my computer via USB it is recognized and connects. The "On"-led is turned on but gets darker within seconds until it's off and the connection breaks. This happens with both USB ports. The area around the usb ports gets hot and especially the "504L" next to the reset buttons. (I just have my finger to measure the temperature, so it could also be something else in this corner).

What could have happened to the board? And is there anything I can try to revive it?

Update:
@GuitarPicker: It's the object labelled "0105" in your image, so it's probably the F1 fuse. If I connect the top USB, F1 gets hot, if I use the lower usb, F2 is activated.

- There is nothing connected to the board. Before that, I used it to send SPI commands where I might have connected some of the SPI pins in the 6 pin group.

- The board is placed on wood, so there should be no external connection

- No smoke or visible damage.

body:
The "504L" is a 500mA polyfuse.  If more than 500mA is attempted to be drawn through the USB port it will get hot which causes the fuse to "trip".  When it cools down again it will "reset".

Why is too much current being drawn through the USB port?  Well, that's what needs answering to know just why your board is misbehaving:

1. Do you have lots of things plugged into the board - like LED strips, motors, etc?
2. Is the board sat on something metal causing a short circuit? (I did that by having some loose change on my desk once).
3. Have you physically damaged the board and caused some pins of one of the chips to short together?
4. Has the Magic Smoke™ escaped from one of the chips rendering your board broken?


message:
OOP vs Inline with Arduino

I have been programming for quite a while now but I am new to Arduino and AVR Programming. The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples?

In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?

Say for example we have a Class:

    class SomeClass(){

    private:
       int x;
       int y;

    public:
       void foo();
       void bar();
    }

    SomeClass thisClass;
    thisClass.foo();
    thisClass.bar();

Would there be any performance or memory gains designing the program in a more inline fashion like:

    int x;
    int y;

    void foo(){ /*** Do something ***/};
    void bar(){ /*** Do more stuff ***/};

I tried doing some searches on Stack Exchange and Google but couldn't find quite the answer I am looking for the closest thing I was able to find was [this Stack Exchange Question.][1]

The reason I am asking about this is I have a project that needs to be as light as possible and I am not clear how I should be designing my program in this environment.

----------

**Edit**

Thank you for the answers, this has shed light on things. There is one thing that I am not quite clear about.

Say you have a class that you are designing that utilizes the u8glib as follows:

    class UserInterface{
    private:
       U8GLIB_ST7920_128X64 Display;

    public:
       UserInterface();
    }

How would you get around using "Dynamic Memory" like:

    UserInterface::UserInterface(){
       UserInterface::Display = U8GLIB_ST7920_128X64(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
    }

  [1]: https://arduino.stackexchange.com/questions/6690/what-are-the-benfits-of-global-variables-over-static-class-members

body:
The reason you can't find the answer is because the answer is both Yes and No.

For basic class stuff - defining your class with methods etc and instantiating objects from it - there's little difference in the end result compared with "vanilla" C.  The compiler's optimizations are so good now that performance is just the same. Yes, there may be slight increases in memory use since you're passing an extra pointer with each method call (instead of `foo(int x)` you have `foo(MyClass *this, int x)`) but that's so small as to not be noticeable.

The big differences come when you start playing with *polymorphism* and other advanced topics.  When start doing these complex programs the compiler is not always unable to work out which functions are required and which aren't, and it's not able to cut out the unused functions (*"garbage collection"*). So you may well end up with bigger code.

That doesn't mean slower code, just chunks of code that are hanging around that never do anything.

Of bigger importance is managing your dynamic memory better than you are used to.  Since there is such a small amount of memory the heap is very small, and as a result it gets fragmented very easily.  Dynamic creation and destruction of objects (`new myClass`, `delete myClassObject`, etc) is very bad.  Class objects really need to either be statically defined (in global scope is the most common) or temporarily allocated on the stack (local instances).  Otherwise you're asking for trouble - and the first you will know of it is strange things happening (no error reports or exceptions, you see...).


body:
> The main question I have about programming these Micro-controllers is
> are there major differences in designing code in Object Orientated
> Classes vs the more traditional inline programming I have seen in many
> examples?
>
> ...
>
> In other words in the world of Arduino/AVR Controllers are there any
> savings with Memory and Performance utilizing classes or visa versa?

Yes, there is a great difference between using C or C++ for small scale embedded systems such as Arduino/AVR. C++ allows more information to be provide for compiler optimizations.

If you are implementing an OOP framework, platform or runtime C++ and classes can also help with software architecture and reuse. In [Cosa][1] a number of OOP design patterns are used to achieve interfaces for both application programmers and device driver programmers. The most common is [delegation][2].

Using abstract classes, virtual member functions, inlining, and templates can help achieve lower foot-print and higher performance than traditional implementations. As an example the Cosa Pin classes are X5-X10 faster than the Arduino core and at the same time smaller in foot-print. Please see the [benchmarks][3].

One thing to "unlearn" from traditional C++ programming is the usage of new/delete (malloc/free). With SRAM size of only a few Kbyte using a heap is very much a risk. The answer is static classes and stack based data.

There is much more to be said about OOP framework architecture but I hope this helps answer your initial questions.

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa
  [2]: https://en.wikipedia.org/wiki/Delegation_pattern
  [3]: https://github.com/mikaelpatel/Cosa/tree/master/examples/Benchmarks


message:
5v to 4.3v Regulator - For SIM800 module

I want to build a simple voltage regulator  3.8-4.2V with atleast 2A Peak Current Capability for my GSM Shield (It doesn't have regulated power supply), I don't want variation or it may burn the board.

Using voltage divider won't help here as there can be variations.
Somewhere i read LDO are for for this task but i am able to get only 3.3v regulator with 800mA supply.

Can i use 3.3v to power the same ?

body:
Consider using a [buck converter](https://en.wikipedia.org/wiki/Buck_converter) for this.  Search ebay for "buck converter" and you will see items like "[Buck Converter Step-Down Adjustable Converter Power Module Regulator LM2596](http://www.ebay.com/itm/261956897110).  That title indicates several things:  the converter is adjustable, it steps voltage down, it's a regulator, and it's based on TI's [LM2596](http://www.ti.com/product/lm2596) chip.  It's rated at 2 A continuous, 3 A peak.

A buck converter has some advantages over a linear regulator:

1. Lower dropout (in general), ie, the input voltage has to be at least as much as the output voltage, possibly plus a small margin for one FET loss, but doesn't have to have the 1.1 to 1.3 volt margin typical of an LDO regulator.

2. Higher efficiency (in general).  For example, 95% is not uncommon.  (The ebay item mentioned above shows 92%.)   A linear regulator, whether LDO or not, turns the input-to-output voltage difference into heat.  A buck converter, on the other hand, uses an inductor and a capacitor to store energy; it refills the capacitor at a controlled rate via the inductor as often as necessary to deliver the required load.  The inductor's DC resistance wastes energy, but that resistance can be kept small.

3. Smaller parts due to high frequency switching operation.  As operating frequency is increased the inductor can be made smaller.  On the other hand, higher frequencies lead to higher switching losses, so there's a tradeoff.  Note, some SOT3-sized (~1.4 mm x 2.9 mm) transistors eg NTR4503 are rated over 2 A at 25°C and might be usable as an output FET for a buck converter chip, and inductors and capacitors also are available in sizes probably as small as you are looking for, but buying them and building your own converter is unlikely to be cost effective.


body:
> I planned to use 3.7v LIPO battery

That's what your SIM800 module is *intended* to be *directly* powered by, *without* any intervening boost or buck converter.

Behind all the misdirection of a title that doesn't describe what you are actually trying to do, your question is an exercise in going around in a circle right back to where you started.  Don't try to convert energy from the lithium cell to some other voltage and then from there to the allowed input range of the SIM800 (which is very intentionally that of a single lithium cell), rather use the parts as they were intended to be used.

> i guess it has current 800mA..

No, it has a capacity of 800 milliamp hours, not 800 milliamps.

A phone or RC model type lithium cell you would find today would have a "C" rating of 10 or better, but even if we assumed one of only 5, that would predict that your cell should be expected to be able to support pulse loads of 5 times the one-hour draw rate, which would be .8 * 5 = 4 amps.


message:
Addressing contents of array using incrementing variable

Why would this simple code which prints out array values give the right value 240 when the array is addressed with index directly addressed by number
but give 184 when addressed usin a varibale n that is incrementing?

    PROGMEM const unsigned char COLSA[8] = {
          240, 240, 240, 240,
          240, 240, 240, 240};  //Stored pattern

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

    void loop() {
      int n;
       for(n=0;n<8;n=n+1)
        {
          Serial.println(n);
          Serial.println(COLSA[1]);
          //n=2;  //If I use n in this way things are fine. It prints 240. Else it prints 184
          Serial.println(COLSA[n]);
        }
         delay(100);
    }

body:
Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.

However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.

**BUT** the array *isn't* in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong.  You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".

PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but *they're not the same room*.

So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:

         Serial.println(pgm_read_byte_near(COLSA + v));

That says "Give me the byte that is located at *v* addresses on from the start of the `COLSA` array in PROGMEM.


message:
Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding

I'm newbie in Arduino Dev

I got Arduino Uno R3, at first it just worked fine.
I tried to upload my whole project sketch which almost up to the max size of arduino memory.

Then suddenly the upload failed, and i can upload any other sketch even an empty or simple sketch.

I already remove all cables connected, still failed to upload.

I really dont know how to fix this.

body:
First stop for me is always the connections (which you've done), the sketch itself (which doesn't sound likely) and then the COM port / baud rate.  If your sketch involves anything with the serial connection, ISR's or power supplies, that could be an issue with the Arduino not listening.  It sounds like you've covered this as well by trying simple sketches.  Next, check the COM port on the host computer (sometimes it changes in Windows) and inside the IDE, the baud rate, and open the IDE serial port and wander through baud rate settings until you get something legible as a response in the serial window.  Also, double check inside the IDE that you still have the correct board selected.  Occasionally / rarely, I've had to reboot Windows to cure the problem.

The good news is, this pain is significant enough that you don't usually make the mistake again, and will probably never forget how you solved it....


message:
Help putting an Arduino project on the Internet

I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?

Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?

And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs?

Thank you for your help, and if you need any more info about the project, I will be happy to edit this post.

body:
> What would be the most efficient, easy to use and reliable system?

What seems to me is that you need what is called Unified Application Routing. There are various technologies to do that but what I suggest is [WAMP ](http://wamp-proto.org/) (Web Applicaton messaging protocol, do not get confused with wamp server stack) but you can check this [comparison table](http://wamp-proto.org/compared/) and select the one that most helps you. Based on that what I suggest is [crossbar.io](http://crossbar.io/). Is open source with a lot of examples, runs on small devices (raspberry pi for example) and is intended for the use you propose, connect devices and let users/apps to get/give information from them. You can publish/subcribe to topics and all devices or apps connected with that topic can read it. Imagine something like an arduino is reading temperatures from a room and publish that data to topic "Temp1". All devices(other arduino, servers, esp8266)  or apps(websites, programs, what ever you clients you imagine) that also are connected at that moment to topic "Temp1" will get that update and act like you want. Wamp also provides a nice feature that is called RPC (remote procedure call). Imagine that you want some real nasty thing in your arduino but it lacks memory or is too slow for that. You can create a program that is, lets say in a raspberry, just waiting for that calculation and returns the result to arduino.

Take a look at this [video](https://www.youtube.com/watch?v=XTIM5W2hLRc) as an example of what you can do with this ttype of techonologies. A lot of demos also in crossbar.io page. The beauty is that you can program in almost any language you are familiar with. They rely on websockets for the majority of things but crossbar is not restricted to it only, you can even use raw sockets.

As for the second part.

If you create your on server (crossbar lets say) inside the lan you have to forward the port he is listening in your router so other outside your network can access it( and possibly will need to get some kind of Dynamic DNS service if your internet provider do not have statics IPs). Or you can host your server outside your network (crossbar has a tutorial for Amazon EC2 and for Microsoft Azure I think). You only need to port forward server ports.
Hwo do you connect arduino? Use ethernet shields, esp8266, choose a yun or make a combo like arduino with usb + raspberry. That way you can also use your raspberry as a crossbar server.

Here is an example of my home made crossbar.io server using 2 python programs , 1 rboard and a raspberry pi has a host to manage my home heating system and the webpage is being accessed from internet, not local lan.

[![Home Heating manager][1]][1]

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


body:
If I'm understanding you correctly, you have your application running on a LAN and now want to figure out how to make it accessible over the Internet (WAN). If you're there the next step is relatively straight forward. All you need is an IP address that is visible on the Internet.

You don't say what your connection to the Internet is, so let's look at both of the likely (IPv4) possibilities:

* You have a block of publicly visible addresses (something other than an IP address starting with 10, 172.16, or 192.168 that are allocated by RFC 1918), or

* You are behind a single IP address using NAT (network address translation) to provide the internal machines with access to the Internet. The internal machines (and devices) will all have an RFC 1918 address and will not be accessible from the Internet – except by traffic responding to requests made by those machines which are routed to them using NAT. For many users this is the more likely case.

In the first case it is simply a matter of connecting the Arduino to a network segment that is connected to the Internet and assigning an IP address (or configuring DHCP). Also, make sure that the UDP port you are using is not assigned to another service.

In the second case you will also need to connect the Arduino to a network segment with access to the Internet, but because of NAT users outside will not be able to get to the Arduino (yet). To solve that problem you will need to map a port and your external address (the address of your router) to a port and the internal address of your Arduino. For example:

* Assume your service runs on port 3142 and your IP address on the Internet is 8.9.10.11 and the Arduino is at 192.168.0.42 on your internal network.

* Then you would configure the port forwarding settings on your router to direct UDP traffic bound for port 3142 to the internal IP address of 192.168.0.42. Some routers will only allow you to forward to the same port, others will also allow you to use a different internal port as well.

* You may also need to open up a "hole" in your firewall to allow traffic to the port where your service runs. The truly cautious will connect the Arduino to a network segment in the DMZ and there will be another firewall protecting your internal computers and devices.

Once you have this set up anybody on the outside will be able to use the service on the Arduino – if they know the IP address and the port number. Typically you would run the service at a well known host name and use DNS to translate the host name to an IP address. From your question I can't tell how you want to advertise the service, that would be another good question…


message:
Speed of built in DAC/ADC in Arduino Due

Can someone tell me how fast the built in DAC (and ADC) in an Arduino Due can be written or read? I currently don't have the equipment to measure but need the information to plan my next steps.

I try to move galvanometer mirrors and want to make the voltage/position updates as small as possible. How fast are the internal DACs compared to an SPI connection (where I have to write 2 Byte).

body:
See sections 43, Analog-to-Digital Converter (ADC), and 44, Digital-to-Analog Converter Controller (DACC), in the Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf specsheet.

In particular, subsection 43.2, Embedded Characteristics, says: “1 MHz Conversion Rate”.  Some time diagrams appear quite a few pages later that suggest 10-bit conversions can be done more rapidly than 12-bit.

For the DAC (or DACC, per the specsheet), section 44.6, Functional Description, says:

>The DACC uses the master clock (MCK) divided by two to perform conversions. This clock is named DACC Clock.
Once a conversion starts the DACC takes 25 clock periods to provide the analog result on the selected analog
output.

AIUI, the Due's master clock frequency is 84 MHz, so DACC Clock frequency is 42 MHz, whence 25 cycles take 575 ns, which is an update frequency of about 1.74 MHz.

For more details about the ADC, see eg [
Analog performance, particularly of Due's 12 bit ADC](http://www.djerickson.com/arduino/) at djerickson.com.


message:
One workspace, two IDEs - Possible?

How can I create a workspace & projects so that either the Arduino IDE or the [EclipseArduino IDE][1] may be used to develop the project, interchangeably?

I have both IDEs installed and working but in separate workspaces.

I need:

 - One workspace that either IDE can understand and work in;
 - Either to IDE build with the physically same set of library sources;
 - Whichever IDE I open to see my sources as I last left them, regardless of which IDE I last used.

I want:

 - The source files to have conventional names - .C or .C++, not .pde or .ino;
 - Either IDE to build with the physically same set of library object modules;

My use-case is that I work in/with Eclipse, and I teach Arduino skills to people starting out with the Arduino IDE. I'd like to be able to prepare class work at home with Eclipse but open and project it in class with the Arduino IDE. It would be nice if I could demonstrate the two IDEs using the same code. Clearly, I could hack up a demonstration, but I'd rather do it honestly and without sync issues like having to apply twice any changes we made in class.

<br>Update 20 Apr '16:
At @Jantje's suggestion (in the comments below his answer), I created a github issue, "*Importing an ArduinoIDE project with the New Sketch Wizard and using same sketch-name, failed.*" The new sketch would over-write the .ino file with a new, empty sketch.

That issue got fixed in the April 14, 2016 nightly and now works as his answer to this question says it does.

  [1]: http://www.baeyens.it/eclipse/

body:
Are you willing / able to work with Xcode? There is a package called [embedXcode][1] that enables Arduino development on Macs – I'm just getting up to speed with it, but it does appear to allow you to work either in Xcode or with the Arduino IDE (the .ino file is present and is what you edit in Xcode). In my testing so far it appears that the easiest thing to do is to create a project using Xcode and then you can point the Arduino IDE at the project pretty easily, getting Xcode to pick up a sketch started in the Arduino IDE is currently beyond me.

From the point of view of your students I would think that you'd want to keep the .ino file rather than make them learn about the conventions of C or C++. It would also save you the hassle of somehow managing file names – although you could probably get make to do this for you.

I haven't looked into it at all, but I think you could do something similar with [Atom][2] (a quick Google found a blog post called *[Arduino Development in Atom Editor][3]* and an Atom package called [nino][4] that is described as a "Toolbelt for Arduino") or Emacs, or for that matter Vim is also like to have some Arduino support.

[1]: http://embedxcode.weebly.com
[2]: https://atom.io
[3]: https://viget.com/extend/arduino-development-in-atom-editor
[4]: https://atom.io/packages/nino


body:
Your requirements for not having `.ino` files and wanting to be able to work with the Arduino IDE are conflicting. Assume we drop that requirement it is very much possible to do what you want.

The Arduino Eclipse plugin has been supporting `.ino` files for a long time now. You can simply compile Arduino IDE-made sketches. You do not have to make links and so make the folder where your Arduino IDE makes its sketches the workspace in Eclipse.

In Eclipse, for each sketch you want to edit, start the new sketch wizard and use a project name that is the same as the sketch name in the Arduino IDE.

Now you can work in the Arduino Eclipse plugin and the Arduino IDE on the same files.

**Important:** In Windows, if you use a version of the plugin from before March 3, 2016, you need to delete the `.ino.cpp` file before starting the Arduino IDE. In Linux, the Arduino IDE ignores this file, but in 1.6.7 on Windows (just tested it) the file gets picked up by the Arduino IDE. You need to restart the Arduino IDE to tell it the file is gone.

From March 3, 2016 onwards, the code in the `.ino.cpp` file is inside a `#ifdef` that is not defined in Arduino IDE.


message:
Arduino using LCD

I am building a project that is using A12864ZW 128X64 LCD, the question I have is should there be anything in the circuit to prevent damage to the Arduino Mega or the LCD? I am using this [example here][1] for a start.

   I think I damaged one LCD with the current circuit because everything was working perfect then all of a sudden it was like the LCD Contrast was set all the way up, displaying only a dark screen but I couldn't adjust it with the U8Glib or with the V0. During programming I would disconnect the ground from the Arduino to the Breadboard, when I would do this the LCD would still flicker as it was being programmed. This is why I am wondering if I am missing something.

   I read somewhere that putting a MOSFET on the Ground of the LCD that is connected to the Reset pin helps. Another problem that I am having is I am using Eclipse with the Arduino C++ add in and sometimes I can program easily, everything goes as expected but then it will fail to upload until I unplug and reset the board sometimes several times.

   Because the program is using pins 11-13 it can create problems because these are the same pins used for programming if I remember correctly. I tried changing the pins used but didn't seem to help anything.
  [1]: http://overskill.alexshu.com/128x64-12864-lcd-w-arduino-serial/

body:
Disconnecting ground while all the other pins are connected and the Arduino is powered up is a *very* bad idea.  Either manually, or using a MOSFET.

Simply because the power you are feeding in to the screen wants to try and find a way to ground through some means or other - and if the ground is disconnected then that means muscling its way through the IO pins into the Arduino and through to ground that way.  The result is that you damage the LCD screen's fragile circuitry.

If you want to disconnect the ground pin at any time, you must ensure that either the power is turned off, or the power connections to the LCD are disconnected first.

If you want to have the Arduino's RESET toggle the power to the LCD to force a hard reset then you need to use a P-channel MOSFET in the power connection instead, so the ground connection is always connected.


message:
Sending and receiving custom messages with Ardulink

I am sending custom code to Arduino with this ardulink command:

    {        ArduinoControl.link.sendCustomMessage("oled");
    }

Code from standard Ardulink sketch CustomMessagesChipKit.ino:

    {
      if (stringComplete) {
        if(inputString.startsWith("alp://")) {
        // OK is a message I know (this is general code you can reuse)
          boolean msgRecognized = true;
          if(inputString.substring(6,10) == "cust") { // Custom Message
            // here you can write your own code.
            int separatorPosition = inputString.indexOf('/', 11 );
            int messageIdPosition = inputString.indexOf('?', 11 );
            String customId = inputString.substring(11,separatorPosition);
            String value = inputString.substring(separatorPosition + 1, messageIdPosition);
            if(customId == "oled") {
                //Clear the virtual buffer
                lcd.noBacklight();
                analogWrite(9,100);
                digitalWrite(13, HIGH);
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("jkhgvjgv");
            } else {
              msgRecognized = false;
              // this sketch doesn't know other messages in this case command is ko (not ok)
            }
          } else {
            msgRecognized = false;
            // this sketch doesn't know other messages in this case command is ko (not ok)
          }
          // Prepare reply message if caller supply a message id (this is general code you can reuse)
          int idPosition = inputString.indexOf("?id=");
          if(idPosition != -1) {
            String id = inputString.substring(idPosition + 4);
            // print the reply
            Serial.print("alp://rply/");
            if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
              Serial.print("ok?id=");
            } else {
              Serial.print("ko?id=");
            }
            Serial.print(id);
            Serial.write(255); // End of Message
            Serial.flush();
          }
        }
        // clear the string:
        inputString = "";
        stringComplete = false;
      }}

As a result the LED on pin 13 is turning on after message from java program. But that is all. LCD or or LED on PWM 9 pin are not reacting at all.

Also I could not understand how to send an answer back from Arduino to Ardulink. Can you please show me an example? I would love to send and print data in Java program from  DHT11 sensor in response. I know about RawDataListener and I read the whole Ardulink site, but I did not understand that. I a newbie in programming.

When i replace

    {String customId = inputString.substring(11,separatorPosition);}

with

    {String customId = inputString.substring(11,15);}

than everything works. What can it be?

body:
you can read a complete (real project) example about how to receive messages from Arduino with Ardulink from here: [https://github.com/openQCM][1]

In general you can use a listener (digital, analog, and raw) to receive messages from Arduino. A raw listener receive all messages received from Arduino, so you need to implement code to filter the messages you are interested in. Digital and Analog listeners receive events from digital and analog PINs.

The sketch in your question isn't the original sketch you can find in Ardulink distribution. That sketch was written to manage the OLED on the ChipKit shield I have. You have modified the sketch to manage your LCD.

Actually you can send successfully messages from an Ardulink based application (as Ardulink Console) to Arduino since LED on PIN 13 is turned on. So the problem maybe just on your sketch.

To FIX analogWrite on PIN 9 try to set the PIN as OUTPUT with this statement:
pinMode(9, OUTPUT);

I cannot help you with lcd library that I don't know.

If you need for some help don't hesitate to write to me.

  [1]: https://github.com/openQCM


body:
It looks like you're trying to send a custom message to arduino and have it respond. As a small add on to your code try serialCommand. It pulls in whatever you send over the command line and executes it as a command and returns whatever you need to whatever interface you gave such as softwareSerial.

https://github.com/scogswell/ArduinoSerialCommand/tree/master/examples

I offer that you could use the two together to get the results you want.

Let serialCommand listen for commands and execute them and then set up a listener in Java for any serial communication back from the unit.

That's more or less what I end up doing when it comes to bluetooth, rf24, and wifi anyway, so why not serial as well.


message:
Controlling DC motor from Android device

Ref: https://robotics.stackexchange.com/q/8526/11146

I want to build a simple android controlled robot

I will connect `android phone<usb>arduino<wire>motor controller<wire>dc motor`

I wonder why I have to write two programs (android java & arduino c++)?

How can I directly control the DC motor from android java program without writing arduino code?

body:
The short answer is "you can't." For the Arduino to do anything useful it needs to have instructions telling it what to do. In your example the Arduino's job is to do something that the Android can't – turn on and off the DC motor. You could even use a wifi or Bluetooth connection from the Android to the Arduino to make it possible to avoid the hassle of the USB cable.

Your project requires a number of small hunks of code on the Arduino to:

 * Listen for commands from the Android.
 * Validate the commands received.
 * Turn on or off the motor.

Roughly speaking your loop() function might look something like this:

    void loop() {
      // look for a command
      // validate the command
      if (valid && turn_motor_on) {
        motor_on();
      } else {
        motor_off();
      }
    }

Fortunately the Arduino code can be very simple and there is a lot of example code to help you get started.