body:
I have a few Arduino sketches that take 70-90% of dynamic memory. It seems that over 70%, the compiler gives the warning:

    Low memory available, stability problems may occur.

but otherwise I wasn't noticing any problems.

Then I uploaded a sketch that took 89%, which logged String data to the serial port, and found that only newlines were being written out. When I commented out some global variables so that dynamic memory usage got to 88%, then it started printing out the data.

Is there any hard/fast rule on when this problem occurs? I was surprised by this problem, because the global variables I removed weren't even being used in the sketch, so I had thought the compiler would have removed or optimized them so they didn't waste any space. Are there any ways to automatically improve compilation efficiency and detect wasteful variables?

title: At what level does low dynamic memory effect performance?

Answers: 2

body:
The problems occur when you run out of memory. That all depends on what you are doing with the memory that is available.

String objects are not good and are wasteful of memory. They really should be avoided, since they use dynamic memory allocation, which uses the "spare" memory that is what's left over from what the compiler says is used.

There is no rule, other than "don't run out of memory", and tracking dynamic usage can be very hard, so try to avoid using it if you can.

body:
The typical build memory statistics is:

    Global variables use XXX bytes (X%) of dynamic memory,
    leaving YYY bytes for local variables.
    Maximum is ZZZ bytes.

What is all this about? First, the maximum number of bytes SRAM depends on the MCU. Arduino Uno is ATmega328 based and has 2K byte SRAM. Arduino Mega2560 has 8K byte. "Dynamic memory" in the print out is SRAM. It is not the heap (malloc/free). To avoid confusion I will use "data memory" below.

The compiler allocates memory for all global variable (objects, struct, etc). It also allocates memory for literal strings (character vectors). These are copied from program memory to data memory at startup. All static variables in functions are also allocated. The sum of all these allocations are the "Global variables".

To execute the sketch data memory is used for the stack. It contains the function parameters, local variables in called functions (that are not allocated to registers), saved registers such as return address to the caller, etc. The size of the frame is known by the compiler and may be found in the assembly listing of a sketch. The maximum stack size required is tricky to calculate as it is the call chain with the largest frame size sum. This is not necessarily the deepest call chain. Also the compiler does to a fair amount of inlining.

The heap (malloc/free) is used by classes such as String. The heap starts directly after the global variables in data memory and grows towards the stack. The heap is blocks of memory allocated and deallocated during the execution of the sketch. This behavior may give heap fragmentation.

Interrupt Service Routines (ISR) need to be able to execute "on top of" any function call. The ISRs are typically called on hardware events such as USART data received. The compiler has to generate code that stores the machine state on stack to execute the ISR. Depending on how many registers the ISR needs more or less of the machine state (registers) need to be stored. The worst case is all 32 registers.

The warning at 30% of SRAM is at approx. 600 bytes left (Arduino Uno, 2K byte). That has to cover the stack and possible heap usage together with ISRs. With a stack heap limit of 32-128 byte, ISR frame of 32-64 byte, that actually leaves worst case approx. 400 bytes for local variables in functions and possible usage of the heap (such as String).

Cheers!


body:
I'm trying to connect Maltab and Arduino by this code:

    arduino=serial('COM7','BaudRate',9600);
    fopen(arduino);

But I get this message:

> Open failed: Port: COM7 is not available. No ports are available. Use
> INSTRFIND to determine if other instrument objects are connected to
> the requested device.

What might be a proper reason?

I have another question which is; How can I save a text file `(.txt)` from Matlab to Arduino SD card .. ? Wether opening a `.txt` file in arduino or saving it from Matlab directly to Arduino SD card.

title: Connection between Matlab and Arduino

Answers: 0


body:
I am attempting to receive GPS data from a GPS SD Shield V2-B purchased from maplin. I have attempted the very simple sketch they provide on their website linksprite.com.
I have also tried following a tutorial found here: http://tronixstuff.com/2014/01/15/tutorial-arduino-mediatek-3329-gps/.
This is the code i am using:

        // Example 19.1

        #include <SoftwareSerial.h>
        SoftwareSerial GPS(2,3); // configure software serial port -

        void setup()
        {
          GPS.begin(9600);
          Serial.begin(9600);
          pinMode(13,OUTPUT);
        }
        void loop()
        {
          byte a;
            if (GPS.available() > 0 )
          {
            a = GPS.read(); // get the byte of data from the GPS
            Serial.write(a);
            digitalWrite(13,HIGH);
            delay(1000);
            digitalWrite(13,LOW);
            delay(1000);
          }
        }

I am using an Arduino 101. The jumpers on the GPS shield are set up as follows:[![enter image description here][1]][1]

I have attempted using both power simply from my Mac and an external 9V battery connected to the Arduino.
The 'blink' has been added the sketch to test whether data was being received but there was a problem with the serial monitor. This is not the case because the blink did not occur. It however did occur when moved outside of the if statement as you would expect.
Any help or suggestions would be much appreciated.

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

title: Cannot receive data from GPS SD Shield V2-B

Answers: 1

body:
You need to set the jumps as per the instructions that came with the shield ...
PAGE4 : short jumpers TX and MRX .... and RX and MTX


body:
I have an arduino micro and several clone "pro micro"'s both of which are based on the 32u4, i'm trying to make my project have a debug mode which is only active when the serial port is open, the documentation states that using:

    if (Serial)

on these boards should only return true if the port is open (on uart based connections it always returns true), i wrote my sketch to take advantage of that but it didn't seem to be working properly, so i stripped back to basics and wrote this sketch:

    void setup() {
      // put your setup code here, to run once:
     pinMode(2, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
     if (Serial){
      digitalWrite(2, HIGH);
     }
     else{
      digitalWrite(2, LOW);
     }
    }

I connected an LED to pin 2 and then tested it by connecting and disconnecting the arduino from the PC, and opening and closing the com port.

after freshly connecting the arduino to the PC the LED is off, when i open a connection to the virtual com port the LED turns on.
however i would expect the LED to go out once the port is closed, but it remains on.

My questions are:
1) have i got an out of date bootloader?
2) if so how do i check?
3) is this intended behavior and if so why?
4) is this a bug in the arduino bootloader or libraries?
5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Edit:
should have mentioned i'm seeing this behavior with or without a call to `Serial.begin`

title: if(Serial) not working correctly on micro or pro micro

Answers: 2

body:
> 1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

> 2) if so how do i check?

See above.

> 3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

> 4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere.  See below.

> 5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.

The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not.  That functionality was just never designed into the protocol.

However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.

The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.

Now comes the tricky part:  You have little or no control over when those signals are asserted or not.  There are three separate factors that decide what happens:

1. The software being run can manually control the signals.  The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
2. The drivers on the computer can decide to automatically control the signals when the port is opened or closed
3. The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.

So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.

body:
I am experiencing the same problem. My environment is Windows 10 on the host side and Arduino 1.6.7 with a genuine Arduino Micro board.

In the OP's sketch, after compiling and uploading, the light does not go on until you open the serial monitor. This is as expected and shows that the Arduino side has some way of knowing that the serial monitor has started.

However if you close the serial monitor, the light stays on. It also stays on if you unplug the USB cable. It goes off when you plug the cable back in and goes back on when you restart the serial monitor.

With some further experimentation and poking around the code, I found that _usbLineInfo.lineState > 0 and thus Serial returns True if either DTR or RTS from the host is nonzero. DTR goes to 0 when the serial monitor is closed but RTS stays HIGH so Serial stays True.

The fix is to use the (undocumented) method Serial.dtr(). This is True only if the serial monitor is running.

[edit] If your system has external power so that it should keep working with the USB cable unplugged, testing Serial.dtr() works as long as you you always close the serial monitor before unplugging the USB cable. However it will remain True if the cable is unplugged before closing the serial monitor.

To detect the cable being unplugged, add the line

`USBCON |= 1<<OTGPADE;`

to setup(). This enables detection of an unplugged USB cable. Then in your loop

`(USBSTA & (1<<VBUS))`

will be True if the USB cable is plugged in and has power.


body:
I'm a member of a [Formula SAE][1] team and we use the Performance Electronics ECU which uses the CAN protocol with a speed of 250 kbit/s and works fine with our 2D Recording Systems Data logger, but we're trying to build a telemetry system which gathers the same data from the CAN bus using an Arduino Uno and CAN shield provided by SparkFun Electronics.

However the CAN shield we're trying to use has failed to initialise the communication with the bus. Kindly help me out on what can be done or are there any alternatives of communicating using CAN with Arduino?

P.S. The link for the CAN shield: [CAN-Bus Shield Hookup Guide][2]

  [1]: https://en.wikipedia.org/wiki/Formula_SAE
  [2]: https://learn.sparkfun.com/tutorials/can-bus-shield-hookup-guide

title: CAN communication with Arduino

Answers: 2

body:
Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

- pin 3/5 [CAN bus shield schematic][1]
- pin 2/7 (Vector tools for example).

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?

  [1]: https://www.sparkfun.com/datasheets/DevTools/Arduino/canbus_shield-v12.pdf

body:
I found this wiki particularly useful: [CAN-Bus Shield Wiki][1]

  [1]: http://www.seeedstudio.com/wiki/CAN-BUS_Shield

And yes, like CQuinson said, you have to pay attention to the pins used. I know Sparkfun is known for having an issue with which pin the CS pin is assigned to (D9 or D10).


