body:
I would like to create some QNX applications and test them in a hardware different than my virtual machine. Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

What would be the challenges to make it work?

title: Is it possible to setup a system based on Arduino Due running QNX?

Answers: 2

body:
Typically the challenge in porting a new OS to a board is to configure stuff like:

- system clock (to drive the scheduler of the OS at the right frequence)
- board specific I/O
- components that are not part of the SoC (but iirc DUE doesn't have any of these)
- individual HW blocks (like on which serial port redirect the character interface, if your application has any)
- wakeup sources, in case you have/want low power modes and you need the board to wake up when something specific happens

None of these are impossible tasks and they are all good to learn more about the system, but otoh it's unlikely you can rush through them.

The good news is that probably you will not need them all and not immediately.

But some you will have to perform and they will require understanding how your OS works and having the technical reference manual of your board and SoC.

body:
> Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

Does QNX really support ARM Cortex-M3? I believe that is not possible as the processor does not have the necessary hardware support.

[![QNX Neutrino RTOS Architectuer][1]][1]

Please see the [BSP][2] list.

Cheers!

  [1]: https://i.stack.imgur.com/IkCPG.png
  [2]: http://community.qnx.com/sf/wiki/do/viewPage/projects.bsp/wiki/BSPAndDrivers


body:
I have an ATmeg328 TQFP on a board (in system). I use an Arduino Uno as an ISP to programm the chip. However, i would like to use Serial Communication with the chip through the Arduino board.

1. Is this possible?
2. If yes, how can i realize this?

EDIT: i have the tx and RX pins not available. The chip is on a board. With through arduino board, I mean that I would like to use the miso mosi sck pins to do this.

title: Arduino as ISP with serial monitor for ATmega328

Answers: 3

body:
Just burn the arduino bootloader to your tqfp. Then connect the tx and rx on the tqfp to the tx and rx on your arduino, and pull the reset line on the arduino low.

Downside is you have to do a manual reset on the tqfp before programming. If you have an Uno you could remove the atmega from the socket, and connect the reset on the uno to the reset on the tqfp.

Another option is to connect the TX on the tqfp to the TX pin on the Arduino using a resistor. But for this to work you have to modify the ArduinoISP sketch to make it release TX pin (`UCSRnB &= ~_BV(UCSRnB);`) and set it to input. And reverse it when data is received on the RX. Not trivial, and only works one way (tqfp to PC).

body: In addition to my previous comment-suggestion that you could implement communication over SPI by adding functionality to both the ISP sketch and the target program, it now occurs to me that another approach would be to implement software serial functionality on both, assigned to some of the pins used for ISP during that process.

body:
as [here][1]? Nick Gammon has a sketch which includes an ISP with serial control. Sketch is available on GitHub [here][2]

  [1]: http://www.gammon.com.au/bootloader
  [2]: https://github.com/nickgammon/arduino_sketches


body:
I have a pretty complicated setup: an ATMEGA328p chip (found in the Uno, Duemilanove, etc.) on a Diavolino board (from EvilMadScientist) running at 8 MHz (instead of the normal 16 MHz).  This should be basically the same thing as the 3.3V arduino pro from the code's point of view.  On top of this is a custom shield including a bunch of digital and analog devices with SPI, I2C, and serial interfaces.

This is supposed to run for days or weeks at a time.  In normal conditions--on the ground outside--it does fine.  However, in two recent tests, it lost its program and stopped working.  One of these was in a cold low-pressure chamber (-40 C/F).  The other was outside mounted on a flying quadcopter.  Reprogramming it fixed the problem; before reprogramming, neither a reset nor power-cycling would get any response from it.

Has anyone ever heard of an arduino bricking itself like that?  My best idea for how this could happen is that somehow the chip was put into a state where it treated incoming serial data as a new program to run.  Also, I'm speculating that connections between the two boards could have been disrupted by thermal contraction or vibration in those tests.

Thanks for any help!

title: Arduino loses its program under unusual conditions

Answers: 1

body:
I would suggest that you reproduce the issue and then use a device capable of _reading_ the flash, to confirm that it's still identical to the .hex file that was used to program the board.

I know that the AVRDragon can do it and maybe also cheaper USB ISP programmers can do it too.

But it seems that [you are not alone][1].

Flash memories like those used in uC work by trapping electrons in wells of charge, so that they pseudo-permanently affect the silicon.

Very low temperatures can change the properties of the insulation, letting many more electrons than usual to escape.

Try to wrap the board in a thermal airtight insulator, possibly providing local heating. That should solve your problems.

  [1]: https://www.physicsforums.com/threads/nor-flash-failures-at-extreme-low-temperatures.207832/


body:
Im getting this error:

    iotHook.ino: In function 'void setup()':
    iotHook:13: error: request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'
    request for member 'begin' in 'esp', which is of non-class type 'Esp8266()'

When I try to lunch my begin function of my class:

    class Esp8266 {

      public:
        Esp8266();
        void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
        ...
      private:

        HardwareSerial *wifiCom;
        HardwareSerial *debugCom;
        ...

    }

    Esp8266::Esp8266() {
    }

    void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
      this->wifiCom = wifiCom;
      this->debugCom = debugCom;

      this->debugCom->begin(115200);
      while (!this->debugCom) {
      ;
      }
    }

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

EDIT 1:
Updated image with new code
[![enter image description here][2]][2]

Why is not picking up the begin function?

  [1]: https://i.stack.imgur.com/LsAdO.png
  [2]: https://i.stack.imgur.com/Io6tr.png

title: Request for member is Non-class type

Answers: 3

body:
You've confused the compiler by making it think that `esp` is a function that takes no arguments and returns a `Esp8266`. But the no-argument constructor is called by default, so you don't need the parens there regardless.

    Esp8266 esp;

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

The line:

    esp.begin (Serial, Serial1);

Should be:

    esp.begin (&Serial, &Serial1);

It is expecting a **pointer** to a HardwareSerial instance.

---

Also make the instantiation line:

    Esp8266 esp;   // <--------- no brackets!

---

