message:
Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns

Hey all I have been trying to figure out a way to random set patterns for my fade in/ out code below:

    int PIN = 3;
    int totalLEDs = 11;
    int ledFadeTime = 5;

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
    }

    void rgbFadeInAndOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
      for(uint8_t b = 0; b <255; b++) {
         for(uint8_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
         }

         strip.show();
         delay(wait);
      };

      for(uint8_t b=255; b > 0; b--) {
         for(uint8_t i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
         }
         strip.show();
         delay(wait);
      };
    };

The code above works great. Fades the blue in and out infinity times. However, I am wanting random LEDs to be off or have a lighter/darker shade of the color I choose (in the above it's blue).

Example:

    [off][blue][blue][off][off][dark blue][blue][off][dark blue][dark blue][off]
    [blue][blue][blue][dark blue][off][blue][dark blue][blue][dark blue][off][off]
    etc etc...

Would anyone happen to have code already like this?

Any help would be great! Thanks!

body:
To make randomly-changing colours for the whole strip, change:

    void loop() {
      rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
    }

to:

    void loop() {
      rgbFadeInAndOut(random (256),
                      random (256),
                      random (256), ledFadeTime); // random colour
    }

---

If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:

    #include <Adafruit_NeoPixel.h>

    int PIN = 3;
    int totalLEDs = 11;
    int ledFadeTime = 5;

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      rgbFadeInAndOut(ledFadeTime);
    }

    void rgbFadeInAndOut(uint8_t wait) {

      uint8_t red [totalLEDs];
      uint8_t green [totalLEDs];
      uint8_t blue [totalLEDs];

      // randomly set each colour
      for (int i = 0; i < totalLEDs; i++)
        {
        red [i] = random(256);
        green [i] = random(256);
        blue [i] = random(256);
        }

      for(uint8_t b = 0; b <255; b++) {
         for(uint8_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
         }

         strip.show();
         delay(wait);
      }

      for(uint8_t b=255; b > 0; b--) {
         for(uint8_t i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
         }
         strip.show();
         delay(wait);
      }
    }


sender: user

message:
How to upgrade Arduino UnoR3 clock

A little background:

I need to generate a 40KHz frequency as accurately as possible.

(One of my other posts is here:
https://arduino.stackexchange.com/questions/8671/stable-frequency-generation)

My code is solid- I'm using an Uno R3 and generating the most accurate frequency I can at this point. The only way to get a more accurate frequency is to upgrade the ceramic resonator to a crystal oscillator.

So, my over-arching question is: How do I actually upgrade the ceramic resonator to a crystal oscillator?

Things I'm considering are:

Is it worth it to actually upgrade my Uno R3 - and is it even possible? Is there a clone that drives the ATMega328p with a crystal oscillator that I could use instead? Is there simply just a better model for this application?

sender: assistant

body:
Looking at the Arduino R3 reference design, it should have a crystal! But in practice it seems that the manufacturers are cutting corners and using a resonator because it is cheaper. I don't like your chances of fitting an xtal instead of a resonator. Unless you are a soldering expert and have suitable facilities, the most likely outcome is a dead board.

If your board has the MCU chip in a socket, you could bend the xtal pins so they don't go into the socket and solder a xtal and a couple capacitors to them. Not exactly a production line solution, but it will be fine if you just want a one-off - and anyone reasonably at home with a soldering iron could do it.

Freetronics (an Australian company) make a R3 compatable with xtals for both processors. These are very well made (I own two), and have a prototyping area as well. Downside is the higher cost. See http://www.freetronics.com.au/products/eleven#.VT3F-PCo1BA


body:
It's really easy to take an ATmega328 chip and wire it up on it's own.  There are even instructions on the Arduino site on how to do it.  Take a look at http://www.arduino.cc/en/Main/Standalone .

You could even pull the 328 out of the Uno, add the crystal and a few caps and then program it with the Uno board.  I've done this a few times myself and it worked just fine for my needs.


message:
Direct port manipulation to write 40 bits

I have 5 shift register changed in series and want to shift the data quickly. I have learned that the internal shiftOut function is slow and direct port manipulation can speed up the things.

However, I am not sure to write code in the specific way.

The current working code block is:

    #define SensDataPin 4
    #define SensClockPin 9
    #define SensLatchPin 8
    updateAllShifters()
    {
    digitalWrite(SensLatchPin, LOW);
    shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_1);
    shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_2);
    shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_3);
    shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_4);
    shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_5);
    digitalWrite(SensLatchPin, HIGH);
    }

As the code shows, I have 5 bytes which are written by independent functions and just before the return statement, these functions call "updateAllShifters()" to mark the changes.

I have followed few tutorials over the internet and have re-written the logic like:

    #define MSDATAHIGH PORTD |= (1<<PD4)
    #define MSDATALOW PORTD &= ~(1<<PD4)
    #define MSLATCHHIGH PORTB |= (1<<PB0)
    #define MSLATCHLOW PORTB &= ~(1<<PB0)
    #define MSCLOCKHIGH PORTB |= (1<<PB1)
    #define MSCLOCKLOW PORTB &= ~(1<<PB1)
    updateAllShifters()
    {
    MSLATCHLOW;
    for(int i=0;i<40;i++)
    {
    HOW TO CODE HERE USING THE DEFINED MACROS!
    }
    MSLATCHHIGH;

Edit: Coding example of this (but want a more optimized way):

    #define MSDATAHIGH PORTD |= (1<<PD4)
    #define MSDATALOW PORTD &= ~(1<<PD4)
    #define MSLATCHHIGH PORTB |= (1<<PB0)
    #define MSLATCHLOW PORTB &= ~(1<<PB0)
    #define MSCLOCKHIGH PORTB |= (1<<PB1)
    #define MSCLOCKLOW PORTB &= ~(1<<PB1)
    updateAllShifters()
    {
    MSLATCHLOW;
    for(byte i=0;i<8;i++)
    {
     if(!!(byte_1 & (1 << i)));// LSBFIRST
       {
       MSDATAHIGH;
       }else
       {
       MSDATALOW;
       }
    }
     MSCLOCKHIGH;
     MSCLOCKLOW;
    //DO ABOVE FOR ALL REMAINING 4 BYTES
    MSLATCHHIGH;
    }

body:
> I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow.

You can change the SPI speed at any time. Once the device is selected (Slave Select asserted) then reconfigure the SPI bus for high speed operation.

eg.

    SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI is definitely the fastest way you can communicate with a shift register.


message:
What is the best way to define an I/O pin?

I read definitions like

    const int ledPin = 9;

and also

    #define ledPin 9

I know that a definition like

    int ledPin = 9;

is a bad practice if you're not going to change it (which you usually won't), though I've see this several times in Arduino programs.
Which one of the other two is preferred?

body:
#define ledPin 9 is preferred. By doing int ledPin = 9; you will be allocating an int memory whose value is used every time you use ledPin. #define is different in the sense it doesn't allocate memory. there is no memory called ledPin. Before compiling all "ledPin"s in the code(other than strings) are replaced by 9. So basically

digitalWrite(ledPin);

becomes

digitalWrite(9);

Advantages of #define : Saves memory and since all ledPin are replaced by 9 before execution, it saves processor time.

Doesn't really matter in small codes...


body:
Strictly speaking, the `#define` approach will use slightly less memory. The difference is usually tiny though. If you need to reduce memory usage, then other optimisations would probably be far more effective.

An argument in favour of using `const int` is **type safety**. Wherever you refer to that pin number by variable, you know exactly what data type you're getting. It might be promoted/converted implicitly or explicitly by the code which uses it, but it should behave in very clear ways.

By contrast, the value in a `#define` is open to interpretation. The vast majority of the time, it probably won't cause you any problems at all. You just need to be a little careful if you have code which makes assumptions about the type or size of the value.

Personally, I almost always prefer type safety unless I have a very serious need to save memory.


body:
Probably the best way would be
    `const uint8_t LED_PIN = 9; // may require to #include <stdint.h>`
    or
    `const byte LED_PIN = 9; // with no include necessary`
    `const unsigned char LED_PIN = 9; // similarly`
The name is in caps as per general practice in C++ (and others) to name constants.
This should not use any RAM in itself, and use about 1 byte of program memory per use.
However, there _might_ be problems when the number is higher than 127 and is sign-extended while getting promoted to larger signed integers (not entirely sure on this), although that is unlikely to happen with pin numbers.


message:
Cannot bootload again after changing the board?

We are so tired and would like to get help with this. We are trying to bootload using the arduino Uno.

We have an `atmega 328p` smd , that we are trying to bootload. We have connected all the right pins, added to the boards.txt the  `"Atmega328 on a breadboard(8mhz internal clock)"`.

Then I have chosen from the "board" menu, this option (internal clock), and uploaded the program. **it worked** .

Later, I wanted to try and bootload for external clock so I chose from the boards menu the `pro mini with 5v board.`(is it wrong?)

Not only that I got an error, now, **I can't bootload the internal clock again** !!

Why can't we bootload again? Did we damage something? Can it be reset again?
How can you bootload for external 16Mhz ??

error :

    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again

body:
> Not only that I got an error, now, I can't bootload the internal clock again !

You need an external clock source, such as a crystal and two capacitors. Once you switch the fuses to the external clock it won't work any more unless you have such a clock.