body:
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?

This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

[![5V 16MHz with ATmega 328. If I want to power a 3.3V bluetooth chip can I do it with my board? ][1]][1]

Here is the bluetooth chip I am powering:

[![Back Side][2]][2]

  [1]: https://i.stack.imgur.com/meuD5.jpg
  [2]: https://i.stack.imgur.com/1iVWM.jpg

Answers: 1

body:
If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.

If you use external power it provides 5v since that is what the regulator provides.

The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).


body:
I have an Arduino.

I'm not sure if RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

For example, do I treat RX1 and TX0 as RX and TX in the Arduino IDE when coding?

This is the chip I have. On the chip it says "ProMini R160JAC6v" and when I program it, it programs under 5V 16MHz with ATmega 328. Notice RST RX1 and TX0 are on the top left corner.

[![ProMini R160JAC6v 5V 16MHz with ATmega 328][1]][1]

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

title: Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

Answers: 2

body:
It's not RX1 and TX0 but RXI and TXO

That is receive input and transmit output,

Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.

body:
Yes you treat them the same, they are the same pins.

It looks like (in the photo) you're connecting a bluetooth module.
Be careful when uploading your sketch.  If you connect something to TX/RX (pins 0 & 1) it may be necessary to disconnect it for arduino-uploading to work.

You may find it a more convenient solution to declare a SoftwareSerial on different ports and use that for the bluetooth communications.


body: Do any shields (or similar boards) exist to let the Mega 2560 (or Due) output a full 100mA per pin on at least 24 pins, in a digital on/off fashion? I know there is a motor shield, but it looks to have only a handful of outputs. It seems very common that people need to output higher current than the MCU can provide safely (if at all), but there do not appear to be any shields for this. Of course individual transistors are fine for a few outputs, and some chips can do up to 8, but what about the rest of us who want to use all those nice pins on the Mega, Due, or similar but who need more power?

title: Driver shield providing 24+ pins at 100mA (for Mega 2560)

Answers: 2

body: You'll likely have to use an https://www.arduino.cc/en/Main/ArduinoProtoShield with 3+ of those chips you like that do up to 8.

body:
You can:

 * use a driver chip, e.g. ULN2803 which gives you 8 outputs of up to somewhat 500mA from 8 digital pins

 * use a serially addressible power+logic chip, such as TPIC6A595NE which gives you 8 outputs, each can drive 350mA, and has a built-in *short circuit protection*. You can cascade these, 3 chips give 24 outputs, and need only three pins to drive all 24 (or more if you use more chips) outputs.

 * There are 24 output devices, however not in this current range. 24 output devices are usually i2c or spi based led controllers - some of them gives you goodies like rock solid hardware PWM on all 24 ports - but none of them gives you 100mA output.


body:
I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.

Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?

The ideal would be a self-contained library that could be linked to my C/C++ program.

title: Using Arduino IDE as an API

Answers: 2

body:
Have you tried [Arduino C Scaffold project][1]?

> ...the scaffolding lives on Github in the Throw The Switch organization as the Arduino C Scaffold project. This should have everything you need to deploy a C project on an Arduino UNO without the Arduino IDE. If you know your way around Git, you can clone this repository and get to work. If you’d rather not mess with Git right now, you can download the latest revision of the scaffold in a zip file. Once you have the scaffold, take a look at the README. This will walk you through getting the AVR toolchain setup on your environment and describe some of the different ways to use the scaffold.
-- https://spin.atomicobject.com/2011/10/15/taking-the-training-wheels-off-the-arduino/

  [1]: https://github.com/ThrowTheSwitch/arduino_c_scaffold

body:
For compiling and uploading Arduino code, you do not need Java, nor the
Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and
avrdude. With a proper Makefile, your program just needs to

    system("make upload");

C.f. the tutorial [Compiling Arduino sketches using
Makefile](http://hardwarefun.com/tutorials/compiling-arduino-sketches-using-makefile).
On an Ubuntu or other Debian-like OS, you would just
`sudo apt-get install arduino-mk make` to get everything you need installed.


body:
I've got an arduino due and I'm having great difficulty connecting to it. The problem seems to come and go, I was using it just fine only 3 or 4 hours ago but now it just won't connect. I've got the board set to the Arduino Due Native Port and the port set to the /dev/cu.usbmodem1421 (Arduino Due Native Port). Every time I try and upload the sketch however, it gives me this error:

        Arduino: 1.6.6 (Mac OS X), Board: "Arduino Due (Native USB Port)"

    Sketch uses 10,316 bytes (1%) of program storage space. Maximum is 524,288 bytes.
    processing.app.debug.RunnerException
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:130)
     at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
     at processing.app.Sketch.upload(Sketch.java:1178)
     at processing.app.Sketch.exportApplet(Sketch.java:1152)
     at processing.app.Sketch.exportApplet(Sketch.java:1124)
     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2452)
     at java.lang.Thread.run(Thread.java:745)
    Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.usbmodem1421'.
     at processing.app.Serial.touchForCDCReset(Serial.java:87)
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:119)
     ... 6 more
    Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem1421; Method name - openPort(); Exception type - Port not found.
     at jssc.SerialPort.openPort(SerialPort.java:167)
     at processing.app.Serial.touchForCDCReset(Serial.java:81)
     ... 7 more
    Error opening serial port '/dev/cu.usbmodem1421'. (Port not found)

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

title: Arduino Due Port Not Found

Answers: 1

body: Not sure what all that was but a simple restart of my computer seemed to fix it.


body:
I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.

Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.

    #include <stdlib.h>

    class Train {
     public:
      int numOfCars;
      void init();
      void move();
    };

    void Train::init() {
     //code intentionally removed
    }

    void Train::move() {
     //code intentionally removed
    }

    const int trainCount = 2;
    Train train1;
    Train train2;
    Train trains[trainCount] {train1, train2};

    void setup() {
     Serial.begin(9600);
     train1.numOfCars = 5;
     train1.init();

     train2.numOfCars = 5;
     train2.init();
    }

    void loop() {
     for(int n = 0; n < trainCount; n++) {
      Train tr = trains[n];
      Serial.println(tr.numOfCars); //always prints 0
      tr.move();
     }
    }

title: Iterate an Object Array

Answers: 2

body:
You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)

    Train trains[trainCount] = {train1, train2};

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with `new[]` and use them. Like this:

    #include <stdlib.h>

    class Train {
        public:
            int numOfCars;
            void init();
            void move();
    };

    void Train::init() {}
    void Train::move() {}

    const int trainCount = 2;
    Train* trains = new Train[trainCount];

    void setup() {
        // initialize trains
        for (int i = 0; i < trainCount; ++i) {
            trains[i].numOfCars = 5;
            trains[i].init();
        }
        Serial.begin(9600);
    }

    void loop() {
        for(int n = 0; n < trainCount; n++) {
            Serial.println(trains[n].numOfCars); //always prints 0
            trains[n].move();
        }
    }

body:
As uint128\_t has already put it, your problem is that you are creating
an array of copies. You should really avoid copying trains around,
especially if you are going to put a significant amount of data in them.
Instead, just create them once in the array, and then you can either
invoke them as array members directly (e.g. `trains[0].init();`) or use
references.

For example, if you initialize your trains like this:

    const int trainCount = 2;
    Train trains[trainCount];
    Train &train1 = trains[0];
    Train &train2 = trains[1];

Then the "real" trains live in the array, and `train1` and `train2` are
references to them. The rest of your code should work fine unchanged. I
would however suggest to avoid copying the trains in loop:

    void loop() {
        for(int n = 0; n < trainCount; n++) {
            Train &tr = trains[n];        // notice the '&'!
            Serial.println(tr.numOfCars);
            tr.move();
        }
    }


body: I would start to learn the best programming language for embedded systems to control devices. What I have heard about that is Assembly Language. I want to know if there is any better languages to code for embedded systems?

title: What isthe best programming language for embedded systems?

Answers: 1

body:
Before your question gets closed:

**There is no such thing as "the best"**

**Assembly**
Assembly can be a very powerful language. But at the cost of some:

 - Assembly is different per machine. https://cs.stackexchange.com/questions/46935/is-a-universal-assembly-language-for-all-computers-possible
 - Assembly is somewhat less readable as other programming languages in my honest opinion.
 - I personally feel that assembly should only be used for optimalization rather than standard use of code.

**C** C can be as powerful as assembly, only when used correct. In fact, in C (and C++) you can actually inline assembly. https://en.wikipedia.org/wiki/Inline_assembler

**C++** C++ is mostly backwards compatible with C, any C compiler (should?) be able to interpret/compile C code. Which also means you could use inline assembly.

C++ also comes with a lot of usefull tools, though, when used wrongly it can actually backfire you. (Which is with most programming languages that allow a lot, but also give you the possibility to do a lot)

I believe, that C++'s Object Oriented code, with the somewhat backward compatiblity and a little abstraction from the machine (being able to port it to other machines) would be the way to go.
Though, a good C/assembly programmer will out-play an average C++ programmer.

**What about the other languages**

C/C++ could be considered as the standard for embedded devices.

Best thing would be, to ask for individual programming languages, and why one would be better than the other. Or what the differences are.