This compiles without errors for me:

    class Esp8266 {

      public:
        Esp8266();
        void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom);
      private:

        HardwareSerial *wifiCom;
        HardwareSerial *debugCom;

    };

    Esp8266::Esp8266() {
    }

    void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) {
      this->wifiCom = wifiCom;
      this->debugCom = debugCom;

      this->debugCom->begin(115200);
      while (!this->debugCom) {
      ;
      }
    }

    Esp8266 esp;

    void setup ()
      {
      esp.begin (&Serial, &Serial1);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

I would rework to use references anyway, saves all that mucking around with pointers:

    class Esp8266 {
      public:
        Esp8266(HardwareSerial & wifiCom, HardwareSerial & debugCom);
        void begin();
      private:
        HardwareSerial & wifiCom;
        HardwareSerial & debugCom;
      };

    // constructor
    Esp8266::Esp8266(HardwareSerial &wifiCom_, HardwareSerial &debugCom_)
      : wifiCom (wifiCom_), debugCom (debugCom_)
      {
      }

    // initialize stuff
    void Esp8266::begin()
    {
      debugCom.begin(115200);
      while (!debugCom)
      {
      }
    }

    Esp8266 esp (Serial, Serial1);

    void setup ()
    {
      esp.begin ();
    }  // end of setup

    void loop ()
    {
    }  // end of loop

---

## Corrected for Leonardo

Sorry, my reply above was compiled for the Mega2560, I didn't notice the Leonardo tag.

Majenko is quite right, you need to rework for the Leonardo. My example using references can reduce down to this now:

    class Esp8266 {
      public:
        Esp8266(Stream & wifiCom, Stream & debugCom)
          : wifiCom_ (wifiCom), debugCom_ (debugCom) { }

      private:
        Stream & wifiCom_;
        Stream & debugCom_;
      };

    Esp8266 esp (Serial, Serial1);

    void setup ()
    {
      Serial.begin (115200);
      while (!Serial) { }
      Serial1.begin (115200);
      while (!Serial1) { }
    }  // end of setup

    void loop ()
    {
    }  // end of loop

By storing a Stream type you can still print to them, however you need to initialize in `setup`, not in the `begin` function, which now becomes redundant.

I agree about not using `this->` although my preference is for trailing underscores as the use of leading underscores is reserved in quite a few cases, depending on the location and capitalization.

body:
Your current problem is that the USB Serial interface of the Leonardo isn't a hardware serial device, it's a CDC/ACM device, and the class for that isn't HardwareSerial, it's Serial_.

So you can't pass it to a function that expects a HardwareSerial.

What you should be using, instead, is the Stream class.  That will allow you to pass any object that is based on the Stream class, such as HardwareSerial, Serial_, Client, etc.  Many different things, including serial and networking protocols, use Stream as their base class.

It does have the down side, though, that you have to initialize the Stream objects in your sketch (that is, do the Serial.begin(...) and Serial1.begin(...) in your sketch not your class) because the Stream class doesn't have the concept of a baud rate, and so no begin(baud) function.

This is what I mean:

    class Esp8266 {

    public:
     Esp8266();
     void begin(Stream &wifiCom, Stream &debugCom);
    private:

     Stream *_wifiCom;
     Stream *_debugCom;

    };

    Esp8266::Esp8266() {
    }

    void Esp8266::begin(Stream &wifiCom, Stream &debugCom) {
     _wifiCom = &wifiCom;
     _debugCom = &debugCom;

     while (!_debugCom) {
      ;
     }
    }

    Esp8266 esp;

    void setup() {
     Serial.begin(115200);
     Serial1.begin(115200);
     esp.begin(Serial, Serial1);
    }  // end of setup

    void loop() {
    }  // end of

Note, as well, my use of pass-by-reference (Stream &whatever) so you don't have to pass a pointer in your begin function.  Also notice the use of unique variable names in the class (I always prefix my member variables with `_`) so you don't have to keep putting `this->` in everywhere.

----

To be able to move the `.begin()` function inside your class you will have to use both `HardwareSerial` and `Serial_` object types within your class.  There's two ways this may be done.

First is [*dynamic casting*](http://en.cppreference.com/w/cpp/language/dynamic_cast):

    void Esp8266::begin(Stream &wifiCom, Stream *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;

        HardwareSerial *hard;
        Serial_ *cdc;

        if (hard = dynamic_cast<HardwareSerial*>(_wifiCom)) {
            hard->begin(115200);
        } else if (cdc = dynamic_cast<Serial_*>(_wifiCom)) {
            cdc->begin(115200);
        }

        if (hard = dynamic_cast<HardwareSerial*>(_debugCom)) {
            hard->begin(115200);
        } else if (cdc = dynamic_cast<Serial_*>(_debugCom)) {
            cdc->begin(115200);
        }

    }

I haven't tested this, and I don't know if the Arduino's cut-down C++ library is even capable of it, but it's worth a try.

The other method is to *overload* the `.begin()` function of your class with multiple versions that take different parameters:

    void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        wifiCom.begin(115200);
        debugCom.begin(115200);
    }

    void Esp8266::begin(HardwareSerial &wifiCom, HardwareSerial *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        wifiCom.begin(115200);
        debugCom.begin(115200);
    }

    void Esp8266::begin(HardwareSerial &wifiCom, Serial_ *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        wifiCom.begin(115200);
        debugCom.begin(115200);
    }

You're still storing them internally as `Stream` objects in all cases, but within the `begin()` function itself you also have them available as their child classes.  It does mean you have duplicate code copied between the different versions of `begin()`.  You could modularize it a little more though by moving the duplicated code into functions which would only need to be duplicated twice, not three times - one to act on a single `Serial_` object and one to act on a single `HardwareSerial` object:

    void Esp8266::initSerial(Serial_ *ser) {
        ser->begin(115200);
    }

    void Esp8266::initSerial(HardwareSerial *ser) {
        ser->begin(115200);
    }

    void Esp8266::begin(Serial_ &wifiCom, HardwareSerial *debugCom) {
        _wifiCom = &wifiCom;
        _debugCom = &debugCom;
        initSerial(&wifiCom);
        initSerial(&debugCom);
    }
    ... etc x3 ...


body:
I have an application that requires reading sensors and moving a stepper motor.
The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.

My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.

From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.

The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.

This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.

I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?

Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).

And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)

title: Powering arduino and sensors and motor damaging 16x2 LCD?

Answers: 1

body:
In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.

A few suggestions:

Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister.  That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.

You should also check the pins for continuity errors, or shorts.

Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.

And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.

I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.

I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.


body:
I have extracted a speaker frim a cheap radio. And I want to connect it to arduino uno. But, I dont know the rating of the speaker. And I am Afraid that If it is over rated, it can fry my arduino. The diameter of the speaker is 9 cm (approx). Whether this Speaker is more likely to be  of 4 ohms, 8 ohms, or 16 ohms ???
I dont have a multimeter...What cam be the probable value of speaker ?

title: Knowing the Ohms of a Radio Speaker

Answers: 2

body:
I googled "measure speaker resistance" and found http://www.wikihow.com/Measure-Speaker-Impedance

Step by step instructions

You will need a multimeter - a great thing to have in any case.

body:
I'm not aware of any simple rule that relates speaker diameter to speaker impedance.  Traditionally, 8 Ω is quite likely for typical cheap speakers, with 4 Ω not far behind in likelihood.