I have a [bootloader uploader](http://www.gammon.com.au/forum/?id=11635) sketch that also provides a clock signal if you need it.


message:
ATMega I/O maximum current

According to the ATmega328P datasheet, the total current from **all I/O pins** must not exceed 200mA.

Let's say that an Output pin sources 30mA and an Input pin sinks 10mA. The total current should be 30+10=40mA or 30-10=20mA?

body:
Usually you sum the magnitudes of the currents - so
|+30| + |-10| = 30 + 10 = 40 mA in your example.

Predictably but unfortunately. the principle of [**TANSTAAFL**](http://en.wikipedia.org/wiki/There_ain't_no_such_thing_as_a_free_lunch)  usually applies in such matters :-).

Such limitations are often (but not solely) dissipation based.
A low level output pin is dissipating ~= (Vo_low) x I low and
a high level pin dissipates (Vdd-Vo_high) x I_high.
For low currents versus I_pin_max, Voutlow is ~= 0  and Vouthigh is ~= Vdd.
As currents approach design capacities Voutlow starts to rise and Vouthigh starts to fall (due to the internal 'switch' not being able to handle the current) and dissipation rises.

**IF** you pulled a high pin fully low or a low pin fully high then
at 5V and 200 mA IC dissipation = 1 Watt.
Under that sort of abuse other bad things may happen.

There MAY be some specialist cases where you can treat **SOME** high and low currents as semi independent but this would need a good understanding of the IC and probably still lies outside specification.


body:
Neither. First, inputs don't draw current. Whether you're sourcing current or draining it, it will always be an output pin.

The 200 mA rule is probably determined by the bonding wires for the Vcc and ground pins on the die. That means that all outputs which are sourcing current shouldn't source more than 200 mA combined, as this current will have to enter the device through the Vcc pin.
Likewise all outputs sinking current shouldn't sink more than 200 mA combined, as this current will drain through the ground pin.


message:
calculating the input current

I have been a bit confused about calculating the input current, so I'd be much obliged if someone could help.

Let's say that we have a potentiometer connected with an analog input as shown below. In a middle position the resistance of the potentiometer is spitted to R1 and R2.

How can I calculate the current in A0?
How much will be the current value if (R1=0, R2=Rmax), (R1=Rmax, R2=0), (R1 and R2 !=0,Rmax)?

     5V --------
               |
               R1
               |
     A0 --------
               |
               R2
               |
              GND

body:
When reading an analog voltage an analog pin has a very high resistance - usually very very much higher than the resistance of any potentiometer used, and input current to A0 can be regarded as zero for practical purposes.

For practical purposes the current drain from the supply will be that which flows from 5V to ground via R1 & R2.
I = V/R = 5V/(R1  + R2)

As for a potentiometer the sum of R1 + R2 is constant, the position of the pot-wiper makes no difference to current draw.

eg 10k pot. I_supply  = V/r = 5V/10K = 0.5 mA.
An I_A0 ~= 0

____________________________

The upper value of a potentiometer which should be used for an analog input is covered by the uC (microcontroller) data sheet. The key parameter is uC input bias currents flowing in the potentiometer and causing **small** voltages which affect the analog reading. A rule of thumb is to keep such voltages under about one LSB (least significant bit) of the ADC.


body:
The input current of the ADC is low enough not to change the potentiometer's characteristic (which won't be perfectly straight, anyway).

The only requirement is that the impedance of the potentiometer (according to Thévénin equal to R1 parallel to R2) shouldn't be greater than 10 kΩ. That's because otherwise it takes too long for the ADC's capacitor to get charged.


message:
Do I need Kalman Filter after I read DMP data on MPU6050?

In my project I need to use as noiseless as possible data from a MPU6050, I do have some nice DMP data, what will happen if I apply Kalman filter above it? Will I get more noiseless data? Or will it become unreliable anymore? Are there any benefits to do that ?

body:
The DMP data from the MPU6050 is already filtered, and while I have not expirimented with the DMP data much myself I believe it is pretty clean. If there is a calibration process you can do to improve it, that is probably worth expirimenting with, but you should not filter the values a second time.

You should figure out what your application's noise tolerance actually is before worrying about different filters. There are potential benefits to your own filter, I think knowing exactly how it performs in edge cases and being able to calibrating it to your specific problem could be beneficial; However, it could also end up being worse than the DMP. Don't forget that filter calculations can generally take a few milliseconds for an arduino to run that you don't have to worry about with the DMP.

If you do work on your own filter, you will need to turn off the DMP and filter the raw values. Look into complementary, mahoney, and madgwick filters as well as kalman, which is quite computationally expensive. Using an existing library or an implementation from an open source quadcopter project is probably most efficient. The math associated with kalman filters and 3d rotations gets very complicated very quickly.


message:
How I could make a bus connection in a prototype shield?

I am a programmer but pretty new to electronics , I recently bought a prototyping shield like the picture :
![enter image description here][1]

In my view there is no bus connections here . I have lots components need connect to solder into a single board , and some ports like GND and VCC , SDA and SCL need connect via buses , how could I make solder such a bus connection by using this shield?

Should I just continuously solder through the holes I want to form a bus?

Thanks..!

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

body:
I would mount the components to the board first then create busses with wire. Depending on the components you might be able to use the same row the component leads are in or you may need to lay the bus in the adjacent row and bridge the gap with component leads.

A quick search turned up an image that sort of gives an idea of what I'm talking about. If you look closely you can see the wire bridging the gap between each solder pad.

https://www.bing.com/images/search?q=soldering+protoboard+bus+wiring&view=detailv2&&&id=EF1514CA6486FC44E0132E7DE1CFBFDBFD015809&selectedIndex=15&ccid=vQ+eHllm&simid=608022938507020230&thid=JN.TBpqHtXSA7o3dTvD8dPVaQ&ajaxhist=0


message:
LCD Display hangs the computer

I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.

<strike>When I tried [this][1] I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.</strike>

When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem.

I'm on OS X Yosemite. Why this can be happening and how can I fix?

Note: Computer is hanging as soon as the Arduino usb cable connected.

  [1]: http://playground.arduino.cc/Main/I2cScanner?action=sourceblock&num=1

body: Sometimes my system hangs in the way you describe  ("hanging as soon as the Arduino usb cable connected")  if I mistakenly connect  the +ve and -ve supply lines to an i2c device the wrong way round.


message:
Serial LED control

Hell0!

I run in small problem. I am try to control LED's by serial port.So I am expect to send "1" and two LED's will start to blink or send "0" and only one LED is constantly lighted up. At first I thought that do-wile will work, Arduino will run do loop while value sent by serial port is "1" or "0". However at first I sent "0" and one LED are lighted, after I send "1" and two LED's are blinking. But when I send "0" again, LED's keeps blinking. What should I change in my code?

    const int ledPin2=2;
    const int ledPin3=3;
    const int ledPin4=4;

    void setup()
    {

      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);

     Serial.begin(9600);
    }

    void loop()
    {
      while (Serial.available()==0);

      int serialVal = Serial.read()-'0';

      do
       {
          digitalWrite(ledPin3, LOW);
          digitalWrite(ledPin4,HIGH);
        } while(serialVal==0);

      do
        {
          digitalWrite(ledPin4,LOW);
          digitalWrite(ledPin2, HIGH);
          digitalWrite(ledPin3, LOW);

          delay(100);

          digitalWrite(ledPin3, HIGH);
          digitalWrite(ledPin2, LOW);

          delay(100);

      }while (serialVal==1);
    };

body:
I don't think you understand how your code is being executed. I would recommend trying the following.

    const int ledPin2=2;
    const int ledPin3=3;
    const int ledPin4=4;
    int serialVal;

    void setup()
    {

      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);

     Serial.begin(9600);
    }

    void loop()
    {
      // If data is available, then read it!
      if (serial.available() > 0)
      {
          serialVal = serial.read()-'0';
      }

      // If serial val is 1, turn on LEd4, turn off Led3
      if (serialVal == '1')
      {
          digitalWrite(ledPin3, LOW);
          digitalWrite(ledPin4,HIGH);
      }

      // If serial val is 0,
      // turn on LED2. Turn off Led3
      // delay for 100ms
      // turn of LED2, turn on LED3
      // delay for 100 ms
      if (serialVal == '0')
      {
          digitalWrite(ledPin4,LOW);
          digitalWrite(ledPin2, HIGH);
          digitalWrite(ledPin3, LOW);

          delay(100);

          digitalWrite(ledPin3, HIGH);
          digitalWrite(ledPin2, LOW);

          delay(100);
      }

    }

The reason why your code doesn't work, is once you are within a do while loop, you will not be allowed to exit until the condition is met. If you are not scanning for more serial values within that do while, you will get stuck there forever.

Another reason why you might be confused, is how digitalWirte operates. There is no need to loop over a digitalWrite, as the pin will stay HIGH, or LOW until you change its state. Once you digitalWrite(HIGH) that pin will stay high until it is told to go LOW.


message:
Why does timer1 not generate correct period on CTC mode with a resolution of 5us?

I have defined my code to generate an interrupt over each 5μs on CTC mode using timer1 but the output shows a time of ~15μs.

Following the equation to set the counting number to achieve the desired time

    (# timer counts + 1) = (target time) / (timer resolution)

I've got OCR1A = 79 for a desired time of 5μs using no prescaler and a source clock of 16MHz on Arduino Uno.

My code is as follows:

    // avr-libc library includes
    #include <avr/io.h>
    #include <avr/interrupt.h>

    #define LEDPIN 9

    void setup()
    {
        pinMode(LEDPIN, OUTPUT);
        digitalWrite(LEDPIN, HIGH);

        // initialize Timer1

        cli();          // disable global interrupts

        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B

        // set compare match register to desired timer count:
        OCR1A = 79;

        // turn on CTC mode:
        TCCR1B |= (1 << WGM12);

        // Set CS10 bit for no prescaler:
        TCCR1B |= _BV(CS10);

        // enable timer compare interrupt:
        TIMSK1 |= (1 << OCIE1A);

        sei();          // enable global interrupts

    }

    void loop () {}

    ISR(TIMER1_COMPA_vect)
    {
      digitalWrite(LEDPIN, !digitalRead(LEDPIN));
    }

This is the output from my logic analyzer:

![Output From Logic Analyzer][1]

Is it a limitation of the Arduino or am I missing something?

My idea is to generate a PWM manually to control a servo motor using timer1 and precisely increase the period by 10μs during "on" time and get the desired angle.

After some experiments, I have discovered that my motor ([MG996R][2]) has a range from 0.6ms to 2.1ms during "on" time to move from 0 to 180 degrees.

I have tried the Arduino's Servo library but it goes far than 180 degrees (I don't know why). That's why I am building my own code for that purpose.

  [1]: https://i.stack.imgur.com/ft4Ti.png
  [2]: http://www.servodatabase.com/servo/towerpro/mg996r

body:
I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.

Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).