I havent yet found anything that could "compile" Java for embedded devices. Java typically runs in a "run-time evironment". Which would come down to the fact that it needs an OS or atleast some resources for the code to be run-time interpreted.

C/C++ is also known for being "hard real-time" or atleast deterministic qua timing. Which is probably because of the same reason, not needing another layer and being pre-compiled. (And not having an runtime environment)

By these arguments, I believe C++ or C or Assembly would be the best. Or atleast most widely accepted.
You should check per project, which languages are known by your developers and which other requirements there are (porting to other platforms).
And it's a bit of a taste issue. I think Object Oriented code is very usefull. But some may see it as excessive/annoying.


body:
I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?

To reiterate what is going on here:
I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.

I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.

Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.

Thanks a lot!

title: 3-Way Bluetooth Communication?

Answers: 2

body:
Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.

Hope this gives you a place to start exploring.

body:
Ok

So From Whatever I can Understand you could do this.

1. make one of the boards talk to a master control board.
2. make the control board talk to your phone.

Why don't you change  your approach

1. Make the board A communicate with board B with Bluetooth.
2. Use different pins to setup communication b/w phone and board b.

**Arduino to Arduino Bluetooth**- <http://www.martyncurrey.com/arduino-to-arduino-by-bluetooth/>

**Arduino to phone via Bluetooth**- <http://www.instructables.com/id/Connect-Arduino-Uno-to-Android-via-Bluetooth/>

**PS: - USE DIFFERENT PINS!**


body:
I have a very basic script that is supposed to display something to the serial monitor but no matter what I try the serial monitor won't display anything...I;ve watched about 5 tutorials now and each one has failed to display anything. Any ideas what I'm doing wrong?

Here is my code:

    char rx_byte;

    void setup() {
      Serial.begin(115200);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop() {
      if(Serial.available() > 0){
        rx_byte = Serial.read();
        Serial.print("You typed: ");
        Serial.println(rx_byte);
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
      }
    }

title: Serial Monitor not displaying anything

Answers: 3

body:
Try replacing the line `char rx_byte;` with `int rx_byte=0;`. Use `Serial.println(rx_byte,DEC);`

    int rx_byte=0;

    void setup() {
      Serial.begin(115200);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop() {
      if(Serial.available() > 0){
        rx_byte = Serial.read();
        Serial.print("You typed: ");
        Serial.println(rx_byte,DEC);
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
      }
    }

body:
You have to change the baud rate at the right bottom corner of the serial monitor to 115200 which you have assigned initially.
I have tested it  and
It doesn't matter if its int/char

body:
> Which one are you using?
>
> The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

[![Due ports][1]][1]

---

## Programming port

For programming, the programming port is easiest to use. **And** you can "talk" to the serial port using `Serial`, like this:

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ("Hello, world!");
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

## Native USB port

This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class `SerialUSB` like this:

    void setup ()
      {
      SerialUSB.begin(115200);
      while (!SerialUSB) ; // wait for it to become ready
      SerialUSB.println ("Starting ...");
      }  // end of setup

    unsigned long i;

    void loop ()
      {
      SerialUSB.print ("Hello, world! Count = ");
      SerialUSB.println (++i);
      delay (1000);
      }  // end of loop

It also helps to wait for the serial port to become ready, as I did in `setup`. Otherwise you may miss the first 10 lines or so of serial output.

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


body:
I am using the MATLAB Arduino Support Package to create a setup where I can read force data from a load cell and positional data from an incremental encoder - then plot them on MATLAB. It must be done at the same time in order to produce a material stress-strain curve.

I am thinking of using the [SPI Device functions to do this][1].

Can the data from the load cell and encoder be read synchronously?

  [1]: http://uk.mathworks.com/help/supportpkg/arduinoio/spi-sensors.html

title: MATLAB - Read from 2 SPI inputs synchronously

Answers: 2

body:
 Yes and No.
 Synchronously in development slang means step-by-step execution. Asyncronously mean by some event.

 Arduino has only one core. Even if you use interrupt, Arduino can only execute one command at once.

 Best way for you I guess would be read both on Arduino and combine into single value to read at once. Just reading both with [readDigitalPin][1]  would give huge latency.

  [1]: http://www.mathworks.com/help/supportpkg/arduinoio/ref/readdigitalpin.html

body:
Truly parallel sampling is rarely needed.  Especially if you can separate the triggering (latching) of a reading in the peripheral from the act of subsequently transferring the latched value over SPI, it is likely you can merely trigger both in quick turn and then read them out in slightly slower turn.

But if you *truly* need simultaneous reading, then you will need a workaround.  The ATmega used in classic Arduinos only has one hardware SPI engine.  But you can also implement a software or "bit bang" SPI master using arbitrary digital I/O pins.

Typically this is done with single-bit GPIO operations, but if you place the critical SPI signals for both chips (probably SCLK, the others are usually only sampled at changes in that) on distinct pins of the same GPIO port, then you can use whole port operations at raw AVR level (below the Arduino API level) to drive them at effectively the same time.

To make this work, you would do the following:

1) For each SPI peripheral, figure out exactly at what transition of what part of what access sampling occurs. Make sure to include any internal setup or latency within the chip in the determination.

2) Start the access to whichever peripheral takes longer using port-wide operations which preserve the status of bits not related to this peripheral.

3) Add the access to the peripheral which takes less setup before the sampling instant by starting to include the bits connected to that in the values to be changed in the port wide GPIO operation.

4) Use a similar port-wide operation to trigger the critical sampling operation for both devices at the same time

5) Continue with whatever followup each device needs, and stop updating its pins when no more operations are needed by that device.

Do be aware that some SPI devices, particularly those which are ADC's or having ADC type behavior internally, can be quite sensitive to jitter or timing variation in the clock edges.  You may want to look at using an interrupt or even a hardware counter/time or the SPI peripheral to generate the SCLK edges, and operate the other signals with interrupt driven software slaved to that.

Again, in most cases true parallelism will not be needed.  But if it is needed methods such as this can achieve it at the cost of intricate software.


body:
Currently I'm working on a vending machine project. The vending machine works using 3 button on LCD Keypad Shield DFRobot where 1 button of it assigned as 0.10 cent,the other two 0.20 cent and 0.50 cent respectively. My problem here is how can my system keep track on the balance/coin inserted so that whenever I pressed `button 1 = balance 0.10` then later I pressed `button 2 = balance 0.30` (because 0.20 cent added to the system). Or if you have a better idea for my code, that should be great. This is my code so far:
<!-- language-all: lang-cpp -->

        #include <LiquidCrystal.h>
        LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
        int lcd_key     = 0;
        int adc_key_in  = 0;
        #define btnRIGHT  0
        #define btnUP     1
        #define btnDOWN   2
        #define btnLEFT   3
        #define btnSELECT 4
        #define btnNONE   5
        volatile float balance = 0.00;
        float number1 = 0.10;
        float number2 = 0.20;
        float number3 = 0.50;
        int read_LCD_buttons()
        {
        adc_key_in = analogRead(0);      // read the value from the sensor
        if (adc_key_in > 1000) return btnNONE;
        if (adc_key_in < 50)   return btnRIGHT;
        if (adc_key_in < 195)  return btnUP;
        if (adc_key_in < 380)  return btnDOWN;
        if (adc_key_in < 555)  return btnLEFT;
        if (adc_key_in < 790)  return btnSELECT;
        return btnNONE;
        }

        void setup()
        {
        lcd.begin(16, 2);
        lcd.setCursor(0,0);
        lcd.print("TouchNGo Machine");
        }

        void loop()
        {
        lcd.setCursor(0,1);
        lcd.print("Balance=");
        lcd.setCursor(10,1);
        lcd_key = read_LCD_buttons();
        balance = 0.00 ;

        switch(lcd_key)
        {
        case(btnLEFT):
        {
        balance = balance + number1  ;
        lcd.print("RM");
        lcd.println(balance);
        break;
        }
        case(btnRIGHT):
        {
        balance = balance + number2 ;

        lcd.print("RM");
        lcd.println(balance);
        break;
        }
        case(btnUP):
        {
        balance = balance + number3  ;
        lcd.print("RM");
        lcd.println(balance);
        break;
        }
        }
        }

I would love to hear any comment from you guys.Thanks for the help!

<!-- Arduino -->

title: Arduino Vending Machine problem

Answers: 1

body: Remove "balance = 0.0;" from you main loop.  It's always clearing your balance.


body:
I am trying to get output from a sensor (micro-structure 5852D), but I only get two outputs: 11 and 255 for even applying pressure.

The following is my code, please show me how to over come this problem.

    #include "Wire.h"
    #define addrs 0x5F // I2C bus address

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

    void loop()
    {

       byte lobyte;
       byte hibyte;
       int Press;

       Wire.beginTransmission(addrs);
       Wire.write(1);
       int x = Wire.endTransmission();

       Serial.print("endTransmission: ");
       Serial.println(x, DEC);

       Wire.requestFrom(addrs, 2); // contents of your first two registers
       while(Wire.available() < 2 );          // Check for data from slave
       {
          delay(1000);
          lobyte = Wire.read();       // Read press high byte
          Serial.println(lobyte, DEC);
          hibyte = Wire.read();      // Read press low byte
          Serial.println(hibyte, DEC);

          Press = toPressure(hibyte, lobyte);
          Serial.print("Pressure: ");
          Serial.println(Press);

          delay(1000);
       }

    }

    float toPressure(byte hi, byte lo)
    {
      int a = (hi * 256 + lo) & 0x3FFF;  // see pdf, mask 14 bit

      float rv = (a - 116)* 0.8606; // faster //(t - 1638.0) / 30.84 + 600.0
      return rv;

    }