As pointed out in the [Measure Speaker Impedance](http://www.wikihow.com/Measure-Speaker-Impedance) link that AMADANON gave, the DC resistance of the speaker's coil will be somewhat lower than the speaker's AC  impedance.  The link suggests 6 Ω DC resistance for a speaker with 8 Ω impedance.

As far as driving the speaker from an Arduino output pin, all of the likely values of speaker impedance are too low to allow driving it directly.  Dividing the maximum allowed pin current of 40 mA into 5 V gives 125 Ω as the least resistance an Arduino output should ever see.  When I attach a speaker to an Arduino output, I usually put a 200 to 400 Ω resistor in series with it.  For my purposes (eg alert-buzzers) that gives enough volume without overstressing the Arduino.

If you still have the radio, look for a small transformer near the speaker connection.  If the radio has an audio output transformer, it probably will have a few KΩ of resistance in the primary and a low-resistance secondary.  If you attach the primary of that transformer to the Arduino pin you can deliver slightly more power to the speaker, but may need some  [clipping diodes](https://www.google.com/search?q=clipping+diodes&biw=1112&bih=593&tbm=isch&tbo=u&source=univ&sa=X&ved=0CCwQsARqFQoTCNXa8qC6yMcCFckziAodpccJmw) or [flyback diodes](https://www.google.com/search?q=clipping+diodes&biw=1112&bih=593&tbm=isch&tbo=u&source=univ&sa=X&ved=0CCwQsARqFQoTCNXa8qC6yMcCFckziAodpccJmw#tbm=isch&q=flyback+diodes) in the circuit to prevent damage from overvoltages.


body:
I have the following problem and wonder if anyone may have some inside into what may be happening.

I have an array of 20 leds that i manage to multiplex using the attiny88 using only 9 pins (4 columns by 5 rows). At any given time only one led is on. The different leds are activated with a pushbutton. Initially, i used five transistors with a 1k resistor to turn on and off the rows of the led array.

Everything worked like a charm even at voltages as low as 2.5 vol. I then decided to remove the transistors to free-up some space in my pcb. Now the circuit works well at voltages above four but at 2.5v it makes leds to turn on randomly, when pressing the pushbutton.

I presume this behavior is because the one led is taking to much current, but i wonder why could be the case if the chip is only driving one led at a time. Also keep in mind that the circuit works very well at 4vol.

Any clue about this and how could i fix it? I like the idea of not using the transistors.

title: Attiny88 problem with LEDs and voltage

Answers: 0


body:
I want to create a structure called CarSpeed it has 4 int FR,FL,BR,BL (FrontRight,..) ; and i would like to create a function that returns this structure :

    ActualSpeed Readspeed(void)
    {
       code to read the speed of the car(already done)
    }

Can someone help me define a function that returns this structure  ? only the way how I should define it, the usual C way doesnt work :

    typedefstruct CarSpeed{...}

and then

    CarSpeed ActualSpeed;
    ActualSpeed Readspeed(void){.. }

title: Function that returns a Structure

Answers: 2

body:
I would recommend to use pointers, it's faster and has the same result.

Something like this (disclaimer - I did not compile it):

    typedef struct {
       int a;
       int b;
    } pair;

    int init_pair(pair *ptr) {
       if (!ptr)
          return -1;
       ptr->a = 6;
       ptr->b = 9;
       return 0;
    }

    int do_something() {
       pair mypair;
       return init_pair(&mypair);
    }

body:
Since you're (probably) using a C++ compiler, it's usually easier to declare structures like this:

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

    struct CarSpeed
    {
        int fr, fl, br, bl;
    };

(Note that there's no need for `typedef`.)

You can then return an instance of it directly from your function:

    CarSpeed ReadSpeed()
    {
        CarSpeed data;

        data.fr = ...;
        data.fl = ...;
        data.br = ...;
        data.bl = ...;

        return data;
    }

You can call it from another function like this:

    CarSpeed speed = ReadSpeed();

That will copy the contents of the structure into an object called `speed`. In this example, it's an 8 byte structure so it's a non-trivial copy. That shouldn't be a big problem unless you're calling it very frequently though.

As noted in another answer, using a pointer (or a reference) can be more efficient if necessary.


body: Hi i would like to implement a sensor and control system for my home. Basically, i would like to send and receive data to my arduino uno using esp8266. I am able program the esp8266 using at commands to send http request to my server. How can i make my server send commands to my arduino uno using esp8266?

title: Send and Receive with ESP8266 and arduino

Answers: 0


body:
I need my Arduino to connect to my web server through HTTPS, can the Arduino handle it?

It only has to act as a client.

title: Can a WiFi enabled Arduino make a HTTPS request to my Web Server?

Answers: 1

body:
It sounds like a better way to do it would be to have a PHP script act as handoff server (maybe protected by originating IP address) to access the HTTPS site and provide the data over a less processor-intensive protocol.

[https://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino][1]

However, another answer suggests that we are working towards a solution to your issue, but it's not quite there yet (~12 seconds to encrypt a packet).

[https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/][2]

  [1]: https://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino
  [2]: https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/


body:
My intent with this sketch is to have motors run for one minute, then stand by for 18 minutes. In practice, the sketch starts the motor state at "low" for the OffTime interval, then goes to the OnTime interval and loops. The desired result is exactly the opposite: the "high" interval first, followed by the "low". I have tried setting the motorState to "HIGH" in the constructor and played with the order of the IF statements to no avail.

I would appreciate any insight into this problem, as well as an intuition for the practical use of millis(). I need a solution which doesn't use delay but am having trouble wrapping my head around the logic of millis() as used. (I adapted this code from a tutorial.)

    class LifeTest
    {
      // Class member variables initialized at startup
      int motorPin;
      long OnTime;
      long OffTime;
      // These maintain the current state
      int motorState;                               // Used to set the motor.
      unsigned long previousMillis;                 // Stores last time motor was updated.

      public:
      LifeTest(int pin, long on, long off)
      {
        motorPin = pin;
        pinMode(motorPin, OUTPUT);

        OnTime = on;
        OffTime = off;

        motorState = LOW;
        previousMillis = 0;
      }

      void Update()
      {
        unsigned long currentMillis = millis();     // Check to see if it's time to change the motor state.
        if((motorState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
        motorState = LOW;                         // Turn off motor.
        previousMillis = currentMillis;           // Remember the time.
        digitalWrite(motorPin, motorState);       // Update the motors.
        }
        else if((motorState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
        motorState = HIGH;                        // Turn on motor.
        previousMillis = currentMillis;           // Remember the time.
        digitalWrite(motorPin, motorState);       // Update the motors.
        }
      }
    };

    LifeTest motor1(50, 60000, 1080000);
    LifeTest motor2(51, 60000, 1080000);
    LifeTest motor3(52, 60000, 1080000);
    LifeTest motor4(53, 60000, 1080000);

    void setup()
    {
    }

    void loop()
    {
      motor1.Update();
      motor2.Update();
      motor3.Update();
      motor4.Update();
    }

title: How do I set the motor state to "HIGH" at the beginning of this sketch?

Answers: 2

body:
just change the constructor to

      LifeTest(int pin, long on, long off)
      {
        motorPin = pin;
        OnTime = on;
        OffTime = off;

        previousMillis = 0;

        motorState = HIGH;
        pinMode(motorPin, OUTPUT);
        digitalWrite(motorPin, motorState);
      }

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

> I would appreciate any insight into this problem, as well as an intuition for the practical use of millis().

I have a lengthy tutorial about this at [How to do multiple things at once ... like cook bacon and eggs](http://www.gammon.com.au/blink).

However as this site frowns upon link-only answers (the link might go down) I'll try to explain as well, here.

`millis()` is like having a wristwatch. You glance at it from time to time to see if it is time to do something, like catch a bus to work, put the dinner on, take the cake out of the oven, that sort of thing.

If you `delay()` all the time, you can only do one thing at a time. For example, if your cake takes 30 minutes to cook, and you do this:

    PutCakeInOven ();
    delay (30UL * 60 * 1000);  // delay 30 minutes
    TakeCakeOutOfOven ();

This is fine, but you aren't also cooking some eggs at the same time, or doing the dishes, right?

With `millis()` you can do lots of things! Win-win! The basic technique is to note the time when you started, and then when time is up, you do whatever-it-is you need to do. Like this:

    unsigned long BakeStartTime;
    const unsigned long CookingTime = 30UL * 60 * 1000;  // 30 minutes
    bool CakeInOven = false;

    void setup ()
      {
      PutCakeInOven ();
      BakeStartTime = millis ();  // when the cake went into the oven
      CakeInOven = true;
      }

    void loop ()
      {
      if (CakeInOven && (millis () - BakeStartTime >= CookingTime))
        {
        TakeCakeOutOfOven ();
        CakeInOven = false;
        }

      // do a whole lot of other stuff, like cooking some eggs

      }

You can expand this technique to do dozens of things "at once".


body:
I am planning to do a project on Sequential tilt motion lock using Arduino uno and accelerometer. I would like to present the accelerometer **within** a rotatable object. So what other components do i have to add to be able to do it i.e.. for wireless transmission of data from the object(that has the acc. meter) to the Uno board. [![Tilt lock circuit ][1]][1]

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

title: Need help in modifying the design

Answers: 1

body:
If you do a google search for "arduino wireless serial" you'll get several results. Plugging them into the arduino should be trivial. Most suppliers (other than ebay) will also have examples for you to reference where it comes to coding your project to use the module.

You should also be aware that you will usually need a transceiver, and a receiver.

You might take a look into the XBEE solutions, as they appear to be popular.


body: I am an undergrad in ICE. I was searching for ideas to do mini projects on and found this Arduino boards and programs. So actually what are the basics to develop our own gadgets? Any guidelines...?

title: What are the basics in writing a program in Arduino?

Answers: 1

body:
There are some excellent books available as well as videos and articles on the Internet which will walk you through basic projects.  The most common method of programming is to use the free [Arduino IDE][1] which will talk to the board from your Mac or PC.  You can run the board straight from the USB port's power, or from an external source if you need it to be portable.

The programming language is very similar to C.  The program structure is basically a setup portion and then a continuous main loop that runs until the board is powered off.

If you want to experiment without actually purchasing one, there are some emulators available which will let you build entire project on a virtual breadboard before buying any actual components.  [Fritzing][2] is a great board planner that you can install, or if you would rather, you can use [123D Circuits][3] from your web browser which will let you edit and simulated the circuits.

Basic knowledge of electrical circuits will be helpful for getting started, and is a great asset when designing larger projects.

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: http://fritzing.org/
  [3]: https://123d.circuits.io/


body:
I'm making a few experiments with a quite simple rover car I made using Arduino UNO and a few spare parts. Just for the heck of it I made it waterproof and now I want to toss it in my pool to make some underwater exploration. Maybe I'll fit some scrubers under it to make it easer to clean the floor.

My problem is: my rover navigates on its own, avoiding walls and objects using an ultrasonic sensor. But underwater the speed of sound goes up, and different qualities of water make it even harder for this system to work. Sometimes the pool is full of particles, and the scruber will probably worse the water quality around the robot.

My question is: what kind of system is better to navigate underwater, simply avoiding walls? The current behavor (on dry ground) is to turn to the right and go on when it finds a wall, I would like to keep this behavior, but underwater. As it's a simple toy, I'm hardly willing to spend a hundred bucks on a fancy laser proximity sensor, neither I need to map the entire pool with a single pulse, it should be a simple wall avoiding system.

Thank you!

title: Underwater positioning system (swimming pool)

Answers: 1

body: How about a tilt switch?  The bottom corners of a pool should allow the car to ride up the wall a little, when it tilts past 5 or 10 degrees, turn it left.....


body:
I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine.  I need them to have unique serial ports.  Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible).

This is the serial number that I get for both:

    $ udevadm info -a -p  $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial
      ATTRS{serial}=="0000:00:14.0"

Is there any way to manually set the serial number on an Arduino Micro?  Or is there any other unique identifying properties I can use for udev rules?

Typically, I do something like this in my ```/etc/udev/rules.d/99-usb-serial.rules``` file:

    SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice"

Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.

title: How to differentiate between 2 Micros on Linux

Answers: 2

body:
The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch.  The VID and PID are tied to the board, and the serial number is always the same regardless of which board.

So no matter which board you program it will get the same details as any other board of the same kind.

There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: `USB_VID` and `USB_PID`.

So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board.  You can then differentiate the two boards in udev using the VID/PID combination.

Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.

body:
That "0000:00:14.0" isn't the serial number for the Arduino: udevadm is printing info for more than one device, and that's for the USB controller chip.

Arduinos built on the ATMEGA32U4 don't get a serial number: I have some Leonardos giving me the same problem you're having. When the bootloader was originally designed, the programmer didn't have it report one. I found a modified bootloader that does, but I haven't tried it yet: http://forum.arduino.cc/index.php?topic=503703.0

Genuine Arduinos with an FTDI chip report unique serial numbers. Some of the knock-offs either don't set it in the chip, or may set it to some non-unique number(skipping that step to save a  few cents of manufacturing cost). Ones that use a 16U2 chip for the USB interface (like the Uno R3) are *supposed* to get a unique serial number. The Chinese ones I just bought did, but it's possible that other makers of them are cutting corners like some users of FTDI chips do.

Arduinos that use the Chinese CH340 USB chip also don't report a serial number: the chip doesn't support it. I *think* that's also true for the CP2102, but I'm not certain.

You *may* be able to fix the problem with that modified bootloader (I hope so: I have half-a-dozen Leonardos, and it's a hassle anytime I have more than one connected simultaneously. Fortunately, I don't normally use them as "PC peripherals"). Or you could buy another of the "tiny" Arduinos with a 328P that uses a USB-to-serial chip, and base the udev rules on VID and PID to distinguish them.


body:
I have a section of code that I am unsure of what it is doing.

    static int bufindw = 0;
    static char buffer[4][96];
    static char *strchr_pointer;
    int result;

    result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The part where I don't understand what is happening is `strchr_pointer - buffer[bufindw] + 1`. `strchr_pointer` and `buffer[bufindw]` will be strings. It gives the result I expect it to give because I know in the end it needs the correct index value in `buffer[][]` and in addition the number 1 is being added to it as well. How can a string minus a string?

title: String operators

Answers: 1

body:
Let's break it down logically for you.

You have 4 strings, each capable of containing 96 characters:

    static char buffer[4][96];

That is a block of RAM that covers 4*96=384 bytes.  Let's say that block of ram starts at address 0x100.

    result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The phrase `buffer[x]` returns the address of the string number `x` in your array of strings.  It's the same as `&buffer[x][0]` - the address of the first character in string x.

You also have a pointer `strchr_pointer` which contains something - what that is I don't know because you haven't told us.  Chances are it's the result of a `strchr()` call, which:

> returns a pointer to the first occurrence of the character c in the string s.

So you have looked for a character in a string and found that it's at a specific address.  Let's say that's address 0x111 for the sake of argument.

Ok, so if we take `bufindw` as 0 for the first string in your array, and work from the inside out, we have:

*    buffer[bufindw] = 0x100
*    strchr_pointer = 0x111
  *    strchr_pointer - buffer[bufindw] = 0x111 - 0x100 = **0x11**
  *    strchr_pointer - buffer[bufindw] + 1 = 0x100 - 0x111 + 1 = **0x12**
*    Replace that into the function's parameters:
  *    &buffer[bufindw][strchr_pointer - buffer[bufindw] + 1] = &buffer[bufindw][0x12]

So you have the address of the 0x12'th (18th) character (or character number 16 since they count from 0 not 1), which is address 0x112.

That address is then passed to strtod() to convert it into a double-precision number:
    strtod(0x112, NULL);

That value is then cast to an integer:

    (int)strtod(0x112, NULL);

So the decimal portion is discarded (not rounded, chopped off).

Say your string contains: "`This is the value:23.83589743`" and is located at 0x100.

You use strchr() to find the first occurrence of ':', and it finds it at address 0x111, which is the 18th character of the string, so 0x100 + 17 = 256 + 17 = 273 = 0x111.  You subtract the start of the string and add one to it, so you end up with 18, which is the start of the numeric value (the 18th character).  The string from that point on contains "`23.83589743`".  That is then passed to `strtod()` and cast to an integer, and so is truncated to `23`.

It's not surprising you're confused, the whole thing can be re-written much simpler:

    strchr_pointer = strchr(buffer[bufdindw], ':');
    result = (int)strtod(strchr_pointer, NULL);

All that manipulating of the buffer address is like doing "x = 6 + y - 3 + 4 - 7" - completely pointless, since you might just as well write "x = y".


body:
I have an LED strip that I am trying to turn on with a magnetic switch when a door opens. I want the LEDs to fade on when I open the door and fade off when I close it, which is where the Arduino comes in. I am using PWM for the fading. I can get each component to work separately. The fading LEDs work with the MOSFET without the switch. I tested the switch with serial output on the Arduino and it works fading a single LED without the MOSFET.

I am using:

- Arduino Uno R3
- Magnetic Switch
- N-Channel MOSFET IRLB3034
- 5 Meter White LED Strip
- 12VDC 30W Power Supply
- 10k Ohm Resistors

My setup looks like this:
![breadboard diagram](https://i.stack.imgur.com/lDJYg.png)

Schematic:
![schematic](https://i.stack.imgur.com/y3mX4.png)

Code (if it helps):

    const int buttonPin = 2;     // the number of the switch pin
    const int ledPin =  9;      // the number of the LED pin

    // variables will change:
    int buttonState = 0;         // variable for reading the switch status
    int brightness = 0;
    int fadeAmount = 5;

    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }

    void loop(){
      // read the state of the switch value:
      buttonState = digitalRead(buttonPin);

      // check if the switch is ON.
      // if it is, the buttonState is LOW:
      if (buttonState == LOW) {
        // fade LED on:
        analogWrite(ledPin, brightness);
        if (brightness < 255) {
          brightness = brightness + fadeAmount;
        }
      }
      else {
        // fade LED off:
        analogWrite(ledPin, brightness);
        if (brightness > 0) {
          brightness = brightness - fadeAmount;
        }
      }
      delay(30);
    }

I have a feeling the problem is with the common ground on the MOSFET and the switch. Any solutions/suggestions are appreciated.

title: Connecting a switch and a MOSFET to an Arduino?

Answers: 2

body:
There is no need for the 10KOhm. MOSFETs are voltage controlled devices unlike transistors which need controlled current. I think your problem might be in debouncing of switch. You are probably getting some false positives which might be making your software go awry.
I recommend having a small debouncing routine. For eg - only if you find 3 successive positives will the switch press be termed a true positive or so.

body:
I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/FbvYW.png)

<!-- End schematic -->

How to make the diagram a bit smaller?


body:
I recently purchased a batch of Due boards and find that they are cosmetically different. After attaching the Atmel-ICE and reading the firmware from both processors, I find that the firmware is different. The green masked one had a sticker indicating a new IDE should be downloaded from arduino.

The back of the board shows silkscreen changes to the logo (DUE in an oval rather than rectangle) but both boards say BOARD MODEL DUE R3-E. The traces appear the same, the placement of parts appears the same, and other than different colored headers the parts are similar. The main processor has the same part number, but distinctly different markings. Internally the processors report the same device signature and revision.

What has changed in the firmware? Are there other changes I've missed? Other than needing an even newer IDE are there changes that will affect my sketches?

If I load the older firmware onto the newer Due processors, should it operate the same, allowing use of the old IDE, and in case my sketches do face a problem with the new version?

![enter image description here][1]

![enter image description here][2]

  [1]: https://i.stack.imgur.com/0RZid.jpg
  [2]: https://i.stack.imgur.com/Tla7u.jpg

title: What changed in the new Due?

Answers: 1

body:
The 'new' board with green soldermask and the lighter headers is made by arduino.org.  The old one was probably made by the same company, but prior to the split in the founders.

Right now there is arduino.cc (the original website) and arduino.org (the website set up by the company that split from Arduino).  There is a lot of different perspectives about who really owns `Arduino` and I won't attempt to weigh in here.

The changes in firmware are still unknown.  It's likely that they are simple strings or response changes so the boards can be differentiated in software.  The `new` IDE is in alpha, and is yet another attempt to differentiate between the two Arduino groups.  I haven't attempted to program either with either group's IDE, but if I do I'll update this answer with the results.

At least there's a way to visually identify the difference once received - wish they had given them different part numbers so Digikey wouldn't have sent me a mixture...


body:
I'm starting with Leonardo and I'm a bit confuse about the serial modem function. As you know on boot the Leonardo for the first 8 seconds wait for a program on the USB port and then it goes in serial modem mode while my program runs.

I'm designing a consumer product (open source) and I will like to make some modifications to my board in order to make it more friendly:

1. On boot it has to go into *programming mode* only if a jumper is set. Otherwise it goes directly into *serial modem*.
2. I need to change to *modem name*, instead of:
[![enter image description here][1]][1]
3. Have the operating system pickup the serial modem with no drivers request.

For 1 and 2, is it possible? should I try to modify Caterina or it will be easier to work with [Optiboot][2]? Number 3 works already in linux distributions, but in Windows some pcs ask for drivers are, and even worse, some windows 64bits + usb3 requires some minors hacks to pick up the Leonardo serial drivers, is it possible to improve? Ideally I want the board to be connected to a PC/Mac/Linux and get configured as a serial com with no user intervention.

I think this are questions that every person trying to create a consumer product with Arduino needs to answer before producing the actual product. So, and resources, references and *where to start* guides will help me and other people in the community.

  [1]: https://i.stack.imgur.com/zRSig.png
  [2]: https://github.com/Optiboot/optiboot

title: Is serial modem routine written on the Arduino Leonardo bootloader?

Answers: 0


body:
I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. But even this still doesn't seem to be a good way prevent the noise that is occurring when using my Remote. Is there any way to fix this?
Here is the code from the smoothing project. (Although i feel it's not really necessary to add it here, but here it is anyways.)

My code is using the PPMrcIn library. An int is created and then using if statements I make an object do work. My problem is that i have a very small window for work.

My values are between 50 and 200

Where 140 is the preferred midpoint i'd like to work with.

This is my somewhat cryptic number line.

140 is in the middle. Where my window of stability is between 130 and 150

and values below 100 and above 180 are where the robot does some work.

50 ---x---<100-----130--<140>--150----180>---x---200

      /*

        Smoothing

        Reads repeatedly from an analog input, calculating a running average
        and printing it to the computer.  Keeps ten readings in an array and
        continually averages them.

        The circuit:
          * Analog sensor (potentiometer will do) attached to analog input 0

        Created 22 April 2007
        By David A. Mellis  <dam@mellis.org>
        modified 9 Apr 2012
        by Tom Igoe
        http://www.arduino.cc/en/Tutorial/Smoothing

        This example code is in the public domain.

      */

      // Define the number of samples to keep track of.  The higher the number,
      // the more the readings will be smoothed, but the slower the output will
      // respond to the input.  Using a constant rather than a normal variable lets
      // use this value to determine the size of the readings array.
      const int numReadings = 10;

      int readings[numReadings];      // the readings from the analog input
      int index = 0;                  // the index of the current reading
      int total = 0;                  // the running total
      int average = 0;                // the average

      int inputPin = A0;

      void setup()
      {
        // initialize serial communication with computer:
        Serial.begin(9600);
        // initialize all the readings to 0:
        for (int thisReading = 0; thisReading < numReadings; thisReading++)
          readings[thisReading] = 0;
      }

      void loop() {
        // subtract the last reading:
        total= total - readings[index];
        // read from the sensor:
        readings[index] = analogRead(inputPin);
        // add the reading to the total:
        total= total + readings[index];
        // advance to the next position in the array:
        index = index + 1;

        // if we're at the end of the array...
        if (index >= numReadings)
          // ...wrap around to the beginning:
          index = 0;

        // calculate the average:
        average = total / numReadings;
        // send it to the computer as ASCII digits
        Serial.println(average);
        delay(1);        // delay in between reads for stability
      }

also link to my code in github
https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino

Since this is being asked. Let me clarify on this black voodoo thing called a PPM.

Many RC Transmitters and Receivers provide access to the PPM Stream, this is a single stream of pulses which includes the information for all of the receiver channels in a single connection.
The stream is made up of a series of short pulses, the first pulse is the start marker. The time between the start marker and the start of the next pulse defines the pulse length for channel one. The time to the next pulse defines the pulse length for channel 2 and so on. The end of the pulse stream is marked by a gap know as the frame space. This gap indicates that there are no more channels to receive and the next pulse will be the start of a new frame. Each frame contains the pulse widths for all of your receiver channels.
Note - unlike servo signals, in a PPM Stream it is the gaps between pulses that defines the pulse width for a channel, not the duration of the pulse itself which can be very short.
-http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html

As discussed above. My PPM signal is highly varied. I want to be able to just get a solid 140. However, the signal will jump irratically between 135 and 142 for reasons I do not completely understand. In an attempt to clear this fuzziness I tried to go for smoothing.

title: PPM from remote control is very noisy

Answers: 1

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

First, I want to thank you for making this post. I have a few remote-controlled cars/boats/helicopters, and I've often wondered how the remote control works. :)

---

To answer your question - and because I was too lazy to work out how to connect to an actual controller - I made a "remote simulator" like this:

    // PPM generator

    const byte SIGNAL_PIN = 3;
    const int SIGNAL_COUNT = 6;
    const unsigned long PULSE_WIDTH = 300;  // µs
    const unsigned long BLANK_TIME = 25;    // ms
    const int widths [SIGNAL_COUNT] = { 600, 2000, 1000, 1500, 2200, 2400 };

    void setup ()
      {
      pinMode (SIGNAL_PIN, OUTPUT);
      }  // end of setup

    void loop ()
      {
      delay (BLANK_TIME);
      digitalWrite (SIGNAL_PIN, HIGH);  // start
      delayMicroseconds (PULSE_WIDTH);
      digitalWrite (SIGNAL_PIN, LOW);   // end of start pulse

      for (byte i = 0; i < SIGNAL_COUNT; i++)
        {
        delayMicroseconds (widths [i] - PULSE_WIDTH);
        digitalWrite (SIGNAL_PIN, HIGH);  // start of pulse
        delayMicroseconds (PULSE_WIDTH);
        digitalWrite (SIGNAL_PIN, LOW);   // end of pulse
        }  // end of for loop

      delay (1000);
      }  // end of loop

This is intended to generate a series of pulses (six in this case) which might be generated by some fancy <s>toy</s> fun device.

---

Output from it:

[![PPM generator][1]][1]

As you can see from the cursor, it is doing what it is bid. The pulse width shown by the scope cursor is indeed 2000 µs, as per the table of widths.

*Note*: Output on pin 3 on the Uno.

---

Now we need a decoder. So let's use interrupts:

    const byte SIGNAL_PIN = 2;
    const int SIGNAL_COUNT = 6;

    volatile unsigned long widths [SIGNAL_COUNT + 1];
    volatile byte count;

    unsigned long lastPulse;

    // ISR
    void gotPulse ()
      {
      unsigned long now = micros ();

      // a long gap means we start again
      if ((now - lastPulse) >= 25000)
        count = 0;

      lastPulse = now;
      if (count >= (SIGNAL_COUNT + 1))
        return;

      widths [count++] = now;
      }

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      attachInterrupt (0, gotPulse, RISING);
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      }  // end of setup

    void loop ()
      {
      if (count >= SIGNAL_COUNT)
        {
        Serial.println (F("Got sequence."));
        for (int i = 1; i < SIGNAL_COUNT + 1; i++)
          {
          Serial.print ("Channel ");
          Serial.print (i);
          Serial.print (" = ");
          Serial.println (widths [i] - widths [i - 1]);
          }
        count = 0;
        }

      }  // end of loop

This uses an interrupt (on pin 2 on the Uno) on the rising edge to detect the start of the pulses. It stores them, and then works out their widths later.

---

Results?

    Got sequence.
    Channel 1 = 612
    Channel 2 = 2020
    Channel 3 = 1016
    Channel 4 = 1512
    Channel 5 = 2220
    Channel 6 = 2428
    Got sequence.
    Channel 1 = 612
    Channel 2 = 2020
    Channel 3 = 1016
    Channel 4 = 1512
    Channel 5 = 2220
    Channel 6 = 2424
    Got sequence.
    Channel 1 = 616
    Channel 2 = 2020
    Channel 3 = 1012
    Channel 4 = 1516
    Channel 5 = 2220
    Channel 6 = 2424
    Got sequence.
    Channel 1 = 616
    Channel 2 = 2020
    Channel 3 = 1012
    Channel 4 = 1516
    Channel 5 = 2216
    Channel 6 = 2432

Highly consistent results, with a small error factor of around 16 µs compared to `600, 2000, 1000, 1500, 2200, 2400`

---

In case it isn't clear, this test required two Unos. One to generate the pulses and a second one to decode them:

[![PPM Test setup][2]][2]

The one with the USB cable is the decoder, which writes to the serial port. The other one is powered by 5V/Gnd from the first one, and the white wire is the data with the pulses.

  [1]: https://i.stack.imgur.com/XBAjj.png
  [2]: https://i.stack.imgur.com/DxH0K.jpg


body:
How do I split a string into two based on it's length to display on a 2x16 LCD?

I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?

Thanks

title: Split a string as 2x16 for LCD

Answers: 2

body: That's what <a href="https://www.arduino.cc/en/Reference/StringSubstring">`String::substring()`</a> is for. Simply take the first 16 characters and the characters from 16 to 32, and output them.

body:
String::Substring does take a start and an end value. So you can do something like this:

    String s1 = longtext.substring(0,15);
    String s2 = longtext.substring(16,31);


body: How to make arduino sense mobile signal coming into a room and display the calling number on an LCD screen

title: How to sense mobile signal coming to a room using arduino uno

Answers: 1

body:
You can't.

Mobile phone signals don't respect artificial boundaries like a room's walls.  You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".

And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".

What you *could* do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.


body:
I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.

I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen).
I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.

Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?

Thanks!

title: Arduino, lcd 16x2 and UTP cable shows gibberish text?

Answers: 1

body:
Is the cable shielded?
Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?

What is the impedance of your total length of cable?

These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test)
a hardware limitation (Too much resistance for accurate data travel)
Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.


body: If I have a basic electronic board with some LEDs and sound fx and I want to program them (I'm a beginner, learning about arduino), does the arduino board always have to be connected to the actual electronic board I'm running or is there a way to "upload" the programming to the circuit board?

title: Does the arduino board have to be always physically connected to the electronic device you are running?

Answers: 3

body:
If the "basic electronic board" is programmable, then yes, you can upload a program to it.

In general, though, "some LEDs" and similar devices are not programmable, and without something to *drive* them (i.e., the Arduino) they won't do anything at all.  The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing.  It is the *brain* of the operation.  Remove the brain from someone and you'll find their body no longer functions.

body: And Arduino UNO is basically a ATMega328 chip (with some extras) on a circuit board. So if you add an ATMega328 to your own circuitboard, you don't need an Arduino Uno.

body:
If the question is "Can I program the Arduino without anything else connected to it?", then yes, you can program it with out the sound and light board connected. But the program will start running shortly after the upload finishes.

If some devices were connected to it and some were not, it's possible the program won't function properly at that point (and obviously the not-connected devices won't function at all!), so you should make sure the Arduino can't or won't try to do anything to the few connected ones that might be harmful when some others are not connected, in case that is possible (this would be an unusual, but plausible, situation).


body:
I am working on a project with an Arduino Nano that includes a keypad, screen, and the NRF4001 transceiver. The keypad requires 7 digital pins to operate, the wireless transceiver uses pins D9 - D13 with the RF24 library I am using. Now, that leaves me with 1 Digital Pin left for a screen unless there is an I2C screen I could use.

That would be easy enough to find except that I have some limitations. If at all possible I would like the screen to be under 5 dollars and about the size of a Nokia 5110. The Nokia uses to many pins and does not tolerate 5v logic levels I've heard. An OLED 0.96 inch is only a 4 bucks and is I2C, but it is too small. I could make a board for the keypad that used different values of resistors and one analog pin to detect different buttons but would rather not go that route if there is any easier way to get around this.

Are there any options out there that would suffice my pin, cost and size conditions or am I being too picky?

title: Cheap LCD with Few Pins

Answers: 1

body:
You can use a single analog pin to read an entire keypad.

First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.

A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.

Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F->G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.

You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: http://www.calculator.net/resistor-calculator.html and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.

DO NOT use any resistors under 1kOhm.

Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out ` * (5.0 / 1023.0)` , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.

Then find the numbers exactly in between.

For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.


body:
I messed around with the [MAX7456][1] chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.

The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like [this][2])

  [1]: https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf
  [2]: http://www.ebay.co.uk/itm/On-Screen-Ardupilot-Mega-Display-MinimOSD-Rev-1-1-OSD-diy-drones-APM2-2-5-2-6-/321843140980

title: How to do a software reset on MAX7456?

Answers: 1

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

The datasheet says:

> The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...

Thus, you need to write address / data after selecting the chip.

    digitalWrite (SS, LOW);  // select the chip
    SPI.transfer (0x00);     // select address 0x00 (Video Mode 0)
    SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
    digitalWrite (SS, HIGH); // done

According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.

      byte result;

      do
        {
        digitalWrite (SS, LOW);      // select the chip
        SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
        result = SPI.transfer (0);   // read it
        digitalWrite (SS, HIGH);     // done
        } while (result & bit (1));  // loop while not reset yet

---

> Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?

I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.

      // reset chip
      digitalWrite (SS, LOW);  // select the chip
      SPI.transfer (0x00);     // select address 0x00 (Video Mode 0) - write mode
      SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
      digitalWrite (SS, HIGH); // done

      byte result;
      unsigned int counter = 0;

      // wait for it to become ready, or time-out
      do
        {
        digitalWrite (SS, LOW);      // select the chip
        SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
        result = SPI.transfer (0);   // read it
        digitalWrite (SS, HIGH);     // done
        if ((result & bit (1)) == 0)
          counter++;     // count times not ready
        } while ((result & bit (1)) && (counter < 1000) );  // loop while not reset yet

      if (counter == 0 || counter >= 1000)
        {
        // chip does not seem to be responding
        }
      else
        {
        // all OK!
        }


body:
I just got my Arduino Pro Mini and GDEW0154T1 ePaper display ([GDEW0154T1 display)][1] and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.

I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?

Thank you for any advice!

  [1]: http://www.good-display.com/products_detail/&productId=305.html

title: Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display

Answers: 1

body:
You need to build a special driver board.  Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.

The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).

There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.

Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task.  You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it *is* the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.


body:
I need help with wiring this current sensor so that I can read the output voltage as an analogue input. - http://www.tamuracorp.com/clientuploads/pdfs/engineeringdocs/L03SXXXD15.pdf

This is how I have it wired right now -
1 - +15v
2 - 15v ground
3 - output to arduino
4 - arduino ground

This seemed simple but reviewing the wiring diagram again I have a hunch that this is not at all how I should be wiring this up.

Thanks

title: Hall Effect Current Sensor Wiring

Answers: 2

body:
Looking at the datasheet the output is +/- 4 volts, so this is not suitable to connect directly to the Arduino, because the input pin will not tolerate -4 V.

I am no Hall Effect sensor expert, but a quick search on Google showed another potential problem: If you are planning to measure AC current, and you try to sample the output on the Arduino, the reading will average out to zero (half of the time positive, half of the time negative).

What may help - and this is a bit of a guess - is to put a diode in series with the sensor output, oriented so that you only get the positive pulses. That is, the anode connected to the Hall Effect sensor, and the cathode (with the black line) on the Arduino side.

Then you probably want to smooth the voltage so you can read the average voltage with the ADC converter, rather than what it is at a particular millisecond. A low-pass filter will take an average, which you can then read with `analogRead`.

Something like this:

[![Hall effect sensor wiring][1]][1]

---

I made up that circuit driven by a signal generator (8 V peak to peak, i.e. +/- 4 V) and found a 400 mV drop over the diode using a 1N4148 normal diode, and a 160 mV drop using a BAT85 Schottky diode.

With a 3 V peak-to-peak signal the voltage drop with the Schottky diode reduced to 120 mV, so it wasn't totally linear.

---

As Majenko pointed out, there is a voltage drop over the diode. You can make a [Precision Rectifier](https://en.wikipedia.org/wiki/Precision_rectifier) out of an op-amp and a few other parts, like this:

[![Precision Rectifier][2]][2]

This avoids the problem of the voltage drop (put this in place of the diode in the earlier circuit).

If the signal is AC then the smoothing circuit I described above will only give you an average voltage, not a peak one. You may want to sample rapidly in order to find the peak values.

  [1]: https://i.stack.imgur.com/3P4pr.png
  [2]: https://i.stack.imgur.com/dn3JC.png

body:
To read the sensor properly you have to convert the output signal into something the Arduino can work with.

At full current the output will swing between +4V and -4V, and over-current will cause that to be nearer +6V to -6V.  The frequency of that swing will be the frequency of the input voltage - so typically 50 or 60Hz.

The Arduino can only read between 0V and 5V, so you will need to convert the provided voltage to fit.

You need to first reduce the voltage by about a half, so it fits into +/- 2V, and then you need to add a 2.5V offset voltage to it so that it swings between 0.5V and 4.5V.

Once you have done that you then need to sample the incoming signal fast enough that you can get the peak values, from which you can then calculate the incoming current.

Often for this kind of thing you would use a simple voltage divider with an offset voltage applied to it, but the output impedance of the sensor (set by RL) is 10KΩ which is around the upper limit for the input impedance of the Arduino's input.  A voltage divider that wouldn't adversely affect the output accuracy would be using resistors in the order of 1MΩ, which would be way too high for the ADC on the Arduino to be able to sample accurately.

So you need to buffer the signal with a high impedance buffer.  That can be achieved most simply with an inverting op-amp circuit with a gain of 0.5.  You want a rail-to-rail op-amp which is capable of running from a single supply voltage.

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

In this circuit the output current is converted into a voltage by the 10KΩ resistor RL.  It is then *AC coupled* to the rest of the circuit through C1 which has to be high enough in value as to not reject the frequency you are working with (it acts like a high-pass filter).  R1 and R2 set the gain of 50/100, or 1/2, so the voltage is halved.  R3 and R4 form a voltage divider to provide a VCC/2 offset voltage into the non-inverting input of the op-amp.  This is known as the *virtual ground* voltage and is the voltage the output of the op-amp will swing around.

The result is the input voltage inverted, halved and off-set by 2.5V, which can be read directly by the Arduino's ADC.

Note the magic word *inverted* there, though.  The values you read will be upside down.  Anything read above 512 from the ADC will equate to a negative voltage.  Anything read below 512 will be a positive voltage.  So it is necessary to first "invert" the reading, which can simply be done by subtracting it from 1023.

Then it's just a matter of sampling often enough and recording the peak (and negative peak) values over a short period.  The faster you can sample the better your results will be.

From those peak values you can then do all sorts of calculations and things.  You can use them "as is" to directly give you the "peak-to-peak" current, or calculate the RMS voltage to then give you the RMS current.

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


body:
I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code

    int a = 2;
    int b = 3;
    int c = 4;
    int d = 5;
    int e = 6;
    int f = 7;
    int g = 8;

    void setup()
    {
       for(int i = 2; i++ ; i<9)
       {
          pinMode (i, OUTPUT);
       }
    }
    void _1()
    {
       digitalWrite ( b, HIGH);
       digitalWrite ( f, HIGH);
       delay(1000);
    }
    void _2()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _3()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _4()
    {
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( b, HIGH);
       delay(1000);
    }
    void _5()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _6()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       digitalWrite ( d, HIGH);
       delay(1000);
    }
    void _7()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( f, HIGH);
       delay(1000);
    }
    void _8()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void _9()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( d, HIGH);
       digitalWrite ( f, HIGH);
       delay(1000);
    }
    void _0()
    {
       digitalWrite ( a, HIGH);
       digitalWrite ( b, HIGH);
       digitalWrite ( c, HIGH);
       digitalWrite ( e, HIGH);
       digitalWrite ( f, HIGH);
       digitalWrite ( g, HIGH);
       delay(1000);
    }
    void wait()
    {
       digitalWrite ( a, LOW);
       digitalWrite ( b, LOW);
       digitalWrite ( c, LOW);
       digitalWrite ( d, LOW);
       digitalWrite ( e, LOW);
       digitalWrite ( f, LOW);
       digitalWrite ( g, LOW);
       delay(100);
    }
    void loop()
    {
       _0();
       wait();
       _1();
       wait();
       _2();
       wait();
       _3();
       wait();
       _4();
       wait();
       _5();
       wait();
       _6();
       wait();
       _7();
       wait();
       _8();
       wait();
       _9();
       wait();
    }

The problem is that it stays at _0 and then never changes. Any suggestions?

title: Arduino code of making a LED digit display not functioning properly

Answers: 1

body:
The `for` loop in your `setup()` function isn't quite right. The condition (`i<9`) and the iterator (`i++`) need to be the other way round, like this:

    for (int i = 2; i<9; i++)
    {
      pinMode (i, OUTPUT);
    }


body:
I'm trying to build a system where if a cable gets disconnected from a pin (any pin), an action is executed.

I am wondering how to set this up. Can I simply wire the 5V to a pin and read its status or will this mess up the Arduino? Should I use any resistors? How should I connect this to the GND?

Please bear in mind that I'm pretty new to all of this.

title: How can I detect a disconnected pin?

Answers: 3

body:
You can connect all pins through a 1M resistor to a rail. Once in a while you set all your outputs to inputs and toggle the rail HIGH and LOW, if the inputs are HIGH and LOW in the sequence you toggled the rail, there is no wire. The same question was asked at Arduino Forums so read [this][1] thread.

This question's answer was provided by johnwasser@forum.arduino.cc.

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

body:
The way to do this, since there is no digital value in between HIGH and LOW, is to actively create a signal on the pin you can recognise.  Note that if the signal coming in to the pin is a datastream (a sequence of HIGH and LOW) that runs all the time this may not work reliably, but it's good for things like buttons and other simple sensors.

Any signal on a wire has a *drive strength*.  This is basically how powerful the signal is and how good it is at overriding other things happening on the same wire.  It is closely related to the output impedance of the source (what is sending the signal).  For things like buttons and switches that is basically the value of the pullup resistor used.

To actively sense if a pin is disconnected or not you need to temporarily connect it to a known signal level *at the same time* as it's connected to the wire (or not connected if it happens to be not connected).  This known signal level has to be of a *weaker* drive than the source signal by several orders of magnitude.  This ensures that if you try superimposing your test signal over the incoming signal the incoming signal swamps out the test signal and you don't see it at all.  For instance, if your source has 10KΩ impedance (say a button with 10KΩ pullup resistor) then a test signal with source impedance of 1MΩ would be suitable.

Each pin to be tested can be connected to its own 1MΩ (in this example) resistor, and those resistors are all connected to the same extra IO pin:

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

In this example pin D2 is the test pin, and pins D4-D7 are your inputs.

So under normal circumstances pin D2 is set as an input and completely ignored.  When you come to test the pins, though, you set it as an output.

You then set D2 to be HIGH and read each of D4 through D7.  Any that read as HIGH are candidates for being not connected.

You then set D2 to be LOW and read the pins that read HIGH before.  Any that now read as LOW are disconnected.

You then set D2 back to being an input again so it doesn't interfere with normal operations.

----

If you just want to know if current is flowing in a wire you can use what is called a *shunt resistor*.  This is a small resistor (maybe 1Ω) that is placed in-line with the wire and you measure the voltage (using Arduino analog inputs) at both sides of the resistor.  The voltage dropped across the resistor is directly proportional to the current flowing through it thanks to Ohm's Law:

> I=V/R

For instance:

[![enter image description here][2]][2]

If the voltage read by A1 should be 5V (the voltage the wire is connected to) and the voltage read by A0 should be 4.93V, the voltage *dropped* by the resistor would be 5-4.93 = 0.07v.  With the 1Ω resistor the current would be 0.07/1 = 0.07A, or 70mA.

With the wire at OUT disconnected there will be zero current flowing since there is no circuit.  So re-arranging the formula above we can prove that we can tell it's disconnected.

If I=V/R then V = RI.  Therefore V = 1Ω × 0A = 0V.  So the voltage dropped across the resistor would be 0V, so A0 and A1 would be equal (discounting any noise). A0 and A1 would both read 5V.  Similarly, if the wire IN was disconnected instead then A0 and A1 would both read 0V.

For sensing higher currents you use a smaller resistance, and for sensing smaller currents you use a larger resistance - this allows for a voltage drop to be generated that is within a suitable range for the sensitivity of the ADC doing the reading.  For the Arduino that's a 10-bit ADC, so it can sense (with a 5V VREF) 5/1024=4.882813mV per LSB.

Note that if you are working with voltages above that at which the Arduino operates you will need to separate or otherwise scale those voltages.  There are special devices designed especially for this task called *high side current shunt amplifiers*.  They also allow you to use a smaller resistance than you would otherwise need which is less intrusive to your circuit (less voltage drop).

  [1]: https://i.stack.imgur.com/soUQi.png
  [2]: https://i.stack.imgur.com/MKALi.png

body:
Alternatively, if this is a digital input, you can just use a pull-up or pull-down resistor to give the input pin a default value. Let's say you use a pull-up resistor to make the default high. Then you connect a low cable to this input so that the input reads low. Now, if the cable goes high or if it is disconnected, you get a high value in the input pin.

I know this was not quite what you were asking but maybe such a solution could help with your original problem. In my case, I have a flame detection module that gives low output by default and turns high when there is a flame. I don't want to miss the flame because of my cable disconnecting, so I use a pull-up resistor that will make the input high not only when there is a flame, but also when there is a disconnection. This way I make sure that I don't miss a fire because of the sensor cable disconnecting.


body: I have one Arduino uno, and one atmega8a 1337 ic. Can i replace the Arduino uno ic with 1337 to program the 1337 one?

title: Replacing Atmega8a pu 1440 arduino Ic with 1337

Answers: 1

body: If you have a bootloader installed on the 8A then yes, you can.  The two chips are pin and electrically compatible.


body:
I am Trying to make a MicroSD .wav file player using Arduino Uno. I have ordered a MicroSD Card Module from ebay today.

Product Link : http://www.ebay.in/itm/Micro-SD-Card-Module-SD-Storage-Board-TF-Card-Memory-Shield-SPI-For-Arduino-/161696480012?

As You can See in the Product Image, there is **not mentioned on the PCB that which Pin Is ground** or VCC Or any other SPI pin.
1. How will I identify the correct pins of the MicroSD Module ?
2. How can I connect a speaker to arduino to play .wav files. Is Amplifier neccessary? I am weak when it comes to electronics.

I have listened that when I connect a Capacitor in series with speaker, it will boost the output volume. There will not be music but only voice recordings in .wav files. I want to listen it clearly only.

title: Help Connecting MicroSD Module with Arduino Uno

Answers: 2

body:
OMG, what a vile listing!

Anyway, I think you'll probably find they are in the order listed in the description when the connector is facing south. It's probably printed on the rear of the board which they don't show.

That is, from left to right, GND, VCC, MISO, MOSI, SCK, CS.

As for connecting a speaker, that depends if you want low quality (PWM) audio, or high quality (DAC) audio.  The latter requires the addition of an audio shield, most of which have an SD card slot on them already thus alleviating the need for this SD card breakout board.

For the former there is a library and instructions here: http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio

body: I got my MicroSD Module today. The labels were printed At the bottom side. Dont confuse, CLK = SCK. The VCC goes to arduino 5v.


body:
How would i capture the following serial data, and split it into parts?
`<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>`

the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z

What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD.

i.e.
X: 0.000  Y:0.000
Z: 0.000  Idle

I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.

title: How would i capture and split serial data?

Answers: 1

body:
This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.

Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function `strtok()` to split the string up into parts.

So you have the string:

    char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

The function `strtok()` takes, on its first call, the string you want to split and the delimiter that you want to split on.  It returns a pointer to the chunk:

    char *alarm = strtok(string, ",");

`alarm` now contains `<Alarm` and `strtok()` moves its internal pointer to point at the next character, so it sees the string as `MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>`

With the next and subsequent calls to `strtok()` you don't give it the string, or it will reset its internal pointer.  You just pass it `NULL` and it gives you the next block:

    char *mposX = strtok(NULL, ",");
    char *mposY = strtok(NULL, ",");
    char *mposZ = strtok(NULL, ",");
    char *wposX = strtok(NULL, ",");
    char *wposY = strtok(NULL, ",");
    char *wposZ = strtok(NULL, ">");

Note that I changed the delimiter on the last one to `>` so it chops off that extra character that we don't want (and there is no `,` after the last part).

So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:

    *alarm = "<Alarm";
    *mposX = "MPos:0.000";
    *mposY = "0.000";
    *mposZ = "0.000";
    *wposX = "WPos:0.000";
    *wposY = "0.000";
    *wposZ = "0.000";

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:

    alarm += 1;
    mposX += 5;
    wposX += 5;

Our list of pointers now looks like this:

    *alarm = "Alarm";
    *mposX = "0.000";
    *mposY = "0.000";
    *mposZ = "0.000";
    *wposX = "0.000";
    *wposY = "0.000";
    *wposZ = "0.000";

The position variables can now be passed through strtod() to convert them to float values:

    float mx = strtod(mposX, NULL);
    float my = strtod(mposY, NULL);
    float mz = strtod(mposZ, NULL);
    float wx = strtod(wposX, NULL);
    float wy = strtod(wposY, NULL);
    float wz = strtod(wposZ, NULL);

You can do different things depending on the content of the `*alarm` string by using `strcmp()`:

    if (strcmp(alarm, "Busy") == 0) {
        // Something to do when Busy
    }

etc.

Or you can just use it to print the content to the LCD.


body:
I've had an idea for an Arduino project, but I'm not sure where to start. My idea is this: have an Arduino Nano connected to an HC-SR04 ultrasonic sensor, as well as an nRF24L01+ radio. This will be the tripwire module, which will send an alert to a second Arduino (connected to another nRF24L01+ of course) whenever something passes by.

This wouldn't be a stationary unit, it would need to be able to be placed and sense in a variety of locations so the distance would need to be set on power up.

Another issue I'm running into is getting the nRF24L01+ units to work for this purpose. I want to know that the units are wirelessly connected, so having a packet sent every second or so lets the receiving unit know that they're connected, and an additional packet for the tripwire trigger sets off an indicator led.

Is this even possible?

title: Remote Wireless Tripwire

Answers: 1

body:
This sounds very doable. The first point, tuning the distance threshold at startup, could be done with a bank of DIP switches or a potentiometer on an analog pin to set the value. You might include some startup code continuously pings the transducer and displays the result on an LED, until you press a button to tell it "use this".

The second, is a very typical communication technique - sending "hello" packets periodically to confirm that communication is up. In your case, the same packet could carry a hit/no-hit bit within it.


body:
After creating a working prototype with DIP ATMega328 chip/ Arduino UNO I recently got PCBs assembled with SMD components and ATMega328P TQFP soldered onto them, but now I'm having a hard time trying to upload the Arduino program.

**This is the schematic of the PCB with ATMega328P TQFP with ISP headers for programming:**
[![enter image description here][1]][1]

I'm using USBasp programmer with upgraded firmware to upload the code. The chip gets detected and also I can upload sketches to it but the problem is the code runs slow, which I found out is due to the default 8MHz internal clock.(the blink program makes LED blink every 16 seconds instead of 1 second,i.e. with delay(1000))

 Now to switch to the external 16MHz clock which I want to use I found out [here][2] that I have to change the fuse values from the default

> **lfuse: 0x62   hfuse: 0xD9   efuse: 0x3F**

to

> **lfuse: 0xFF   hfuse: 0xDE   efuse: 0x05**

I tried it two times and both the times it screwed up the ATMega328P chip

    C:\Users\p>avrdude -p m328p -c usbasp -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efu
    se:w:0x05:m

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.03s

    avrdude: Device signature = 0x1e950f
    avrdude: reading input file "0xFF"
    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xFF:
    avrdude: load data lfuse data from input file 0xFF:
    avrdude: input file 0xFF contains 1 bytes
    avrdude: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of lfuse verified
    avrdude: reading input file "0xDE"
    avrdude: writing hfuse (1 bytes):

    Writing | ################################################## | 100% 0.03s

    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xDE:
    avrdude: load data hfuse data from input file 0xDE:
    avrdude: input file 0xDE contains 1 bytes
    avrdude: reading on-chip hfuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of hfuse verified
    avrdude: reading input file "0x05"
    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.03s

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0x05:
    avrdude: load data efuse data from input file 0x05:
    avrdude: input file 0x05 contains 1 bytes
    avrdude: reading on-chip efuse data:

    Reading | ################################################## | 100% 0.01s

    avrdude: verifying ...
    avrdude: 1 bytes of efuse verified

    avrdude: safemode: Fuses OK

    avrdude done.  Thank you.

    C:\Users\p>avrdude -p m328p -c usbasp

    avrdude: error: programm enable: target doesn't answer. 1
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

Both of the PCBs are not responding to the USBasp programmer and now I have only got one PCB left. I desperately want to get the final one working.

This is my first time using the SMD ATMega328P chips and any help would be appreciated.

  [1]: https://i.stack.imgur.com/agw3N.png
  [2]: http://forum.arduino.cc/index.php?topic=71580.0

title: Cannot upload sketch to Atmega328p TQFP soldered on PCB

Answers: 1

body:
It looks like the capacitors on your crystal are considerably bigger than they should be.

You are switching the clock to the external crystal, and because you have such massive capacitors on it it's failing to oscillate.  Without that oscillation the chip can't run, and so it can't respond to the programming.

The crystal capacitors should be roughly 2x the "load capacitance" of the crystal you are using.

> CX1 = CX2 = 2(CL - CSTRAY)


body:
I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.

I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds.

Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?

title: Handling serial streams biggers than the available ram

Answers: 1

body:
You can parse indefinitely large amounts of data with a state machine parser.

General description: [State machines](http://www.gammon.com.au/statemachine)

As an example, I wrote recently an [HTTP server](http://www.gammon.com.au/forum/?id=12942) which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.

You need enough RAM for **one** item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

---

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.


body:
I, once again have difficulties including libraries from code files other than my .ino file.

I have several .cpp and .h files in my project to keep it sorted and clean.
However one of my header files starting like this:

    #ifndef DPLANDEF
    #define DPLANDEF
    #include <Arduino.h>
    #include <EEPROM.h>
    #include "syssettings.h"

yields the following errors:

> In file included from
> /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.cpp:2:0:
> /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.h:5:20:
> fatal error: EEPROM.h: No such file or directory  #include <EEPROM.h>
>                     ^ compilation terminated. Fehler beim Kompilieren.

EEPROM.h should be known to the IDE, because I can find it in the libraries menu, too. If it was a custom library, I might have botched something during installation, but this is a standard library. It should work out of the box. What's the problem here?

title: Including libraries from header files sometimes doesn't work

Answers: 1

body:
The problem here is that it's a header file.  The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.

In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.