I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.

    void setup()
    {
        DDRD = B00001000; // pin 3 as output
        PORTD &= ~_BV(PORTD3);   // set 3 as LOW

        // initialize Timer1

        cli();          // disable global interrupts

        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B

        // set compare match register to desired timer count:
        OCR1A = 9;

        // turn on CTC (Clear Timer on Compare Match) mode:
        TCCR1B |= (1 << WGM12);

        // Set CS10 bit for clk/8 prescaler:
        TCCR1B |= _BV(CS11);

        // Output Compare A Match Interrupt Enable
        TIMSK1 |= (1 << OCIE1A);

        sei();          // enable global interrupts

    }

    ISR(TIMER1_COMPA_vect)
    {
      PORTD = ~PORTD;
    }


message:
Level tracking using optical or capacitance sensors

I am looking to devise a level tracking system using arduino and some sensors. My particular situation is I have solute that is coming out of solution and I want to track the formation rate of the solid phase as the salts settle at the bottom and build a bed of particulates.

I am looking for precision at about 0.5mm and over a range of like 6 inches. My initial idea was to get a sensor bar that could detect when and where light is hitting the sensor and post processes that signal. I have to design this device to sit outside the cylindrical vessel. The solvent is transparent so any form of light would work. I am stuck on finding the parts that could pull this off and I was hoping the more experienced community could point in the right direction.

*** UPDATE ***

a little cartoon for a clearer picture of the idea
I am leaning towards capacitance since using light seems like a rabbit hole. I was playing with some foil and it may work but I need a much more sensitive tool on the order of pico-Farads to work.

![enter image description here][1]

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

body:
What about measuring this with two resistive probes - the electricity will go through down one probe to the top of the water, across the water, and up the other probe. You can measure how much of the probe it went down, by measuring the resistance. You would need the probes to be a specific, very consistent distance apart, and be made of resistance wire.

Another option is to use a float of some kind, and measure it this way. This is a lot easier if all you need to know is full/not full.


message:
How can I use a 'Global' class object?

I created a class inside the sketch file(not in another file) and init it as object before setup() and loop() as a global object, after I change some parameters inside the object in setup() , I found in loop() the parameters in the global object remain unchanged.
Here is the pseudocode code to describe my question:

    //all of the code below are in the same ino file.
    class Animal{
    public:
      bool alive = false;
      Animal (bool liveStatus){
        alive = liveStatus;
      }
    }

    Animal dog(false);
    Animal cat(false);
    Animal lion(false);
    Animal animalArray(dog,cat,lion);

    void setup(){

      for (int i=0;i<3;i++){
        Animal current_animal = animalArray[i];
        current_animal.alive = true;
      }
      //here when I print each animal's alive flag is 'true'
    }

    void loop(){
      for (int i=0;i<3;i++){
             // here the alive flag of each animal is still false  , they should be all true!!
      }

    }

It looks like after I quit setup() somehow every change of the global object inside the setup are all gone .

Thanks for helping me ..

body:
Your problem here is that `Animal current_animal = animalArray[i];` is making a whole new Animal object that starts as a copy of `animalArray[i];`, but after that the two are no longer associated. Then when you call `current_animal.alive = true;`, you are not actually changing the animal in `animalArray[i]` anymore.

The simplest way to fix this is to make `current_animal` a reference to the object you pick out of the array, although a pointer would work the same way. With this code:

    Animal& current_animal = animalArray[i];
    current_animal.alive = true;

`current_animal` becomes a reference to `animalArray[i]`, instead of a copy. Then operating on `current_animal` changes the same data that is stored in `animalArray[i]` like you intend.


message:
Arduino Standalone - photo shows incorrect pin wired to MOSI

I have been building a standalone Arduino on a breadboard following the guide, [Building an Arduino on a Breadboard][1]. The guide is generally very good, however, I have yet to get the Arduino working, for a number of various reasons, be it misinterpreted, or misread instructions (the reset pull-up resistor connected to GND instead of Vcc, Tx to Tx, instead of Tx to Rx (and vice versa), to name but a few issues that I have had to resolve).  However, I am sure that the following issue is not down to my careless interpretation or lack of attention.

Look at [the photo][2] taken from the webpage, [Building an Arduino on a Breadboard][3], on the Arduino website, showing the *Sparkfun AVR programming adapter* connected to the ATmega IC.

![Standalone Arduino breadboard][4]

The MOSI on the adapter is shown to be connected, via a dark green wire, to pin 16 on the ATmega chip, whereas the instructions say:

> Be sure to refer to the Arduino pin mapping for help wiring this up.
>
>  - The MISO pin of your adapter will go to pin 18 or Arduino digital pin    12 of your Atmega chip.
>  - The SCK pin of your adapter will go to pin 19 or Arduino digital pin    13 of your Atmega chip.
>  - The RESET pin of your adapter will go to pin 1 of your Atmega chip.
>  - The MOSI pin of your adapter will go to pin 17 or Arduino digital pin    11 of your Atmega chip.

According to the pinout below, Pin 16 is SS and pin 17 is indeed MOSI.

![ATmega168 pin out][5]

So, to my mind, the photo is definitely wrong. Indeed I was getting avrdude errors when trying to use a USBasp to load a bootloader, when using the wiring as shown in the photo. When I correctly wired MOSI, from the adapter, to pin 17, the avrdude errors disappeared.

Am I correct in my thinking? Has anyone else attempted to build this circuit, following the instructions on the Arduino website, and come across this issue?

I am just looking for confirmation that I am right, before I contact the owner of the web page.

  [1]: http://www.arduino.cc/en/Main/Standalone
  [2]: http://arduino.cc/en/uploads/Main/arduinobload_wires.jpg
  [3]: http://www.arduino.cc/en/Main/Standalone
  [4]: https://i.stack.imgur.com/bQWqz.jpg
  [5]: https://i.stack.imgur.com/PdcP5.png

body:
I have programmed AVR microcontrollers for a while. I would follow the datasheet, instead of the guide you have.

The Atmega168 Pin Mapping shows SS on 16, MOSI 17, MISO 18, SCK 19 and you will also need to connect to RST 1


message:
Arduino Mini Pro not working with my Neopixel project

my project involves 9 Neopixel LEDs. I have tested my code with my Arduino Uno board successfully. I'm using a mix of breadboard, jumper wires, and solder to connect everything. Powering the strip of 9 LEDs with 4 AA NiMh rechargable batteries, showing 5.2v on the meter. I've put a capacitor (1000mF 25v) in the circuit, right at the power source.

But when I upload the same code to my Mini (5v/16MHz) and swap it in in place of the Uno, I get nothing. No matter how much I jiggle wires or provide a good ground (which helped me get good results from my Uno). Every now and then by messing with wires, or as a few minutes go by, the first few lights *might* light up, but not in the right colors and no animation.