title: Regarding using I2C with Arduino for Silicon Micro-structure 5852 D 1.5 psi

Answers: 2

body:
The issues in your code:

 - When communicating with the sensor, the sensor expects a **register address** after the device address. Instead of providing it the register address, you sent the *number of bytes you would like to receive*. Good guess, but unfortunately the device was not designed that way.

 - You did not combine the least significant bits and most significant bits of the sensor output correctly. The LSB contains the 6 (**not 8**) least significant bits, while the MSB contains the 6 most significant bits. You first combined them like ` 00MMMMMM00LLLLLL` (where bits marked L come from the LSB and bits marked M come from the MSB), and then masked off the upper two bits as in ` MMMMMM00LLLLLL`. The proper way would have been to only left shift the MSB 6 bits, producing `0000MMMMMMLLLLLL`, and then masking away the upper 4 bits leaving `MMMMMMLLLLLL`.

 - You should avoid 32 bit floating point math on 8-bit microcontrollers at all costs unless you have a huge amount of processor cycles to spare.

In order to read data from the sensor you must first select the register you want to read. To select a register you must first send the device address (95 in decimal, 5F in hexadecimal) with the write request bit set, and then the register address of the byte you want to read.
You can then read the contents of the selected register by first sending the device address, this time with the write request bit clear, and then receiving one byte of data immediately followed by a not acknowledge (NACK) to end the transmission.

The internal registers are organized as in the following table:

![register table](https://i.stack.imgur.com/ZFjGh.png)

Here is my take on the code. It compiles fine, but obviously I cannot test if it actually works as I don't have the sensor. I removed the scaling routine, as it would be wise to first get it working to some level before implementing less essential features.

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

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

    #define SENSOR_I2C_ADDR 95
    #define SENSOR_REG_PRESSURE_LSB 128
    #define SENSOR_REG_PRESSURE_MSB 129

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

    void loop()
    {
        Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the least
        Wire.write(SENSOR_REG_PRESSURE_LSB);            //..significant bits of the pressure measurement are found
        Wire.endTransmission(false);                    //Send a repeated start
        Wire.requestFrom(SENSOR_I2C_ADDR, 1, false);    //Request 1 byte of data, followed by a repeated start

        Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the most
        Wire.write(SENSOR_REG_PRESSURE_MSB);            //..significant bits of the pressure measurement are found
        Wire.endTransmission(false);                    //Send a repeated start
        Wire.requestFrom(SENSOR_I2C_ADDR, 1, true);     //Request 1 byte of data, followed by a stop, ending the transaction.

        uint16_t pressureRaw;

        //There should now be two bytes of data in the receive buffer.
        if(Wire.available() == 2)
        {
            uint8_t lsb = Wire.read();                  //The first byte contains the 6 least significant bits
            uint16_t msb = Wire.read();                 //The second byte contains the 6 most significant bits
            pressureRaw = (msb << 6 | lsb) & 0x0FFF;    //The most significant bits are aligned and combined with the
                                                        //..least significant bits. As the resulting value only has
                                                        //..12 bits of precision the upper 4 bits are masked to zero.

            Serial.print("Raw pressure value: ");
            Serial.println(pressureRaw);
        }
        else                                            //If more or less than 2 bytes have been received something isn't right.
        {
            while(Wire.available())                     //Clear the buffer
                Wire.read();
            Serial.println("I2C transaction error");
        }
        delay(1000);
    }

For some unfathomable reason Silicon Microstructures decided to not include the I2C interface specification in the [datasheet](http://www.si-micro.com/upload/product/pdf/SM5852-003-004-015_Datasheet.pdf) itself. The information is instead found in a separate [application note](http://www.si-micro.com/ci2/userfiles/files/40an0110.02.pdf).

EDIT:
Apparently Wire.flush() does absolutely nothing. Implementation from Wire.cpp:

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

    void TwoWire::flush(void)
    {
        // XXX: to be implemented.
    }

And no, the implementation isn't in the base class either: `virtual void flush() = 0;`. To work around this, I replaced the flush call with a read() loop.

body:
Sorry if I'm late to the party. I solved this years ago. Here's my YT video demo with a google drive link to the code in the video description. It works with the entire SM58XX series of sensors. Just input the parameters for your particular model in the top lines of the code and you'll be off to the races.
https://www.youtube.com/watch?v=Xb2J1puSOwk


body:
I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.

Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking `delay()` function is no longer feasible.

How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?

title: Multiple non-blocking countdown timers?

Answers: 4

body:
>  Would a non-blocking timer solution work?

Yes.  Your "timer" doesn't have to be anything more than a start time from `millis()` and a flag.  Then your loop just compares the start time to the current `millis()` value, and if it's more than the interval you wanted, do the "thing".  In code:

    uint32_t startTime;
    bool waiting = false;
    const uint32_t PUMP_DURATION = 30000UL;

    void setup()
    {
      // start the "timer"
      startTime = millis();
      waiting = true;
    }

    void loop()
    {
      if (waiting && (millis() - startTime >= PUMP_DURATION)) {
        waiting = false;
        // do something now!
        foo();
      }

The flag keeps it from checking when the pump *isn't* running.

If you have multiple timed things, just make another set of variables (i.e., `startTime2` and `waiting2`).  Give 'em better names, eh?

There are also Arduino libraries that encapsulate this common design pattern.  [TimeMark](https://github.com/mikaelpatel/Arduino-Timemark) is one.

Here's some [sample code](http://forum.arduino.cc/index.php?topic=223286.0) on the Arduino forum.

body:
The ["blink-without-delay"-pattern][1] shows how this can be solved but with several time periods and logic this becomes complex. Some abstraction is needed. The [Timemark][2] library provides a solution. Belows is the logic for a single sensor-relay pair with a state trace to serial:

    #include <Timemark.h>

    const uint32_t TURN_OFF_TIMEOUT = 30000L;
    Timemark turnOff(TURN_OFF_TIMEOUT);
    const int sensorPin = 2;
    const int relayPin = 3;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);

      pinMode(sensorPin, INPUT_PULLUP);
      pinMode(relayPin, OUTPUT);
      digitalWrite(relayPin, LOW);

      trace.start();
    }

    void loop()
    {
      if (trace.expired()) {
        Serial.print(millis());
        Serial.print(F(":sensor="));
        Serial.print(digitalRead(sensorPin));
        Serial.print(F(", relay="));
        Serial.println(digitalRead(relayPin));
      }

      if (digitalRead(sensorPin) == LOW) {
        digitalWrite(relayPin, HIGH);
        turnOff.start();
      }
      else if (turnOff.expired()) {
        digitalWrite(relayPin, LOW);
      }
    }

Expanding to three sensor-relays becomes:

    #include <Timemark.h>

    const uint32_t TURN_OFF_TIMEOUT = 30000L;
    const int CONTROL_MAX = 3;
    Timemark turnOff[CONTROL_MAX];
    const int sensorPin[CONTROL_MAX] = { 2, 4, 6 };
    const int relayPin[CONTROL_MAX] = { 3, 5, 7 };

    void setup()
    {
      for (int i = 0; i < CONTROL_MAX; i++) {
        turnOff[i].limitMillis(TURN_OFF_TIMEOUT);
        pinMode(sensorPin[i], INPUT_PULLUP);
        pinMode(relayPin[i], OUTPUT);
        digitalWrite(relayPin[i], LOW);
      }
    }

    void loop()
    {
      for (int i = 0; i < CONTROL_MAX; i++) {
        if (digitalRead(sensorPin[i]) == LOW) {
          digitalWrite(relayPin[i], HIGH);
          turnOff[i].start();
        }
        else if (turnOff[i].expired()) {
          digitalWrite(relayPin[i], LOW);
        }
      }
    }

An alternative solution is to use the [Scheduler][3] library. Below is a rewrite using template functions and a controller task per sensor-relay pair.

    #include <Scheduler.h>

    const uint32_t TURN_OFF_TIMEOUT = 30000L;
    const uint32_t DEBOUNCE_TIMEOUT = 40L;

    template<const int sensorPin, const int relayPin> void setupController()
    {
      pinMode(sensorPin, INPUT_PULLUP);
      pinMode(relayPin, OUTPUT);
      digitalWrite(relayPin, LOW);
    }

    template<const int sensorPin, const int relayPin> void loopController()
    {
      if (digitalRead(sensorPin) == LOW) {
        digitalWrite(relayPin, HIGH);
        while (digitalRead(sensorPin) == LOW) delay(DEBOUNCE_TIMEOUT);
        delay(TURN_OFF_TIMEOUT);
        digitalWrite(relayPin, LOW);
      }
      yield();
    }

    void setup()
    {
      Scheduler.start(setupController<2,3>, loopController<2,3>);
      Scheduler.start(setupController<4,5>, loopController<4,5>);
      Scheduler.start(setupController<6,7>, loopController<6,7>);
    }

    void loop()
    {
      yield();
    }

Please note that the Scheduler requires yield() or delay() to switch between the tasks.

Cheers!

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
  [2]: https://github.com/mikaelpatel/Arduino-Timemark
  [3]: https://github.com/mikaelpatel/Arduino-Scheduler

body:
You might use something like this:

    #define AMOUNT_OF_TIMERS 10
    unsigned int timer[AMOUNT_OF_TIMERS];
    unsigned int sensors[AMOUNT_OF_TIMERS];
    unsigned int pumps[AMOUNT_OF_TIMERS];
    void setup()
    {
      sensors[0] = 1;
      sensors[1] = 2;
      sensors[2...
      ......s[9] = 12;
      pumps[0] = 13;
      pumps[1....
      ....s[9] = 22;
      for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
        PinMode(sensors[i],INPUT);
        PinMode(pumps[i],OUTPUT);
      }
    }

    void loop()
    {
      checkPins();
      decreaseTimers();
      delay(1000);
    }

    void checkPins(){
      for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
        if(digitalRead(sensors[i])
        pump[i] = 30;
      }
    }

    void decreaseTimers(){
      for(unsigned int i = 0; i< AMOUNT_OF_TIMERS; i++){
        if(timer[i]>0)
        timer--;
      }
    }

Personally, I think, handling the timing events in an interrupt is way better. Which might also be for the sensor inputs.

It's not the neatest thing, but it will do.
Using interrupts should make it even more efficient.

- You should use interrupts.
- You might use unsigned chars to preserve extra RAM.
- You should adjust the timers/delay. (set timer to 300, and delay to 100ms) for better result.

body:
Using info from every suggestion, I've so far come up with the following.  I may not need to touch this code again for years and years (or a new house owner may need to look at it should I move out), so I tried to comment it as much as possible.

I don't like that I've repeated so much code in the readFloatSensor functions, but this is where I am so far.  How can I eliminate the code duplication?  I believe I could use arrays and `for` loops but now I've entered another grey area for my knowledge level.

    // PumpController.ino

    // ----CONSTANTS
    // ----Edit these if you need to change the pin layout or pump duration

    #define RELAY_ON 0                     // The pump relays are active-LOW; on when LOW (0)
    #define RELAY_OFF 1                    // and off when HIGH (1). These #defines just help keep track.

    const int pumpRelayPin1 =  12;         // Pin numbers for the pump relays
    const int pumpRelayPin2 =  11;
    const int pumpRelayPin3 =  10;

    const int floatSensorPin1 = 7;         // Pin numbers for the float sensors
    const int floatSensorPin2 = 8;
    const int floatSensorPin3 = 9;

    const int pumpDuration = 500;          // Number of millisecs that the pumps run
                                           // after the float sensors no longer detect water

    // ----VARIABLES

    byte pumpState1 = RELAY_OFF;           // Used to record whether the pumps are on or off
    byte pumpState2 = RELAY_OFF;           // (default to HIGH/OFF)
    byte pumpState3 = RELAY_OFF;

    unsigned long currentMillis = 0;       // Stores the value of millis() in each iteration of loop()

    unsigned long pumpTimerMillis1 = 0;    // Stores the times when the float sensors were last triggered
    unsigned long pumpTimerMillis2 = 0;
    unsigned long pumpTimerMillis3 = 0;

    // ----SETUP (Sets up the pins at startup/reset)

    void setup()
    {

     // Debug
     Serial.begin(9600);
     Serial.println("Starting PumpController.ino");

     // Pump relays are active-LOW. Initialize pump
     // pins HIGH so the relays are inactive at startup/reset
     digitalWrite(pumpRelayPin1, RELAY_OFF);
     digitalWrite(pumpRelayPin2, RELAY_OFF);
     digitalWrite(pumpRelayPin3, RELAY_OFF);

     // THEN set the pins as outputs
     pinMode(pumpRelayPin1, OUTPUT);
     pinMode(pumpRelayPin2, OUTPUT);
     pinMode(pumpRelayPin3, OUTPUT);

     // Set the float sensor pins as inputs and use the built-in pullup resistors
     pinMode(floatSensorPin1, INPUT_PULLUP);
     pinMode(floatSensorPin2, INPUT_PULLUP);
     pinMode(floatSensorPin3, INPUT_PULLUP);

    }

    // ----MAIN LOOP

    void loop()
    {
     // Get the current clock count

     currentMillis = millis() + pumpDuration;       // We add the countdown timer duration to
                                                    // the clock to prevent the pumps from
                                                    // running at boot time, while the clock
                                                    // counter is still below the timer value

     // Call the functions that do the work

     readFloatSensor1();             // check each float sensor and decide whether
     readFloatSensor2();             // to start the pump and countdown timer
     readFloatSensor3();
     triggerPumps();                 // Actually toggles the relay pins based on
    }                                   // the data from the above functions.

    // ----WORKER FUNCTIONS

    void readFloatSensor1()
    {
     if (digitalRead(floatSensorPin1) == LOW)   // If the float sensor is tripped (pulled low)
     {
      pumpState1 = RELAY_ON;                 // then trigger the pump relay pin
      pumpTimerMillis1 = currentMillis;      // and set the pump countdown timer to the current clock time
     }

     if (currentMillis - pumpTimerMillis1 >= pumpDuration)   // If the countdown timer has expired,
     {
      pumpState1 = RELAY_OFF;                             // then turn off the pump relay pin
      pumpTimerMillis1 = 0;                               // and reset the timer to 0 for the next trigger
     }
    }

    //========

    void readFloatSensor2()
    {
     if (digitalRead(floatSensorPin2) == LOW)   // If the float sensor is tripped (pulled low)
     {
      pumpState2 = RELAY_ON;                 // then trigger the pump relay pin
      pumpTimerMillis2 = currentMillis;      // and set the pump countdown timer to the current clock time
     }

     if (currentMillis - pumpTimerMillis2 >= pumpDuration)   // If the countdown timer has expired,
     {
      pumpState2 = RELAY_OFF;                             // then turn off the pump relay pin
      pumpTimerMillis2 = 0;                               // and reset the timer to 0 for the next trigger
     }
    }

    //========

    void readFloatSensor3()
    {
     if (digitalRead(floatSensorPin3) == LOW)   // If the float sensor is tripped (pulled low)
     {
      pumpState3 = RELAY_ON;                 // then trigger the pump relay pin
      pumpTimerMillis3 = currentMillis;      // and set the pump countdown timer to the current clock time
     }

     if (currentMillis - pumpTimerMillis3 >= pumpDuration)   // If the countdown timer has expired,
     {
      pumpState3 = RELAY_OFF;                             // then turn off the pump relay pin
      pumpTimerMillis3 = 0;                               // and reset the timer to 0 for the next trigger
     }
    }

    //========

    void triggerPumps()
    {
     // Toggle the pump relay pins on and off based on
     // pumpState from the readFloatSensor functions

     digitalWrite(pumpRelayPin1, pumpState1);
     digitalWrite(pumpRelayPin2, pumpState2);
     digitalWrite(pumpRelayPin3, pumpState3);
    }

    //=====END


body:
I am working on a project for tracking cars. I am using an Arduino UNO to receive the position from GPS/GPRS shield. I am OK on obtaining the coordinates position.
Now I need to send the position to a webserver and then show it on a webpage using the Google Maps API. Which accepts it in a POST or GET method.
Here is the shield model:
[U-blox Sara G-350][1]
and this is its manual [here][2]

Here is my approach:

    #include <SoftwareSerial.h>
    #include <String.h>

    SoftwareSerial gprsSerial(7 ,8);

    void setup() {
      // put your setup code here, to run once:
      gprsSerial.begin(19200);
      Serial.begin(19200);
      delay(2000);

     gprsSerial.println("AT+CGDCONT=3,\"IP\",\"weborange\"");
     toSerial();
     delay(2000);

     gprsSerial.println("AT+UHTTP=0");
     toSerial();
     delay(2000);
     gprsSerial.println("AT+UHTTP=2,1,\"www.navtec.16mb.com\"");
                       //AT+UHTTP=<profile_id>,<op_code>,<HTTP_server_name>
     toSerial();
     delay(2000);

     gprsSerial.println("AT+UHTTP=0,5,80");
     toSerial();
     delay(2000);

    }

    void loop() {

     //gprsSerial.println("AT+UHTTP=2,1,\"submit\"");
                        //AT+UHTTP=<profile_id>,<op_code>,<param_val>[,<param_val1>]
     //toSerial();
     //delay(2000);

     gprsSerial.println("AT+UHTTPC=2,1,\"/add.php\",\"filename\"");  //Problem here!!!!!!!!
                       //AT+UHTTPC=<profile_id>,<http_command>,<path>,<filename>[,<param1>[,<param2>[,<param3>]]]
     toSerial();
     delay(2000);
    }

    void toSerial()
    {
      while(gprsSerial.available()!=0)
      {
        Serial.write(gprsSerial.read());
      }

    }

This is what I get:

> +CGDCONT=3,"IP","weborange"
>
> OK
> +UHTTP=0
>
> OK
> +UHTTP=2,1,"www.navtec.16mb.com"
>
> OK
> +UHTTP=0,5,80
>
> OK
> +UHTTPC=2,1,/add.php,filename
>
> ERROR
> +UHTTPC=2,1,/add.php,filename
>
> ERROR
> +UHTTPC=2,1,/add.php,filename
>
> ERROR
> +UHTTPC=2,1,/add.php,filename
>
> ERROR ...

Thanks for your time, I am waiting for your support, any ideas could help. Sorry for my bad English

  [1]: https://i.stack.imgur.com/HfhAU.jpg
  [2]: https://www.u-blox.com/sites/default/files/u-blox-ATCommands_Manual_(UBX-13002752).pdf

title: Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350)

Answers: 1

body:
I worked on a project similar to yours. I think you forgot to **establish a connection first**.
Just add those lines of code at the top of `setup()` method:

     gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
     toSerial();
     delay(2000);
      gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
     toSerial();
     delay(2000);
     gprsSerial.println("AT+UPSDA=2,3");
     toSerial();
     delay(2000);
     gprsSerial.println("AT+UPSND=2,0");
     toSerial();
     delay(2000);

I hope it works for you. Else, you can use `AT+UHTTPER=2` after all to check for error source.


body:
I was trying to connect my Arduino Nano to my home Wi-Fi. To do that, I connected my Arduino to ESP8266 module.

I connected pins

    Arduino  | ESP8266
    3.3V     | VCC
    3.3V     | CH_PD
    D10      | RXD
    D11      | TXD
    GND      | GND

to connect to Wi-Fi, I used code which I found on internet.

What I'm getting is `"FAILED - Timeout exceeded"` which indicates there is no response from the ESP module. Is it possible I did something wrong and I fried it, or I connected it wrong? Or maybe it does not have enough power (I'm powering my Arduino via computer USB port)? I also read reviews which indicates customers who bought similar product from different vendors they had issues with firmware. Is it possible I have same problem?

#Code

    #include <SoftwareSerial.h>
    SoftwareSerial softSerial(10, 11); // RX, TX
    String WSSID = "xxxxxxxxxxxx";
    String WPASS = "xxxxxxxxxxxx";
    bool r;

    void setup() {
      /* SETUP SERIAL COMMUNICATION */
      espSerialSetup();
      delay(2000); // Without this delay, sometimes, the program will not start until Serial Monitor is connected
      r = espSendCommand( "AT+CIFSR" , "OK" , 5000 );
      if( !r ) {
        r = espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
        r = espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
      }
    }

    void loop(){
      r = espSendCommand( "AT+CIPSTART=\"TCP\",\"108.59.11.102\",80" , "OK" , 5000 );
      String getRequest = "GET /shiznic/ HTTP/1.1\r\nHost: www.rootpower.com\r\n";
      int getRequestLength = getRequest.length() + 2; // add 2 because \r\n will be appended by SoftwareSerial.println().
      r = espSendCommand( "AT+CIPSEND=" + String(getRequestLength) , "OK" , 5000 );
      r = espSendCommand( getRequest , "+IPD" , 15000 );
      //r = espSendCommand( getRequest , "world" , 15000 ); // page should respond with Hello, world.
      if( !r ) {
        Serial.println( "Something wrong...Attempting reset...");
        espSendCommand( "AT+RST" , "ready" , 20000);
        espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
        espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
      }
      delay(3000);
    }

    void espSerialSetup() {

      // change baud rate so SoftwareSerial works better -- need a certain version of ESP for this to work and be retained after power cycle
      // make sure Serial Monitor port speed is set to 9600
      softSerial.begin(115200); // default baud rate for ESP8266
      delay(1000);
      softSerial.println("AT+CIOBAUD=9600");
      delay(1000);
      softSerial.begin(9600);
      Serial.begin(9600);
    }

    bool espSendCommand(String cmd, String goodResponse, unsigned long timeout) {
      Serial.println("espSendCommand( " + cmd + " , " + goodResponse + " , " + String(timeout) + " )" );
      softSerial.println(cmd);
      unsigned long tnow = millis();
      unsigned long tstart = millis();
      unsigned long execTime = 0;
      String response = "";
      char c;
      while( true ) {
        if( tnow > tstart + timeout ) {
          Serial.println("espSendCommand: FAILED - Timeout exceeded " + String(timeout) + " seconds" );
          if( response.length() > 0 ) {
            Serial.println("espSendCommand: RESPONSE:");
            Serial.println( response );
          } else {
            Serial.println("espSendCommand: NO RESPONSE");
          }
          return false;
        }
        c = softSerial.read();
        if( c >= 0 ) {
          response += String(c);
          if( response.indexOf(goodResponse) >= 0 ) {

            execTime = ( millis() - tstart );
            Serial.println("espSendCommand: SUCCESS - Response time: " + String(execTime) + "ms");
            Serial.println("espSendCommand: RESPONSE:");
            Serial.println(response);
            while(softSerial.available() > 0) {
              Serial.write(softSerial.read());
            }
            return true;
          }
        }
        tnow = millis();
      }
    }

**UPDATE**
I changed connections to
  D11      | RXD
  D10      | TXD

and i also simplified my code

    #include <SoftwareSerial.h>

    SoftwareSerial esp(10, 11);

    void setup() {
       Serial.begin(115200);
      while (!Serial);
      Serial.println("Started");
      esp.begin(115200);
      esp.write("AT\r\n");
    }

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

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

now I'm sending basic AT command to test connection, and still not getting any response. LED on ESP module is on, so I'm assuming it is working.

title: Did I fry my ESP8266 module or was it something wrong with it?

Answers: 2

body:
By the looks of the information you have provided, it looks as though you have not made the crossed serial connection: `rx-tx tx-rx`.

Your wiring:

    Arduino  | ESP8266
    3.3V     | VCC
    3.3V     | CH_PD
    D10      | RXD
    D11      | TXD
    GND      | GND

And when you intialize the software serial library:

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

You declare `D10` as `RX` and then connect it to the ESPs `RX` and ditto for the `TX` line.

What you need to do is the following:

    Arduino  | ESP8266
    3.3V     | VCC
    3.3V     | CH_PD
    D10      | TXD   //change to this
    D11      | RXD   //change to this
    GND      | GND

Also you need to ensure that the arduino TX line does not exceed 3.3V you can use a voltage divider, logic-level shifter board or a 74LVC245. This is important as the 5V arduino pins will damage a 3.3V device. This is a note as arduino nano is a 5V device from what I know(I may be corrected).

body:
As far as I know, the 3.3v on the Arduino board might not have enough current for the ESP module, as it is very 'power hungry'.

I've had some hard time making my modules work properly, and your problem could be a number of things.

I will stick to Ockam's razor principle and go by the simple side.

In your code you are using 9600 baud,but the ESP8266 'base' speed is 115200. Try that speed (and CR+LF) also on your Usb cable and it might work.


body: I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.

title: ESP 8266 web server using arduino

Answers: 2

body: The ESP communicates using the UART, not SPI. It uses modem-like AT commands. Unless you write your own ESP firmware, in which case how it communicates is up to you - and so is the accompanying Arduino library.

body:
The following link is a great resource for learning how to use the WiFi module.  It has all the commands you are likely to need.  The guide is written with the intent that the user will use the module as a standalone device without the Arduino, but at the end of the guide the commands given are all the same.  This is the reference I use for projects like this.  [ESP8622 Quick Start Guide][1]

  [1]: http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf


body:
I'm looking for a way to use Arduino UNO's as serial outputs or input "individually", I don want to have an RX pin for each TX pin. I know the library *SoftwareSerial*, but I'm not sure if it is posible to achieve my objective with it.

I have also read that in this library "If using multiple software serial ports, only one can receive data at a time". Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

Thank you for your time.

title: Use only one pin as serial output/input with arduino

Answers: 3

body: AVR304, "Half Duplex Interrupt Driven Software UART on tinyAVR and megaAVR devices" describes how to implement a half-duplex software UART using 2 pins. Simply omit the half of the UART that you do not need in your own implementation.

body:
Serial ports do not require both directions to work. You can connect just one if you want. Of course you won't be able to reply or receive but you know that. Multiple TX from a microcontroller is easy. Just send the data at the speed required. RX is harder because you have to be able to read multiple high speed random inputs at the same time. It requires careful and complicated coding and will not be small or simple. You may not be able to do it and the rest of your project as well.

There are ICs or setups that can multiplex serial lines though. See https://electronics.stackexchange.com/questions/111491/multiplexing-ttl-serial-lines-with-transistors

body:
> I don't want to have an RX pin for each TX pin ...

I adapted the SoftwareSerial library a while ago to omit the receiving part. You can download that from:

http://www.gammon.com.au/Arduino/SendOnlySoftwareSerial.zip

You use that like SoftwareSerial but if you read you will always get -1 returned, and `available` always returns 0.

The constructor only has the transmit pin:

      SendOnlySoftwareSerial(uint8_t transmitPin, bool inverse_logic = false);

---

> Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

You don't want an Rx pin, but you want to receive from more than one pin at a time? Now you've lost me.

Sounds like an [X-Y Problem](http://xyproblem.info/) - maybe describe this requirement in more detail.

Having said that, hardware serial can receive from one pin while the processor is doing something else. If you have a Mega you could receive from 4 ports at once (it has 4 x hardware serial ports).


body:
I have been working on a hydroponic garden that is controlled with Arduinos. I have everything working except for the user interface. What I would like to do is have an LCD screen paired with a rotary encoder for use on the garden, and an ESP8266 WiFi module set as a server working with a custom Android app that I am writing.

I have been working on writing the app and the code that will allow the Arduino and the app to talk to each other, but I have been running into a problem. Sometimes the serial data between the ESP266 and the Arduino is not being picked up by the Arduino. I have verified that the data coming out of the WiFi module is correct, but the Arduino seems to be missing characters. This seems to happen almost at random. Sometimes it will work, and other times it will simply get stuck. I used a SoftwareSerial library to add an extra serial port and printed what the Arduino was receiving from the WiFi module, and it just seems to be missing random characters.

Up until now I have had the WiFi module connected and the LCD screen. I was using the LCD screen to display debugging messages. I took the LCD screen off and deleted all the LCD code and now everything seems to work just fine.

The LCD screen uses I2C.

Why does disconnecting the LCD screen solve the issue? Is there a way to make both run at the same time? The LCD uses I2C. I am unaware of anything that would prevent this from working.

Thanks.

title: Serial not working with I2C

Answers: 1

body:
**Explanation**

The SoftwareSerial library requires continually polling the serial ports over short periods of time therefore it presents a problem of having to parse received data into something usable, which is going to be nearly impossible as your program is going to be too busy trying to keep up with all the incoming NMEA characters to assemble it all into something meaningful.

So in your situation the data from the ESP8266 module is probably fine as you say, but parsing it and sending it to the lcd over I2C is a lot of work and sometimes it will "lose" data it simply doesn't have time to process. This explains why the data loss is hit and miss, and gets resolved when you reduce the processing workload of your program by removing the lcd component.

**Solution**

What you need here is to use an interrupt-driven SoftwareSerial library instead, which works by filling a buffer in the background with received data and allows a little breathing room to process the serial data. A great example is the [NewSoftwareSerial][1] library. This link will show you how to use the library , also expand into the details my answer to give you a deeper understanding.

  [1]: http://arduiniana.org/libraries/NewSoftSerial/


body:
I'm new to arduino. I had found an interesting project to work on with, but unfortunately I'm held up at compilation error. I tried finding answers to this problem but not able to understand.

Here is my code:

        // Include Libraries
    #include <Wire.h>
    #include <Servo.h>
    #include <Adafruit_TCS34725.h>

    // Initialize Sensors
    Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);
    Servo myservoRed;
    Servo myservoGreen;
    Servo myservoBlue;

    int posRed = 0;
    int posGreen = 0;
    int posBlue = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("Color View Test!");

      if (tcs.begin()) {
        Serial.println("Found sensor");
      } else {
        Serial.println("No TCS34725 found ... check your connections");
        while (1); // halt!
      }

      //Attach servos to ouput pins
      myservoRed.attach(9);
      myservoGreen.attach(6);
      myservoBlue.attach(3);

      // Initialize Fan pin
      pinMode(7, OUTPUT);

    }

    void loop() {
      uint16_t clear, red, green, blue;
      tcs.setInterrupt(false);
      delay(60);  // takes 50ms to read
      tcs.getRawData(&red, &green, &blue, &clear);
      tcs.setInterrupt(true);
      Serial.print("C:\t"); Serial.print(clear);
      Serial.print("\tR:\t"); Serial.print(red);
      Serial.print("\tG:\t"); Serial.print(green);
      Serial.print("\tB:\t"); Serial.print(blue);

      // Map color to motor position
      posRed = map(red,100,10000,10,80);
      Serial.print("\tRedPos:\t"); Serial.print(posRed);
      posGreen = map(green,100,10000,10,80);
      Serial.print("\tGreenPos:\t"); Serial.print(posGreen);
      posBlue = map(blue,100,10000,10,80);
      Serial.print("\tBluePos:\t"); Serial.print(posBlue);
      Serial.println();

      // Write position to motor
      myservoRed.write(posRed);
      delay(100);
      myservoGreen.write(posGreen);
      delay(100);
      myservoBlue.write(posBlue);
      delay(100);

    }