Just to test the Mini board I uploaded the sample program "blink" and the mini runs that one properly. So I'm certain my code is getting on there. My program is definitely bigger and involves some quick changes (I'm making an "ebbing" glow of supernatural eyes). Connecting the Mini to the Neopixel strip I soldered a wire with a female jumper onto the board, and my strip of lights has a wire soldered on with a male jumper. As a side note, it takes a little physical handling to get the project to work with the Uno (like pressing a little bit on the data wire in it's plug on the Uno or using a jumper wire in the breadboard clamped in a metal measuring tool and my hand to ground out the circuit). So maybe I'm just experiencing some of the shortcomings of the Mini, but I was under the impression that it would do just about anything the Uno could do. Especially in terms of just providing a data line for the LEDs.

I'm new to Neopixel. This is my first project in fact. So it is entirely possible I'm doing something wrong or there's something I just missed completely, or maybe my luck just sucks and I have some piece of faulty hardware... No idea.

Any suggestions would be most appreciated!

body:
As I was playing around today I found a solution. Powering the board through the FTDI adapter, which in turn was being powered by a USB juicepack charger, wasn't supplying enough juice and/or ground. It was enough for the Uno to work, so that's what was confusing me. I soldered in a 9V battery and clamped down on the pins with a wrench to ground it out. That made the board happy and it kicked into gear and lit my project up perfectly. It's pretty ghetto but it works! Yeah! :D![enter image description here][1]

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


message:
Training Commands with easyVR

I am using the EasyVR Arduino Shield with Uno.

What i am trying to do is train a custom phrase like a name.

I want to be able to train the phrase directly with arduino whilst it is not connected a pc.  I have noticed in the documentation there are some references to commands like it, but i'm not sure how to go around writing code for such a thing.

thank you

body:
Hi a bit late but I thought it could be useful to someone, I successed to train SD  commands without pc easyvr commander with this code:

    // ARDUINO 1.6.6
    // EasyVR Shield 2.0
    // EasyVR library v1.7

    #include "Arduino.h"
    #if !defined(SERIAL_PORT_MONITOR)
    #error "Arduino version not supported. Please update your IDE to the latest version."
    #endif

    #define pcSerial SERIAL_PORT_MONITOR

    #include "SoftwareSerial.h"
    SoftwareSerial port(12, 13);

    #include "EasyVR.h"
    EasyVR easyvr(port);

    //

    char label[33];
    uint8_t data;

    bool train = false;
    bool recog = false;

    int8_t group = EasyVR::PASSWORD;
    int8_t index = 0;

    void setup()
    {
      pcSerial.begin(9600);
      port.begin(9600);

      while (!easyvr.detect())
      {
        pcSerial.println(F("EasyVR not detected!"));
        delay(1000);
      }

      //

      easyvr.setPinOutput(EasyVR::IO1, LOW);
      pcSerial.print(F("EasyVR detected, version "));
      pcSerial.println(easyvr.getID());
      easyvr.setTimeout(5);
      //  easyvr.setLevel(EasyVR::HARD);

      //

      printCommands();
    }

    void printCommands()
    {
      pcSerial.print(F("Password: "));
      int16_t count = easyvr.getCommandCount(group);
      pcSerial.print(count);
      pcSerial.println(F(" command(s)"));
      for (int8_t idx = 0; idx < count; ++idx) {
        if (easyvr.dumpCommand(group, idx, label, data)) {
          pcSerial.print(idx);
          pcSerial.print(F(" = "));
          pcSerial.print(label);
          pcSerial.print(F(", Trained "));
          pcSerial.print(data, DEC);
          if (!easyvr.isConflict()) pcSerial.println(F(" times, OK"));
        }
      }
    }

    bool checkMonitorInput()
    {
      if (pcSerial.available() <= 0) return false;

      int16_t rx = pcSerial.read();
      //  pcSerial.print(rx);

      if (rx == 's')
      {
        easyvr.removeCommand(group, index);
        easyvr.addCommand(group, index);
        easyvr.setCommandLabel(group, index, "cuss");

        printCommands();
      }

      if (rx == 't')
      {
        recog = false;
        pcSerial.print("say something");
        train = true;
      }

      if (rx == 'r')
      {
        train = false;
        pcSerial.print("start recognition");
        recog = true;
      }

      //

      if (rx >= 0)
      {
        easyvr.stop();
        pcSerial.flush();
        return true;
      }
      return false;
    }

    void loop()
    {
      checkMonitorInput();

      if (train) {
        pcSerial.println("Train a word");
        easyvr.trainCommand(group, index);
      }

      if (recog) {
        pcSerial.println("Say the word");
        easyvr.recognizeCommand(group);
      }

      //

      do {
        if (checkMonitorInput()) return;
      }
      while (!easyvr.hasFinished());

      //

      int16_t idx = easyvr.getCommand();
      if (idx >= 0) {
        if (easyvr.dumpCommand(EasyVR::PASSWORD, idx, label, data)) {
          pcSerial.print("recognized = ");
          pcSerial.println(label);
        }
        easyvr.playSound(0, EasyVR::VOL_FULL);

      } else {
        if (easyvr.isTimeout()) pcSerial.println("Timed out, try again...");
        int16_t err = easyvr.getError();
        if (err >= 0) {
          pcSerial.print("Error 0x");
          pcSerial.println(err, HEX);
        }
      }
    }


message:
Problems splitting a string to get authentication and command

Good afternoon,

In a nutshell I'm having some difficulty with splitting and returning part of a string.

Essentially I'm working on the code for transmitting a password (24 character string) and command (string) in a single packet. However, the 'get_command' function is only returning the first character of the string (T) as opposed to the whole string (T1) and I'm not sure why. Any help would be greatly appreciated. Thanks in advance.

The entire sketch is below so you should be able to just drop it in and compile.

    char *received_data = "KkV3vKvLgC4PdBZRs5kkKM86T1";
    char *password = "KkV3vKvLgC4PdBZRs5kkKM86";

    int authenticate_transmission(char *data) {
        if(strncmp(data, password, 24)) {
            Serial.println("no match");
            return false;
        } else {
            Serial.println("match");
            return true;
        }
    }

    char *get_command(char *data) {
        char command[3];
        strncpy(command, data + 24, 3);
        // Fine here
        Serial.println(command);
        return command;
    }

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

    void loop() {
        // test received data - message is T1 at the end.
        if (authenticate_transmission(received_data)) {
            char *command = get_command(received_data);
            // But just prints out first char when returned from a function
            Serial.println(*command);
        }
        delay(10000);
    }

body:
The `command` array created inside `get_command()` is local data. That means it's only available while that function is being executed.

However, you're returning a pointer to it. That means when you're trying to use `command` afterwards from inside `loop()`, you're trying to refer to data which has been deallocated. By that point, it's getting used for something else.

There are various solutions to this. A fairly simple approach would be to have the caller allocate the `command` array, passing a pointer to it into `get_command()`. For example:

<!-- language-all: lang-cpp -->

    void get_command(char *data, char *command) {
        strncpy(command, data + 24, 3);
    }

From `loop()`, you would call it like this:

    char command[3];
    get_command(received_data, command);

The `command` array is still local data in this case. However, it's local to the `loop()` function (or wherever else you put that code). That means it will still be available when `get_command()` is called.


body:
The direct issue is you have a dereference operator (`*`) in the loop that you don't need:

    Serial.println(*command);

This causes it to pass **only the first character** to `Serial.println()` instead of the pointer to the memory location. That's the first issue.

Like Peter mentioned, the string gets deallocated when returned from the `get_command()` function. It's undefined behavior, but it's luck that it worked the way it did.


message:
Arduino R/C compatible transmitter and reciever

I want to make a RC buggy or something down those lines (using Legos of course) and I'm confused while looking what transmitter/receiver to use. Would like a simple classic remote and any compatible receiver for the Arduino.
Found such a remote: http://www.hobbypartz.com/79p-th9x-r9b-9channel-radio.html
But this seems way overkill for what I want to do. Any links or suggestions would be appreciated. Hope the question isn't too broad for stack exchange.

body: It depends on the number of channels you need, but you could go to HobbyKing, they offer RC remotes for down to 20$


body:
If you want to involve an Arduino on the receiver, you may want to choose a transmitter which is compatible with a 2.4 GHz chipset that is both available, and for which you can find Arduino code.  The NRF24L01+ and Beken compatibles are probably the most available, and a lot of RC toys use something compatible, though getting firmware right to interact with them can be tricky.  Beware that there are some other chips in wide use too, which can be harder to source a module for.

You can use an off-the-shelf multi-channel receiver, but that will tend to output each channel on a distinct PWM pin, which is annoying if you want to capture the data into an Arduino.

You might want to spend some time looking on rcgroups and in various hobby drone sites - the latter folks have a similar problem, as they want to collect all the control channels and mediate them through a custom flight computer (which in the early days was sometimes Arduino-compatible).

You can also make your own transmitter - perhaps by retrofitting an NRF24L01+ module and miniature Arduino equivalent into the casing of an older 5/72/75 MHz set - or the IR transmitter from a toy helicopter.


message:
Starting usb on pro micro after deep sleep (ATmega32u4)

I have just started playing with a low power arduino project, and have managed to get the power drain down to about 220uA using `powerDown` from `LowPower`.

What I would love to be able to do is start the USB controller and send some data every 8 seconds, but I cant seem to send anything...

Any idea would be greatly appreciated :)

Her is my code:

    // **** INCLUDES *****
    #include <LowPower.h>

    #include <avr/interrupt.h>
    #include <avr/power.h>
    #include <avr/sleep.h>
    #include <avr/io.h>

    void setup()
    {
      DDRD = B00100000;       // PORTD5 = TXLED
      DDRB = B00000001;        // PORTB0 = RXLed

      Serial.begin(9600);
      while (!Serial) ; // Needed for Leonardo only
      Serial.println("Starter...");
      delay(100);
      Serial.end();

      /*
      *  IKKE FJERN DENNE!!! Da greier vi ikke å omprogramere kortet...
      */
      delay(10000);
      Serial.begin(9600);
      while (!Serial) ; // Needed for Leonardo only
      Serial.println("low-power...");
      delay(100);
      Serial.end();
      flash();
    }

    void loop()
    {
      //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER4_OFF, TIMER3_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART1_OFF, TWI_OFF, USB_OFF);//, USB_OFF);
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
      //USBCON &= B11011111; //Disable USB Freeze clock USBCON.FRZCLK
      //USBCON |= B10010001; //SET USB_MACRO_ENABLE_BIT USBCON.USBE

        PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
        while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
        USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
        //-Clear Resume information ???

      flash();

      /*
      * Test USB kommunikasjon :)
      */
      Serial.begin(9600);
      while (!Serial);
      delay(5);
      Serial.println("Hello world!!!");
      delay(5);
      Serial.end();
       PORTD |= B00100000;
       PORTB |= B00000001;
    }

    void flash() {

       PORTD &= B11011111;
       PORTB &= B11111110;
       delay(100);
       PORTD |= B00100000;
       PORTB |= B00000001;
       delay(100);

       PORTD &= B11011111;
       PORTB &= B11111110;
       delay(100);
       PORTD |= B00100000;
       PORTB |= B00000001;
       delay(100);

       PORTD &= B11011111;
       PORTB &= B11111110;
       delay(100);
       PORTD |= B00100000;
       PORTB |= B00000001;
       delay(100);
    }

Best regards, Richard

EDIT
====
The manual specifies this resume protocol:
Resuming the USB interface (21.13 USB Software Operating Modes)

 - Enable PLL
 - Wait PLL lock
 - Unfreeze USB clock
 - Clear Resume Informtion

which I have translated into this:

    PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
    while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
    USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
    //-Clear Resume information ???

It have no effect whatsoever, have no idea how to **clear resume information** though...

Also, for the record, the LEDs are flashing happily every 8 seconds.

body:
I found an answer to a similar question here:
https://forum.sparkfun.com/viewtopic.php?f=32&t=39214&start=15#p175098

Note: it requires you to close and open the serial monitor at proper timings.

<!-- language: c -->

    // disable the USB prior going to sleep
    USBCON |= _BV(FRZCLK);  //freeze USB clock
    PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
    USBCON &= ~_BV(USBE);   // disable USB

    // and wake it up after
    //routine to properly wake up
    sleep_disable();
    delay(100);
    USBDevice.attach(); // keep this
    delay(100);
    Serial.begin(9600);
    delay(100);


message:
How to call URL with Arduino Ethernet shield?

I'm working on Arduino and Ethernet shield.

I need to call a URL. How can do it? (This URL is HTTP API to send an SMS to my phone).

 1. url:
    http://api.clickatell.com/http/sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello

body:
You need to use the **EthernetClient**. [link][1]

The exemple using your API call is:

    if (client.connect(server, 80)) {
        Serial.println("connected");
        // Make your API request:
        client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
        client.println("Host: api.clickatell.com/http/sendmsg");
        client.println("Connection: close");
        client.println();
    }

Full example from Arduino.cc docs:

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

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
    char server[] = "www.google.com";    // name address for Google (using DNS)

    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192,168,0,177);

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
       while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }
      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");

      // if you get a connection, report back via serial:
      if (client.connect(server, 80)) {
        Serial.println("connected");
        // Make your API request:
        client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
        client.println("Host: api.clickatell.com/http/sendmsg");
        client.println("Connection: close");
        client.println();
      }
      else {
        // kf you didn't get a connection to the server:
        Serial.println("connection failed");
      }
    }

    void loop()
    {
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        while(true);
      }
    }

  [1]: http://www.arduino.cc/en/Tutorial/WebClient


message:
Powering arduino uno from Car's reverse light?

I am making a reverse sensing alarm system. I am using a HC-SR04, arduino UNo and a piezo buzzer. The programming was a success however i will like this circuit to be powered when the reverse gear is shifted into place. So I am thinking to power the V in of the UNO with the 10V from the  reverse bulb socket receives. However I think the amperage sent to this bulb is too much for my UNO. What should I do ? and Does anyone have any other recommendations to power the UNO in such a scenario?