Here is the Wire.h:

    /*
     * TwoWire.h - TWI/I2C library for Linux Userspace
     * Copyright (c) 2013 Parav https://github.com/meanbot.
     * All rights reserved.
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     */

    #ifndef TwoWire_h
    #define TwoWire_h

    #include "Stream.h"
    #include "variant.h"

    #define BUFFER_LENGTH 32
    #define I2C2 0x4819c000
    #define I2C1 0x00000000
    #define WIRE_INTERFACES_COUNT 1

    class TwoWire : public Stream {
    public:
     TwoWire(void(*begin_cb)(void));
     void begin();
     void begin(uint8_t);
     void begin(int);
     void beginTransmission(uint8_t);
     void beginTransmission(int);
     uint8_t endTransmission(void);
        uint8_t endTransmission(uint8_t);
     uint8_t requestFrom(uint8_t, uint8_t);
        uint8_t requestFrom(uint8_t, uint8_t, uint8_t);
     uint8_t requestFrom(int, int);
        uint8_t requestFrom(int, int, int);
     virtual size_t write(uint8_t);
     virtual size_t write(const uint8_t *, size_t);
     virtual int available(void);
     virtual int read(void);
     virtual int peek(void);
     virtual void flush(void);
     void onReceive(void(*)(int));
     void onRequest(void(*)(void));

        inline size_t write(unsigned long n) { return write((uint8_t)n); }
        inline size_t write(long n) { return write((uint8_t)n); }
        inline size_t write(unsigned int n) { return write((uint8_t)n); }
        inline size_t write(int n) { return write((uint8_t)n); }
     using Print::write;

     void onService(void);

    private:
     // RX Buffer
     uint8_t rxBuffer[BUFFER_LENGTH];
     uint8_t rxBufferIndex;
     uint8_t rxBufferLength;

     // TX Buffer
     uint8_t txAddress;
     uint8_t txBuffer[BUFFER_LENGTH];
     uint8_t txBufferLength;

     // Service buffer
     uint8_t srvBuffer[BUFFER_LENGTH];
     uint8_t srvBufferIndex;
     uint8_t srvBufferLength;

     // Callback user functions
     void (*onRequestCallback)(void);
     void (*onReceiveCallback)(int);

     // Called before initialization
     void (*onBeginCallback)(void);

     // Timeouts (
     static const uint32_t RECV_TIMEOUT = 100000;
     static const uint32_t XMIT_TIMEOUT = 100000;

     uint8_t adapter_nr;
     int i2c_fd;
     int i2c_transfer;
    };

    #if WIRE_INTERFACES_COUNT > 0
    extern TwoWire Wire;
    #endif
    #if WIRE_INTERFACES_COUNT > 1
    extern TwoWire Wire1;
    #endif

    #endif

Here is Wire.cpp:

    /*
     * TwoWire.h - TWI/I2C library for Linux Userspace
     * Copyright (c) 2013 Parav https://github.com/meanbot.
     * All rights reserved.
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     */

    extern "C" {
    #include <string.h>
    #include <i2c.h>
    }

    #include "Wire.h"

    #include <Mux.h>
    #include <trace.h>
    #define MY_TRACE_PREFIX "Wire"

    TwoWire::TwoWire(void(*_beginCb)(void)) : rxBufferIndex(0), rxBufferLength(0),
           txAddress(0), txBufferLength(0),
           srvBufferIndex(0), srvBufferLength(0),
           onBeginCallback(_beginCb),
           adapter_nr(-1), i2c_fd(-1),
           i2c_transfer(0)
    {
     // Empty
    }

    void TwoWire::begin(void)
    {
     muxSelectI2c(0);
     if (onBeginCallback)
      onBeginCallback();
     if ((adapter_nr = i2c_getadapter(I2C2)) < 0) {
      return;
     }
     if ((i2c_fd = i2c_openadapter(adapter_nr)) < 0) {
      return;
     }

    }

    void TwoWire::begin(uint8_t address)
    {
     if (onBeginCallback)
      onBeginCallback();
    }

    void TwoWire::begin(int address)
    {
     begin((uint8_t) address);
    }

    uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
    {
     if (quantity > BUFFER_LENGTH)
      quantity = BUFFER_LENGTH;

     /* Set slave address via ioctl  */
     i2c_setslave(i2c_fd, address);

     if(i2c_transfer) {
     /* Need to perform a combined read/write operation
      */
      i2c_transfer = 0;
      if (sendStop == false)
       return 0;
      i2c_add_to_buf(address, 1, rxBuffer, quantity);
      if (!i2c_readwrite(i2c_fd)) {
       rxBufferIndex = 0;
       rxBufferLength = quantity;
       i2c_transfer = 0;
       return quantity;
      } else
       return 0;
     }
     if (i2c_readbytes(i2c_fd, rxBuffer, quantity) < 0)
      return 0;
     // set rx buffer iterator vars
     rxBufferIndex = 0;
     rxBufferLength = quantity;

     return quantity;
    }

    uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
    {
     return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
    }

    uint8_t TwoWire::requestFrom(int address, int quantity)
    {
     return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
    }

    uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
    {
     return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) sendStop);
    }

    void TwoWire::beginTransmission(uint8_t address)
    {
     if (i2c_fd < 0 || adapter_nr < 0)
      return;
     /* set slave address via ioctl in case we need to perform terminating
      * write operation
      */
     i2c_setslave(i2c_fd, address);
     // save address of target and empty buffer
     txAddress = address;
     txBufferLength = 0;
    }

    void TwoWire::beginTransmission(int address)
    {
     beginTransmission((uint8_t) address);
    }

    //
    // Originally, 'endTransmission' was an f(void) function.
    // It has been modified to take one parameter indicating
    // whether or not a STOP should be performed on the bus.
    // Calling endTransmission(false) allows a sketch to
    // perform a repeated start.
    //
    // WARNING: Nothing in the library keeps track of whether
    // the bus tenure has been properly ended with a STOP. It
    // is very possible to leave the bus in a hung state if
    // no call to endTransmission(true) is made. Some I2C
    // devices will behave oddly if they do not see a STOP.
    //
    uint8_t TwoWire::endTransmission(uint8_t sendStop)
    {
     int err;
     if (sendStop == true) {

      // transmit buffer (blocking)
      if (txBufferLength > 1)
       err = i2c_writebytes(i2c_fd, txBuffer, txBufferLength);
      else if (txBufferLength == 1)
       err = i2c_writebyte(i2c_fd, *txBuffer);
      else
      /* FIXME: A zero byte transmit is typically used to check for an
       * ACK from the slave device. I'm not sure if this is the
       * correct way to do this.
       */
       err = i2c_readbyte(i2c_fd);
      // empty buffer
      txBufferLength = 0;
      if (err < 0)
       return 2;
      return 0;
     } else {
     /* sendStop = false
      * pretend we have held the bus while
      * actually waiting for the next operation
      */
      i2c_add_to_buf(txAddress, 0, txBuffer, txBufferLength);
      i2c_transfer = 1;
      return 0;
     }
    }

    // This provides backwards compatibility with the original
    // definition, and expected behaviour, of endTransmission
    //
    uint8_t TwoWire::endTransmission(void)
    {
     return endTransmission(true);
    }

    size_t TwoWire::write(uint8_t data)
    {
     if (txBufferLength >= BUFFER_LENGTH)
      return 0;
     txBuffer[txBufferLength++] = data;
     return 1;
    }

    size_t TwoWire::write(const uint8_t *data, size_t quantity)
    {
     for (size_t i = 0; i < quantity; ++i) {
      if (txBufferLength >= BUFFER_LENGTH)
       return i;
      txBuffer[txBufferLength++] = data[i];
     }
     return quantity;
    }

    int TwoWire::available(void)
    {
     return rxBufferLength - rxBufferIndex;
    }

    int TwoWire::read(void)
    {
     if (rxBufferIndex < rxBufferLength)
      return rxBuffer[rxBufferIndex++];
     return -1;
    }

    int TwoWire::peek(void)
    {
     if (rxBufferIndex < rxBufferLength)
      return rxBuffer[rxBufferIndex];
     return -1;
    }

    void TwoWire::flush(void)
    {
     // Do nothing, use endTransmission(..) to force
     // data transfer.
    }

    void TwoWire::onReceive(void(*function)(int))
    {
     onReceiveCallback = function;
    }

    void TwoWire::onRequest(void(*function)(void)) {
     onRequestCallback = function;
    }

    void TwoWire::onService(void)
    {
    }

    #if WIRE_INTERFACES_COUNT > 0
    static void Wire_Init(void)
    {
    }

    TwoWire Wire = TwoWire(Wire_Init);

    void WIRE_ISR_HANDLER(void) {
     Wire.onService();
    }
    #endif

    #if WIRE_INTERFACES_COUNT > 1
    static void Wire1_Init(void)
    {
     if ((adapter_nr = i2c_getadapter(I2C1)) < 0) {
      return;
     }
     if ((i2c_fd = i2c_openadapter) < 0) {
      return;
     }
    }

    TwoWire Wire1 = TwoWire(Wire1_Init);

    void WIRE1_ISR_HANDLER(void) {
     Wire1.onService();
    }
    #endif