body:
Power the Arduino in parallel with the bulb.  Take the V+ wire running to the reverse light and the frame ground.  The frame ground is any bare metal surface of your car will be grounded, just connect a wire to your frame.  Or you can just splice the light bulbs ground wire.  When powering the circuit in parallel you do not have to worry about the amperage draw of the light.  By a barrel jack connector like [this connector from spark fun][1] you can buy these cheaper elsewhere just a 2.1mm barrel jack connector.  Connect the positive and negative respectively, and connect the 12v into the Arduino's barrel jack.

As a side note the bulb should be getting 12V not 10V it's not a huge problem, but it is a slight issue that could later be a problem or be caused by an electrical bug.  If everything works don't scramble to fix it, but be aware it exists.

  [1]: https://www.sparkfun.com/products/10287


message:
Can I use a UDOO as an Arduino?

I have a UDOO, and I wonder whether or not it is possible to use the Arduino that it has without starting the UDOO's operating system, i.e., I would like use Atmel Studio to load a program within the Arduino at UDOO.

body: Yes, but you have to erase the flash (and reset the ATMEL SAM3X8E processor) manually before the programming. You can use the J16 and J22 jumpers to do this.


message:
Not sure if programmer or ATMega is burned

some time ago i tried doing [this][1] with my original arduino uno r3. I guess i had to plug the power cables in wrong order(i think it's called reversing polarity)  because my arduino stoped working. It turns on (the power diode is on) but i cannot upload any sketch on it. I'm thinking about changing the ATMega chip but, before i do that i want to be certain that it's the chip issue ,not the programmer. I have another arduino uno, and i heard that i can upload sketch with it to another uno. So my idea is, if i do this i will be able to say whether it's the programmer or the chip issue. The only problem is that i don't know how to do this and i wasn't able to find any reasonable tutorials online. Please tell me what to do.
Many Thanks,
Jan

  [1]: https://www.youtube.com/watch?v=CMz2DYpos8w

body:
The Arduino IDE ships with a built in `ArduinoISP` sketch, and there is a very detailed [tutorial][1] with wiring diagrams etc on the Arduino site.

  [1]: http://www.arduino.cc/en/Tutorial/ArduinoISP


message:
Clone pro micro serial port 'COM4' already in use

So I just got this board I ordered from ebay and tried to play with it for the first time. http://www.ebay.com/itm/Leonardo-Pro-Micro-ATmega32U4-Arduino-IDE-1-0-3-Bootloader-replace-Pro-Mini-/310634777706?pt=LH_DefaultDomain_0&hash=item4853468c6a

I connected it to my PC and it was installing a driver. I didn't pay much attention to it but I think it finished installing it successfully. I then installed arduino IDE 1.6.3(latest) and tried to compile and upload the empty default sketch just to see if it uploads it. the progress bar got to the end but it was stuck on "uploading..". I waited for a few minutes but it didn't seem like it is going to end so I unplugged the USB and re inserted it back. I then looked in the tools menu and saw it was set to port COM1 which is the communications port on my pc, so I changed it to port COM4(Arduino Leonardo) and the board to Leonardo and again tried to compile and upload the default sketch but now I got this error:

Arduino: 1.6.3 (Windows 7), Board: "Arduino Leonardo"

Error opening serial port 'COM4'. (Port not found)

trying to open the serial monitor gives the same error.

So I checked the item listing on ebay and it said that the board was supported under arduino IDE 1.0.3 so I downloaded it and tried to compile and upload the default sketch but it gave me the serial port 'COM4' already in use error.

I tried resetting the board, uninstalling and reinstalling the driver and the IDEs and disabling/re-enabling the device in the device manager. nothing helped.

I am not sure what I am doing wrong as I am new to this.

Thank you.

body:
Reboot you PC, see if that clears it.

If not then fire up Device Manager and have a look at what COM ports you are using.

I think there is a way of reassigning the ports used by the boards within the control panel, but I can't remember what it is at the moment, so have a quick google.

Its not the fact that its a Clone that's causing you an issue, its Windows drivers that have caused you issues.  If all else fails, uninstall the drivers, reboot twice and try again.  I also don't think using a newer version of the IDE will have a negative affect.


message:
Electret microphone amplification

I've got an electret microphone and I understand that I need quite some amplification to get it to be read by an Arduino (0-5V input). So I seeked the web, but answers are as different as people on the street. Some use Op-Amps, some only a transistor cicruit or the like. This guy is using 2 amps before and after his filters [Video][1], [LM386][2] and this guy claims, that exactly this amp isn't good for the job: [recommends NOT using LM386][3].

I really only want to have a threshold switch, so I need no filters whatsoever and not a super duper amplification. What is the simplest solution, with which I can read a voltage with the arduino? With a transistor alone (seems easiest to me so far) - how can I know how much it amplifies (or as I understand it modifies the "other voltage" to look the same)?

I found many different schematics using various op-amps, but regarding them I don't really need another tutorial, but rather a rule of thumb for a "readable" amplification. Is 100 times enough? I found circuits with 1000 times amplification, so I'm really wondering which one works fine.

However the really simple thing would be this: [video at 17sec][4]. At second 17 and 50 or so, they show an extremly basic circuit, which would be exactly what would work best for me... However the question is, if this is enough amplification for the ADC in an arduino.

If I can't get a satisfying answer I think I'll build both and see how they compare/work for me.

  [1]: https://www.youtube.com/watch?v=hpMVG4a9sR4&feature=youtu.be
  [2]: http://wiring.org.co/learning/basics/microphone.html
  [3]: https://arduinodiy.wordpress.com/2012/12/20/electret-microphone-amplifier/
  [4]: https://www.youtube.com/watch?v=0E9DzgRuL_k

body:
For the most basic circuit you must bias your microphone since it is electret with a 10k pull up resitor. If you do not want to build a complex circuit you could use a breakout board such as [this one][1].  To build your own see [here][2]. It is used as a VU meter which is basically the same idea.  Also, make sure you observe polarity(pin with traces touching metal packaging is negative).

  [1]: https://www.sparkfun.com/products/9964
  [2]: http://www.arduino-hacks.com/arduino-vu-meter-lm386electret-microphone-condenser/


body:
You can use Maxim MAX4466 op-amp which works very well with Arduino. There is a breakout available for the same for arduino at Adafruit [here][1]. The chip has a select-able gain from 25x-125x. This amplifies works very well to get a nice waveform for audible noise. There are a couple of libraries available for the waveform that you record and can translate it to frequencies. You can also use it to distort or change the voice. Here is a schematic of the circuit if you want to make one yourself.![enter image description here][2]

  [1]: https://www.adafruit.com/products/1063
  [2]: https://i.stack.imgur.com/Va3A5.jpg


body:
I've built

![Inverting Op-Amp][1]

This circuit without C4 and everything after R4 (no rectifier, not a single diode used). R4 has to be switched for 100kOhms, since this gives a 100x amplification. I guess this is simple enough for most people.
Thanks for the hints.

The following code can be used to detect claps/noises. It is restricted to a double-clap with silence in between. Parameters can be easily tuned. This works quite well for me, even when I play noise/TV/music to the speaker directly it triggers rarely, or not at all!

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

    // CLAP switch using an electret microphone
    // switches ie. a relais or led with a certain
    // clap-melody

    // sound parameters
    const int THRESHOLD = 20;
    const int VAL_MEAN = 507;

    // trigger characteristics
    const int CLAPS_TO_TRIGGER = 2; // number of claps
    const int DEBOUNCE_TIME = 150; // ms to ignore double-clapping
    const int SILENCE_T = 40; // ms between claps, otherwise reset
    const int MELODY_INTERVAL = 800; // ms max time for the claps
    const int PAUSE_TIME = 2000; // wait after switch, or noise

    // pin-layout
    const int analogPin = 0;
    const int OUTPUT_PIN = 13;

    int output_state = LOW;
    uint32_t pause_t = 0;
    uint32_t debounce_t = 0;
    uint32_t start_time = 0; // timestamp of first clap-start
    uint8_t claps = 0;
    int sensorVal = 0;
    int amp = 0;

    void setup() {
      Serial.begin(115200);
      pinMode(OUTPUT_PIN,OUTPUT);
    }

    void loop() {
      sensorVal = analogRead(analogPin);
      amp = abs(sensorVal-VAL_MEAN);

      // Serial.print(F("sensed: ")); Serial.println(sensorVal);
      // Serial.print(F("amp: ")); Serial.println(amp);

      // at the end of an interval check the number of claps
      if (millis()-start_time > MELODY_INTERVAL & claps != 0) {
        if (claps == CLAPS_TO_TRIGGER & millis()-pause_t > PAUSE_TIME) {
          output_state = !output_state;
          pause_t = millis();
          digitalWrite(OUTPUT_PIN,output_state);
          Serial.print(F("Triggered "));
          Serial.println(output_state);
        }
        if (claps>CLAPS_TO_TRIGGER) { Serial.print(F("- too many")); }
        reset();
      }

      // noise/clap detected
      if (amp > THRESHOLD &\
          millis()-debounce_t > DEBOUNCE_TIME &\
          millis()-pause_t > PAUSE_TIME) {
        // there has to be silence between claps
        if (millis()-debounce_t < SILENCE_T+DEBOUNCE_TIME) {
          claps = 0;
          debounce_t = millis();
          Serial.print(F("reset - silence interrupted"));
          Serial.print(F(" amp "));Serial.println(amp);
        } else {
          claps++;
          debounce_t = millis();
          Serial.print(F("claps "));Serial.print(claps);
          Serial.print(F(" amp "));Serial.println(amp);
          if (claps == 1) { start_time = debounce_t; }
        }
      }
      delay(1);
    }

    void reset() {
      // time has expired
      start_time = 0;
      claps = 0;
      debounce_t = 0;
      Serial.println(F("reset"));
    }


message:
How to solve Atmega 16A Serial write (println) hang with Arduino Uno firmware?

For doing some experiments I bootloaded an Atmega16a with Arduino Uno. I am powering my Atmega16a from Arduino UNO. I am not using any external clock. Atmega16a is connected to a breadboard. For bootloading I refer the site http://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers I can run blink sketch on my Atmega16a using Arduino as ISP. TX and RX of Atmega16 is connected to Max485's DI and RO respectively.

    Atmega16a pin 14 (RXD) -> MAX485 pin 1-RO
    Atmega16a pin 15 (TXD) -> MAX485 pin 4-DI
    Atmega16a pin 17 (D3)  -> MAX485 pin 2 and 3. Also connects a LED to the pin

I used a boards.txt downloaded from https://github.com/sudar/arduino-extra-cores/blob/master/boards.txt

###Issue: hang at Serial.println

I faced issues when I started to interface with MAX485.

The program wont run if I add a `Serial.println`, see my program below.

    void setup() {
       Serial.begin(76800); // I tried 9600 too
       pinMode(3, OUTPUT);
    }

    void loop() {
      digitalWrite(3, HIGH);
      delay(400);
      Serial.println("20"); //comment this code and could see the led blinks
      delay(2000);
      digitalWrite(3, LOW);
      delay(400);
    }

###Regression

I tried Latest Arduino IDE as well as 1.0.6 version

I could do a serial communication with Raspberrypi and Arduino Uno via MAX485 without any issues. For the complete connection detail of MAX485 and other Arduino, check [my blog](http://sonyarouje.com/2015/04/23/rs485-communication-protocol-with-micro-controllers-and-raspberry-pi/).

Some times I receive some string to serial port of Raspberry pi like below. I run a nodejs app in RPi, using serialport npm and parser is RAW.

    <Buffer fa>
    <Buffer 82>
    <Buffer 86 ff>
    <Buffer fe>
    <Buffer fe>

How to prevent these hangs?

body:
Unfortunately you can't just simply upload the Arduino bootloader and expect it to work. The ATmega16 is not the same as the ATmega328. One quick look at the datasheet will already explain why this is not working. The UDR(USART data register) is at 0xC6 on the 328, while it's at 0x2B at the Atmega328. So the ATmega16 will look at the location where the 328 stores the received data and will not find it. This could explain the hang, but I expect that other things like UART setup will have gone wrong before you get to the receiving of data.

If you want serial communication with the ATmega16, try programming it directly in C with the AVR libraries and without the Arduino extensions. That will make it harder to figure out.


message:
What are the advantages of "Arduino compatible" boards

There are countless boards called ["Arduino compatible board"][1]. Some of them have specialized hardware features such as WiFi, SD card readers etc., but most of them seem like plain Arduino copies to me.

Sure, they are a bit cheaper, but for me the price difference doesn't make me favor the money I'd safe over the potential issues I have yet to discover.

**Question:** What are the benefits (or disadvantages) of Arduino compatible boards *(the ones without the "extras")* in general? Do you know an Arduino compatible board that you would recommend for some extraordinary features?

  [1]: http://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems

body:
Arduino compatible means that you would be able to use the boards directly with the Arduino IDE and you can use most of the libraries and examples that come for the official Arduino Boards.

The official Arduino boards comes with a standard set of features that are infinitely expandable, but sometimes you have constraints for a project and you need a board that you can easily adapt to a project, the compatible boards come handy in those place. For example, you can use [Ardupilot][1] to control UAV's and has a lot of sensors on it with a very small form factor but you can still code it with the Arduino IDE, you can use [Femtoduino][2] (which is an arduino board the size of a coin) for very small projects.

Another simple reason for using the compatible boards is that a lot times they are cheaper than the official Arduino Boards (see [Sparkfun Redboard][3])

You should be able to use any Arduino compatible boards without any problems but it would be better to go with a reputable supplier rather than a supplier in China to ensure that you get a good board that works without any problems.

  [1]: http://ardupilot.com/
  [2]: http://femto.io/
  [3]: https://www.sparkfun.com/products/12757


body:
While Arduino is an open source system, "Arduino" is a trademarked name and may only legally be used for products from the Arduino's originators or licensed suppliers. Arduino are quite clear about this requirement - [**see here - Logo**](http://www.arduino.cc/en/Trademark/CommunityLogo) and here [**Trademark**](http://www.arduino.cc/en/Trademark/HomePage?from=Main.Trademark)
and here [**What makes an Arduino board an Arduino?**](http://www.arduino.cc/en/Main/Policy) and [FAQ](http://www.arduino.cc/en/Main/FAQ)

As a result, compatible microcontroller boards are legally required to NOT identify themselves as being "Arduinos", so the term "Arduino compatible" is about the most that even an Arduino-identical clone can claim.

_____________________

As karan notes, some Chinese sourced Arduino compatibles "have issues".
however, I have had no problems at all with Arduino compatibles manufactured and supplied by [**this Chinese supplier**](http://www.aliexpress.com/store/812021/search?SearchText=nano). As well as the basic devices they sell various interface boards (shields) and related equipment. Prices are astoundingly low, free postage is included in many cases (about 2 to 3 weeks delivery time to New Zealand) or you can pay for courier delivery. I buy Nano or Pro-Mini compatibles devices  - usually in batches of 10. As you will see -  Nano compatible costs $US3 each in 10's. Pro Mini compatible is currently $US1.68 each in 10's. !!!
Uno compatible [**here**](http://www.aliexpress.com/store/812021/search?SearchText=arduino) is $3.80 in 10s.  The voltage requlator may be a different type than than on 'real' Arduinos (but work OK) and versions with a USB-serial bridge IC use a non FTDI IC and you need to source and load the correct (freely available) drivers.

NB: (1) I have NO commercial connection with this company except as a very happy customer.
(2) I'd expect you to have no problems with these or other products from them but I of course have  no responsibility for what they sell.


message:
How to use an Arduino Uno + Keyboard Firmware to make a "N Key Rollover" Game Pad

Hello I have flashed my Arduino Uno with USB keyboard firmware from this tutorial http://mitchtech.net/arduino-usb-hid-keyboard/#comment-6786, and I have been successful sending individual key presses but, not when trying to press an hold a key. I am attempting to use this firmware to create a custom Game Pad to USB adapter, the only issue is sending simultaneous keystrokes (not sending them one at a time). If you know how to accomplish this task I would be very happy. The technical term for this is "Key Rollover"

body:
You don't want to send random keys do you?

Well consider using the code below as your base.
It's using [Port Manipulation][1] to read the buttons (Digital 0 to 7).

    void setup()
    {
      Serial.begin(9600);//Start serial connection.
      DDRD = 0b00000000; //Set Data Direction Register of port D to inputs (attach keys to digital pins 0to7;
      delay(200); //Misc delay.
    }

    void loop()
    {
      Serial.write(PIND, 8); // Send states of PORTD (digital 0 to 7)
    }

I strongly suggest you use pull-down/up resistors on the buttons also.
Adjust your code to the amount of keys you're using, or pull the pins low if not used. To avoid receiving random/floating pin values.

  [1]: http://www.arduino.cc/en/Reference/PortManipulation "Port Manipulation"


body: After closer research on this topic I have found the answer to my problem but,thank you to all that have tried to help. In order to do "Key Rollover" I needed to write the additional key states to the remaining values of the buffer array then write the values with Serial.write(buf,8). I can now use my Arduino Uno + My Game Pads as controllers for all my computer games.


body: Could you post an example of your updated code?  I'm working on a similar project but a complete n00b as far as using the Arduino goes.


message:
Android Studio project for Redbearlab BLE Shield apps

To interact with its [BLE shield][1], Redbearlab published sample Android apps in the Play Store. The sources for the apps are available on [GitHub][2]. How can I build them in Android Studio?

  [1]: http://redbearlab.com/bleshield/
  [2]: https://github.com/RedBearLab/Android

body:
It was much simpler than expected to put together the Android Studio projects. They are on [GitHub now][1].

Note that the apps built from source are actually different from the ones published by Redbearlabs on the Play Store. On top of that, the chat app is not working.

  [1]: https://github.com/ryklith/RBL_for_Android_Studio


message:
Is it possible to program Arduino UNO with USB/TTL adapter withouth connection Vcc

For some strange reason my Arduino UNO clone board occasionally cause my Mac to reset, when I connect the usb cable. Possibly a power problem in Arduino or the USB hub.

Is it possible to program Arduino UNO with USB/TTL adaptor withouth conncecting the Vcc and GND pins (RX/TX and DTR only.)

body: If you power the board with an external source of electricity (e.g. a battery), it's possible. But as it can force your Mac to reset, it will possibly damage your battery.


body:
> Is it possible to program Arduino UNO with USB/TTL adaptor without connecting the Vcc and GND pins (RX/TX and DTR only.)

No.
As a minimum you need to add ground as well - even if the Mac is battery powered.  Serial port signals are ground referenced so removing the ground would prevent operation.

Operation is possible without deriving Vcc from the USB port, but you will then need to derive Vcc from some other source.

If connecting ground alone causes your Mac to reset you have a serious system problem which may damage your Mac and which possibly may be dangerous to you.

Presumably you are NOT using an external power supply for the UNO.
In case you are: If the power supply for the UNO is AC mains powered it should be connected to the same mains outlet as the Mac. If the programmer powerpack is intended to be grounded but is not powered from a grounded socket AND using a 3 wire mains lead (ie with a ground pin and wire) then it s possible in some cases for the programmer to float at half mains voltage with a high impedance capacitive connection to mains. This is not **usually** dangerous to people but can cause minor nuisance shocks. It can destroy equipment (ask me how I know :-( .)
If you have a DMM (digital multimeter) set it to an AC voltage range greater than your local mains voltage and measure the AC voltage from a known ground (such as a water tap in most cases) and the programmer power supply (either wire or jack terminal). If you measure a voltage of about 50VAC with 100 VAC mains or about 115 VAC with 230 VAC mains then the power supply MUST be operated with a 3 wire mains cord and grounded power socket OR a ground lead from mains ground to power supply output ground.

If the Mac is battery powered and you have reset problems then something is wrong with connections or signal levels. You may be feeding voltage back onto the USB lines or loading the too heavily or ... ?


body: It's possible the reboot isn't a hardware issue, short circuiting, but some kind of operating system issue such as a faulty driver, or conflicts... Best to have a look at the Console after a reboot to see if there are any notes here, or try the same Arduino on another Mac or PC.


body:
It is a bit of work, but it is possible to use a couple of optoisolators to build a circuit that will electrically isolate the MCU from the serial adapter.

![optoisolator circuit][1]

You should still figure out why your computer resets though, as it may not be related to the Arduino at all (e.g. maybe the cable is bad).

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


message:
Can I use custom ethernet shield with standard libraries?

I would like to make a custom ethernet card that uses the enc28j60 like this:
[DIY Ethernet card][1]

but first I would like to know if I can use the standard libraries which can be used with the ethernet card which is in the market like this:
[ENC28J60 ethernet module][2]

  [1]: http://www.picprojects.net/enc28j60_modul/index.html
  [2]: http://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=p2047675.m570.l1313.TR0.TRC0.H0.XENC28J60 module.TRS0&_nkw=ENC28J60 module&_sacat=0

body: The libraries don't care whether or not you're using a shield, only that you're using a device they support and that you've wired it up how they expect (or that you've modified the library to use the actual wiring you're using). So find a library that supports the ENC28J60 and knock yourself out.


message:
Ask for available ip on ethernet shield

Is there any way so an ethernet shield to ask the router for an available ip address? For example to ask for an ip an the router to return 192.168.1.2 if it is available. I am asking it because if we set the ip programmatically and it is attached to another device we gonna have problem.

body:
Using the [DHCP (Dynamic Host Configuration Protocol)][1] you can obtain an IP address dynamically from a DHCP server (which a router usually also is), without having to hardcode it into the firmware of the Arduino, thus enabling it to work on different networks.

There is also a library for that: http://www.arduino.cc/en/Tutorial/DhcpAddressPrinter. It's an extension of the official Arduino Ethernet library, written for the Arduino Ethernet Shield, but you'll likely find implementations of DHCP in many Ethernet libraries (I am using the [EtherCard library][2]) because it's an important feature to be able to connect to a network without a statically assigned IP and "only" requires UDP (on top of IP).

For e.g. the Ethernet library you call the [`begin` function][3] either with only the MAC address of your device or with MAC and IP address:

    Ethernet.begin(mac);
    Ethernet.begin(mac, ip);
In the first case it will use DHCP to obtain an IP address dynamically, in the second case it will use the static IP address you provide. Be warned that the second case, due to the needed implementation of DHCP, will increase the size of the compiled binary significantly.

  [1]: http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol
  [2]: https://github.com/jcw/ethercard
  [3]: http://www.arduino.cc/en/Reference/EthernetBegin


message:
What options are available for connecting to a CDMA network?

I am looking specifically to connect to a CDMA carrier from an Arduino. In doing research, I came across a CDMA shield option (requires getting a [CDMA module][1] that you drop [into a shield][2]), but that ends up being quite expensive - the CDMA module alone is $140, as opposed to a GSM shield which runs $30-$60. I've also tried looking for other CDMA modules, but haven't been able to find much.

Even if it's not sold as a proper Arduino shield, does anyone know of a CDMA module for hobby projects?

  [1]: https://www.nimbelink.com/2g-cdma-1xrtt/
  [2]: https://www.nimbelink.com/skywire-arduino-cellular-shield/

body:
I assume when you state "CDMA" it is Carrier Detect Multiple Access.  There are several that are not very expensive and can go thousands of feet such as a RS485 network.  The premium would be CAN, it will give your CSMA-NDA (Carrier Detect, Multiple Access, Non Destructive Arbitration). A non-destructive bit-wise arbitration is used to control access to the bus. There are many more but these seem to be very popular.  Of course you can always go to an Ethernet Network, that is not that expensive and is typically a star network where the others are point to point. This is not a  complete answer but it should get you going down the correct path.  CAN will not run with one node, it needs a remote node to acknowledge the transmission. Try this link for a better description: "http://bitstream24.com/controller-area-network-can-bus-arbitration-principle/' Check the people that support this forearm, they sell the modules with instructions and of course eBay.
Good Luck,
Gil


body:
There are no CDMA (more correctly known as CDMA2000) modules for hobby projects. There are a lot of reasons for this, which I won't get into, but suffice it to say, it is the way it is.

**EDIT**

Okay, I'll bite (just a little).

- I think the most important reason is CDMA is actually kind of USA-centric technology. While there are now a few other countries that have CDMA networks deployed, it pales in comparison to the number GSM networks globally.
- So in the cellular services world there is a service offering called machine to machine (M2M). What this is is a service to allow various machines (think parking meters, vending machines, ATMs, etc.) to have a data connection for control and status messages. These services are usually bought in bulk at rates much lower than equivalent consumer services would cost.
- The rest from here on out is just economies of scale. If I am making an ATM machine, would I rather be limited to a handful of countries, or be able to sell in almost all countries. The obvious choice is the latter, so these manufacturers use GSM.
- The reason a hobbyist can get anything cheap is because some other industry is using a lot of them. For example accelerometers used to be crazy expensive, that was until millions of cell phones started shipping with them every year, and now you can get them for pretty cheap. GSM modules are relatively cheap because there are lot of devices being made with them for the above mentioned reasons. CDMA modules are not so cheap because there are not a lot of devices using them.


body:
Take a look at this link, you should get the impression that CDMA envelopes a lot more then Cell Phones.
http://www.slideshare.net/mnsh01987/bluetooth-technology?next_slideshow=1

Since you did not state CDMA2000 and I was involved in the automotive industry I took that approach because you can use CAN, RS485 and many other adapters to implement it with the Arduino, to my knowledge a complete CDMA2000 package is not yet available to the Arduino users.  Initially we tested the CDMA theory with open collector transistors on a wire transmission line then we tested CSMANDA with the same hardware. From that point custom chips were designed and implemented. This was in the early 90's.


body:
I am looking at NimbeLink's Arduino baseboard which works with a CDMA modem. Never tried it, but thinking of ordering one. http://nimbelink.com/skywire-arduino-cellular-shield/. Not sure if you'd put this as 'affordable' since it is $40 for baseplate + $130 for modem.

Also this Arduino WCDMA 3G. http://linksprite.com/wiki/index.php5?title=3G_+_GPS_Shield_for_Arduino

Frustrating to have all this cheap awesome GSM technology, but only CDMA network in my region.


message:
Converting live vocals to discrete signals

I would like to augment a live music performance by displaying an specific LED for any given musical note.

**For vocals:**
Rather than attempt to process the audio using the Arduino board, I'd like to use something like an auto-tune box to do the heavy lifting.

**For digital instruments:** Would like to drive the Arduino board with some kind of digital signal (for example midi)

I'm having trouble finding out which (if any) consumer audio device can provide the pre-processing. Are there any comparable projects or insights?

body:
Confusing question. You list vocals and Digital Instruments, then you ask which audio device provided pre-processing?

There are the auto tunes boxes you mentioned. Since you know about them I don't see how you would be asking about them.

A digital instrument might output midi, and midi is just a simple serial protocol, so there is no device needed.

So what is your question actually?

An auto-tune box does work that would be best suited to a laptop or desktop computer. It first must determine the intended pitch than apply a formant filter to shift the incoming signal to a correct pitch. It requires the use of heavy fast math, Fast Fourier Transforms, FFT.  The smaller boxes you see doing this are actually specialized computers. Do not confuse their size with their power.

Google 'digital tuner software' to get an idea of what goes on.  I do not know of a device that specifically output the 'corrected' midi for an auto-tune, but at that point it would be fairly trivial so it would not surprise me if many did it.  For sure the many guitar to Midi converts do just that, but a good one is several thousand dollars.


message:
connecting GSM 900A module to arduino

I am trying to connect my arduino uno to GSM 900A with the help of this tutorial https://elementztechblog.wordpress.com/2014/10/10/interfacing-sim900a-gsm-modem-with-arduino/
but the calling is not being carried out.

The serial output is as following:

    Calling through GSM Modem
    Called
    ÿÿÿÿ

and the code is

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup()

    {

      Serial.begin(9600);
      Serial.println("Calling through GSM Modem");

      mySerial.begin(9600);
      delay(2000);
      mySerial.println("ATD99abc19965;");
      mySerial.println("ATH");
      Serial.println("Called ");
    }

    void loop()
    {

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

body:
You're really missing multiple parts here...

Check out this tutorial: http://tronixstuff.com/2014/01/08/tutorial-arduino-and-sim900-gsm-modules/

 - First of all, did you power up the SIM900A using its PWRKEY pin?

 - And can you send and receive AT commands?

How do you know that you have a valid GSM connection?
Did you try `AT+CREG?` and `AT+CPIN?`

 - Do you understand the AT commands you send?

You send `ATD` (with `abc` in the number?) and after that you *immediately* send ATH. Thus you would hang up directly after calling, and probably wouldn't even get to the actual calling part.

----------

    #include <SoftwareSerial.h>

    SoftwareSerial sim900Serial(10, 11); // RX, TX

    void setup()
    {
       Serial.begin(9600);
       Serial.println("Calling through GSM Modem");
       sim900Serial.begin(9600);
       delay(2000);
       sim900Serial.println("ATD99abc19965;");
       delay(10000);
       sim900Serial.println("ATH");
       Serial.println("Call ended ");
    }

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

Also, your code isn't very well formatted. Compare the code above with yours.


message:
How to drive motors and use an ultrasonic sensor simultaneously?

I have a L298 motor driver, which I coded with an Arduino Nano.
The code is very simple at the moment:

    // connect motor controller pins to Arduino digital pins
    // motor one
    int enA = 10;
    int in1 = 9;
    int in2 = 8;
    // motor two
    int enB = 5;
    int in3 = 7;
    int in4 = 6;
    void setup()
    {
      // set all the motor control pins to outputs
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
    }

    void demoTwo()
    {
      // this function will run the motors across the range of possible speeds
      // note that maximum speed is determined by the motor itself and the operating voltage
      // the PWM values sent by analogWrite() are fractions of the maximum speed possible
      // by your hardware
      // turn on motors
      Motors_FWD_PWM_Initialize();

      // accelerate from zero to maximum speed
      for (int i = 0; i < 256; i++)
      {
        analogWrite(enA, i);
        analogWrite(enB, i);
        delay(20);
      }
      // decelerate from maximum speed to zero
      for (int i = 255; i >= 0; --i)
      {
        analogWrite(enA, i);
        analogWrite(enB, i);
        delay(20);
      }
      // now turn off motors
      MotorsOff();
    }
    void loop()
    {
      demoTwo();
      delay(1000);
    }

    void Motors_FWD_PWM_Initialize()
    {
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
    }

    void MotorsOff()
    {
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }

Currently I have two questions:

__Q1:__ I have an ultrasonic sensor, how can I write the code so that the motors work and 'keep an eye out' with the ultrasonic sensor simultaneously? i.e. When a certain proximity is reached I would like the robot to stop.

__Q2:__ Also I would like my robot to 'rove' around. How can I make it so? I was thinking having a number of subroutines, and making the arduino randomly choose one.

body:
For the first question, you could simply implement an **interrupt routine** to regularly check the status of your sensor and when it achieves the desired threshold it triggers the action to stop the motor.

You can achieve this by setting timer1. There is a library [here][1] for example, where you set the period to execute a desired function, when some distance is detected you just stop the motors.

The second question could be done exactly like you said. Say you have some paths saved in memory, you can just create some options for them and execute whenever you want using switch/case command.

http://playground.arduino.cc/code/timer1

  [1]: http://playground.arduino.cc/code/timer1


message:
HC-06 Bluetooth RX & TX voltage (3v3 || 5v)

I acquired a HC-06 Bluetooth module, and understand that the voltage on the pins must be 3v3 and therefore requires the use of a voltage divider to lower the Arduino's 5v to 3v3 [like this.][1]

[![wiring diagram with 3V3 pullups][2]][2]

But the page where I purchased the product says the following:

> interface level 3.3V, you can directly connect a variety of SCM (51, AVR, PIC, ARM, MSP430, etc.), 5V microcontroller can also be directly  connected, it can not pass without MAX232 MAX232!

Does this mean I can connect without using a voltage divider?

What does "it can not pass without MAX232 MAX232!" mean?

  [1]: http://cdn.instructables.com/FFM/2LM8/HHS9W6IV/FFM2LM8HHS9W6IV.LARGE.jpg
  [2]: https://i.stack.imgur.com/OnBrt.jpg

body:
Some chips that run on 3.3v have 5v tolerant inputs. But it doesn't look like the BC417 does (looking at the datasheet).

So just add the voltage divider.


body:
About the MAX232, I have a Dwengo (similar to Arduino) and to use the HC06 I have to disconnect the serial port(=RS232) else I short circuit my HC06.

After some googling, MAX232 is simply the name of that chip which is required to convert your TX/RX from your bluetooth module to something usable by Arduino.

Source: http://en.m.wikipedia.org/wiki/MAX232


message:
Arduino serial informations

Is it possible to change serial information of arduinos board ?
For example I have an arduino uno with this serial informations :

    {
          comName: '/dev/cu.usbmodem1411',
          manufacturer: 'Arduino (www.arduino.cc)',
          serialNumber: '75430333137351804230',
          pnpId: '',
          locationId: '0x14100000',
          vendorId: '0x2341',
          productId: '0x0043'
    }
I want to modify for example the manufacturer to be able to automatically detect the device whatever the comName is. I don't want to detect arduino board I want to detect arduino board modify by me without make a serial connection.

body:
Once you have purchased a USB vendor ID you can edit the firmware within the Arduino installation at `hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/` with your vendor ID, chosen product ID, and other USB parameters as you wish and then rebuild the firmware and upload it to the ATmega16U2 on the board via ISP.

If you do not wish to purchase a vendor ID for the time being then you can use 0x6666, the prototype vendor ID, in the meantime, but you are not allowed to make products using that vendor ID available to the public.


message:
WebCam Face detection and tracking tutorial with Arduino Uno R3 and OpenCV 3.0 RC1 in Ubuntu 14.04

I try to make this Arduino Open CV tutorial for webcams. OpenCV 3.0 RC1 is compiled and installed. I also use Code::Blocks 13.12 as IDE. I am a newbie what comes to OpenCV and I do not know too much about Arduino either but here I am learning. Arduino IDE is 1.7.2. The tutorial is made for Windows 7 and software for this OS but I bet it is possible to repeat this in Ubuntu Linux 14.04 also.

So the tutorial is here:

<b>http://duino4projects.com/face-detection-and-tracking-with-arduino-and-opencv/</b>

When I try to compile and run the techbitarFaceDetection.cpp

the Code::Block IDE gives me following error:

>fatal error: Tserial.h: No such file or directory

So please tell me what to do next and how to fix this error.

body:
[`TSerial.h`][1] is part of the Serial C++ Library that is used by the project that you are trying to build (see the section "Software Required" on the tutorial page you linked).

Make sure you have that library installed correctly.

  [1]: http://www.tetraedre.com/advanced/serial/tserial.h


body:
Forget Tserial.h lib. To solve your problem (for serial communication) I sugest you to use "read/write from/to a file" programming method. The serial ports may be written to just like you are writing in a file. In the facedetect.cpp (OpenCV's example), in the detectAndDraw() function (I'm using OpenCV 3.0) add: `unsigned char MSB[1] = {0}; //
    unsigned char LSB[1] = {0}; //
    char serialPortFilename[]="/dev/ttyACM0";
    FILE *serPort = fopen(serialPortFilename, "w"); //`

than add:

    LSB[0]=r->x & 0xff;//
        MSB[0]=(r->x >>8) & 0xff;//

        fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
 fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

 LSB[0]=r->y & 0xff;//
        MSB[0]=(r->y >>8) & 0xff;//

        fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
        fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

into the if (0.75 < aspect_ratio && aspect_ratio < 1.3) statement.

Finally don't forget to close the file

    fclose(serPort);

Hope this will work for you!


message:
MOSFET to dim LED backlight

I have built the following to dim the brightness of the LED backlight of a display:
![enter image description here][1]
I am using a BS170 MOSFET (the diode is no extra part but included in the MOSFET, according to the [datasheet][2]). The BL pin is the supply of the LED backlight. (I have left out all other pins.)

Unfortunately, it does not work. Even if I set the PWM pin to 255, the backlight does not light (actually it's completely off). If I short BL and Vcc, it lights up as it should.

Also, the voltage readings confuse me: I measure 3.3 V on the gate and drain against ground, 1.5 V on source against ground (= the voltage across the backlight) but only 1 V if I measure drain against source.

So my questions are:

 1. Shouldn't this add up to 3.3 V?
 2. More importantly, why do I get only 1.5 V at BL?
 3. Most importantly, what do I need to change? Different MOSFET? No MOSFET?

The primary aim of controlling the backlight is to be able to switch in off completely, thus reducing power consumption. (Being able to dim it is only a plus.)

## EDIT ##
I should have added details about the display. It's one of those:
![enter image description here][3]

I haven't found a datasheet / specs for exactly this model. Most datasheets I found refer to a different version that is not 5 V compatible. A very similar model is described [here][4].

Concerning my question I haven't found information on how much current the backlight would draw. Therefore I didn't want to drive it directly from the PWM pin. (Actually I could just measure it...)

  [1]: https://i.stack.imgur.com/T3KtX.png
  [2]: https://www.fairchildsemi.com/datasheets/BS/BS170.pdf
  [3]: https://i.stack.imgur.com/dP3Uh.jpg
  [4]: http://skpang.co.uk/catalog/images/lcd/graphic/docs/User_Manual_ET_LCD5110.pdf

body:
**Summary:**
It looks as though you can just drive BL directly with the PWM-output.
What happens when you do?

______________

**Details:**

(1)  As shown, even  if the circuit did what you wanted, all you would be doing is providing a rail to rail (0V to 3.3V ) signal to the BL pin. You can do this by connecting PWM-out to BL directly.
Does this work?

If the LCD and Arduino used differing power supplies the MOSFET may be useful.

(2) To use circuit almost as-is you need a PChannel FET.
Swap Drain and Source and it will provide PWM to the BL pin. When BL is high the FET is off. When BL is low the FET is on. The FET used must turn on with about 3V between gate and source.

(3) To use the N Channel BS170 you must drive the gate +ve above the source by an amount that is enough to just turn it one "plus a little more". This is called Vth (Vthreshold). The BS170 has Vth ~= 1.8V at low currents. Vth varies somewhat between samples. When you connect the gate to +3.3V the FET tried to turn on but as the source rises it reduced Vgs until it reaches about Vth. Raising the source above this level reduced Vgs to below Vth so the FET is not turned on.
ie this is what a=accounts for the 1.5V that you see as 3.3V - 1.8V = 1.5V.

To use the BS170,
connect the source to ground,
connect drain via a say 1k resistor to +3.3V,
connect drain to BL,
drive gate with PWM.

BUT why does not just driving BL with PWM do what you want?
A data sheet for the display would be useful.


body:
Since you are switching on the high side, you need a P-channel mosfet, not an N-channel like the BS170. (Or you need a higher voltage on the Gate to reach the VGS(th)).

I have a similar display, but mine will light up if BL is connected to ground. For these kind of displays you'd use a N-channel mosfet.


message:
Control external device using Java Web Servlet -> Pi -> Arduino -> Device

I'm new to the world of Arduino & PI, so far it's been a fantastic experience but I'm now looking to build something a bit more practical.

My plan is for the PI to host a JSP Servlet website.  I'd like to go to a certain page of this site: 'powerCycleDevice' for example where it would pass a parameter in '?=on' or something similar.  This would then be picked up by the Arduino which in turn would then power said device.

It's also be nice to just use it as a monitoring station.  If I have several Arduinos hooked up (and I plan to - think Wallace & Gromit :)) then it'd be nice to view the statistics of each of the sensors.

My problem is not knowing if a: it's possible (I'm certain it is) and b: where to start.

If anyone can lend any advice, hints or tips on where to get started it would be fantastic.  A noob guide or tutorial would be great as I'd then use the info and expand upon it.

Thanks in advance.

body:
You can use Ardulink. It's a java open source project of mine. It can control an Arduino boad. So you have just to write a servlet that call my library. That's it.

See this post to understand how install ardulink in a PI: http://www.ardulink.org/how-to-install-arduino-pc-link-on-raspberry-pi/

You can read a sample code that sends some messages to Arduino you can read this post:
http://www.ardulink.org/how-to-blink-a-led/

The most important statement is **Link link = Link.getDefaultInstance();**

**Link** is the Ardulink class you need to send (and receive) messages.