Here is the error message i got:

    libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `TwoWire::write(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::write(unsigned char const*, unsigned int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:194: multiple definition of `TwoWire::write(unsigned char const*, unsigned int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:194: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:204: multiple definition of `TwoWire::available()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:204: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::read()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:209: multiple definition of `TwoWire::read()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:209: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::peek()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:216: multiple definition of `TwoWire::peek()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:216: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::flush()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:223: multiple definition of `TwoWire::flush()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:223: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::begin()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:43: multiple definition of `TwoWire::begin()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:43: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:57: multiple definition of `TwoWire::begin(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:57: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:63: multiple definition of `TwoWire::begin(int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:63: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:68: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:68: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:100: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:100: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:105: multiple definition of `TwoWire::requestFrom(int, int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:105: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int, int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:110: multiple definition of `TwoWire::requestFrom(int, int, int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:110: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:115: multiple definition of `TwoWire::beginTransmission(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:115: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(int)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:128: multiple definition of `TwoWire::beginTransmission(int)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:128: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission(unsigned char)':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:146: multiple definition of `TwoWire::endTransmission(unsigned char)'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:146: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:181: multiple definition of `TwoWire::endTransmission()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:181: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::onReceive(void (*)(int))':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:229: multiple definition of `TwoWire::onReceive(void (*)(int))'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:229: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::onRequest(void (*)())':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:233: multiple definition of `TwoWire::onRequest(void (*)())'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:233: first defined here

    libraries\Servo\Wire.cpp.o: In function `TwoWire::onService()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:238: multiple definition of `TwoWire::onService()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:238: first defined here

    libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:248: multiple definition of `WIRE_ISR_HANDLER()'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:248: first defined here

    libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

    C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `Wire'

    libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling.

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

title: compilation error in arduino

Answers: 1

body:
Looks like the Servo library has Wire source files in it for some reason. I checked my Servo library, and it doesn't have those, so not sure what's going on there, but maybe try removing Wire.cpp from Servo/src/? (keep in the file so you can put it back if necessary)

**credits to uint128_t**(in the comments)

Based on his suggestion i removed the
*wire* library files present in servo library folder and things worked just fine.


body:
I'd like to ask you some questions about ARM processor from Atmel like the SAM3X8E, the one used in the Arduino Due. I have found this [AVR programming guide] from abcminiuser on avrfreaks very helpful.

Q1. Why are there no ICSP pins in Arduino Due to use it to program the SAM3X8E from an external programmer instead of the USB port in the Due board?

Q2. If I want to program an Arduino Due from an external programmer which of the programmers in abcminiuser guide will do the job and give me the ability to program 8/16/32bit AVR and ARM chips from Atmel at the same time?

Q3. On the Arduino Due website I read this:

>"Uploading sketches to the SAM3X is different than the AVR Microcontrollers found in other Arduino boards because the flash memory needs to be erased before being re-programmed. Upload to the chip is managed by ROM on the SAM3X, which is run only when the chip's flash memory is empty. "

What is that mean?

title: Need some explain before desigin my own custom Arduino Due board

Answers: 1

body:
1. Because it is not needed. The chip comes with the bootloader pre programmed in  ROM, not in Flash. It cannot be replaced, upgraded, removed, etc like other more sensible chips. So there is no real need for ICSP since the main use for that is putting the bootloader on.
2. Unknown.
3. Unlike the AVR chips, whose bootloader always runs first for about 2 seconds, the SAM3X's boot loader only runs if the flash is empty. As a result there is a way to empty the flash built in to the Arduino code, so that it can be erased by software. That means that the software has to be working right though, which isn't always the case, since people write bad code which crashes the chip. As a result they added a erase button to the board so you can manually erase the chip and get the bootloader to run.

I have always maintained that the SAM3X is a really idiotically designed chip and I wouldn't ever use it in a design of my own.


body:
I want to get the GPS ordinates in degrees with 6 decimal accuracy. I can obtain this by creating a gps object with TinyGPS library. but In the TinyGPS example codes, its written

    Serial.println(gps.location.lat(), 6);

But I actually want to store this latitude degrees in a variable of type string or float. when i write this;

    double Tiny_latitude = (gps.location.lat());
    Serial.print("Tiny lat:");
    Serial.println(Tiny_latitude);

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600.
How do I do that ?

title: Store TinyGPS++ latitude value into a variable of type string or float

Answers: 1

body:
> it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600. How do I do that?

The issue is simply the number of decimal places. That can be added to the Serial.println().

    double Tiny_latitude = (gps.location.lat());
    Serial.print("Tiny lat:");
    Serial.println(Tiny_latitude, 6);

> Now if i want to make a String "your location is \nlat:33.546600 \nlong: 75.456912" , i.e. my String variable are stored in Tiny_latitude and Tiny_longitude and want to make a string my_Location. How do i do that?

I would use sprintf() for that but as that requires some additional build parameters the easiest way is to use String. Some special care is needed to increase the number of decimal places.

    void loop()
    {
      ...
      float latitude = 33.546600;
      float longitude = 75.456912;
      String buf;
      buf += F("your location is \nlat:");
      buf += String(latitude, 6);
      buf += F("\nlong:");
      buf += String(longitude, 6);
      Serial.println(buf);
      ...
    }

Cheers!


body:
How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?

ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.

title: Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?

Answers: 1

body:
The magical trick you are looking for is Ethernet UDP Broadcast. By chance there is an example sketch in the [Arduino Tutorial][1]. I cannot say if it is up to date but this will help you get started.

Cheers!

  [1]: https://www.arduino.cc/en/Tutorial/UDPSendReceiveString