text:
Transfer a struct's data to an external struct via serial?
Using two boards of similar architecture I would like to send the contents of a struct from the sending board to the receiving board. I am using UART to transfer.
My plan was to populate an array with the starting structs data. Transfer that, than un-package the array onto the receiving boards struct.
I'm not sure this is a possible option. Unpacking the array seems sort of rigid, as I would be assigning each struct variable to the array index. It might work but I'm not really convinced I should do it this way.
Here's what my sending sketch looks like.
Send:
typedef struct NWK_DataReq_t
{
 uint8_t      state;
 uint8_t      options;
} NWK_DataReq_t;

//Instance struct
NWK_DataReq_t dataRequest;

void setup()
{
  //Give it some values
  dataRequest.state = 2;
  dataRequest.options = 4;

  Serial.begin(9600);
}

void loop()
{
  //set variable array to struct length
  uint8_t payload[sizeof(dataRequest)];

  //copy struct to variable array
  memcpy(payload,&dataRequest,sizeof(dataRequest));

  //send each item of struct, now contained in payload array
  for(int i=0;i < sizeof(payload);i++)
  {
    //Serial.print(i);
    //Serial.print(":");
    Serial.println(payload[i]);
  }

  Serial.println("");
  delay(1000);
}

Receive:
typedef struct NWK_DataReq_t
{
 uint8_t      state;
 uint8_t      options;
} NWK_DataReq_t;

//Instance struct
NWK_DataReq_t dataRequest;
uint8_t incomingPayload[sizeof(dataRequest)];

void setup()
{
  Serial.begin(9600);
  Serial.print("Recieve started");
}

void loop()
{

  if (Serial.available())
  {
    //add incoming data to array
    for(int i=0;i<sizeof(dataRequest);i++)
    {
      uint8_t incomingByte = Serial.read();
      incomingPayload[i] = incomingByte;
    }
  }

  //set array values to structs
  for (int i= 0;i < sizeof(dataRequest);i++)
  {
    structIndexPosition = incomingPayload[i];
  }
}

structIndexPosition is not attached as I wasn't sure how I might index the struct, or if this is an okay approach.

You might want to look at my ICSC library. It handles this kind of transfer very cleanly and reliably. Feel free to use it, abuse it, rip it to bits, steal bits from it, learn from it, get ideas from it, whatever: https://github.com/MajenkoLibraries/ICSC

I think you are over-complicating it to send two bytes. Just send them as straight ASCII with a newline after, and decode it on the receiving end.
eg.
42,87

However if the question was just an example of something much more complex, then you may need to do more work. You need to have the receiving end know when a packet of data starts, and ends, and preferably have some validation that it wasn't corrupted.  If you want to pursue that idea, see my thread about sending data via RS485 which has a library that does that sort of thing.

Thanks for the link, Nick. It will be more complex than this. I'll be looking into validation shortly, just wanted to get some basics straight.

The simplest possible way of sending the struct's data is:
Serial.write((const uint8_t *)&myData, sizeof(myData));

Get the address of myData, cast it to an unsigned int pointer, and starting at that address write the number of bytes specified by sizeof(myData). That will transfer the raw data of the struct through the serial with no messing with copying of data into other arrays, assigning pointers, etc.
However: it won't work.
Sending raw binary data over serial like that, where serial has no concept of anything other than bytes, it is just not possible to know where in the stream of data you are. Which of the myriad of bytes coming in is which within a struct?  Who can tell?
So you need to write a protocol. A method whereby one end tells the other end "This is the start of the data.  This is the data.  This is the end of the data."  But also you need to be able to say "This bit, that looks the same as the 'start of the data' message is actually a bit of the data, not the start of the data".  You see, it's quite an involved task really.

If you couldn't run this code like me then all you have to do is cut the:"
struct package
{
};
typedef struct package Package;
Package data; "
And paste it into the "void loop" and it should work fine.
P/s: Thank you very much for this helpful video, but hope you will update this in the future ( i guess the update had changed something in the Arduino codes)

For what it's worth I'm looking at the question and looking at your answer and it almost looks like you're answering a completely different question from the one being asked.  But, I can't tell for certain.

Why go over the bridge for water?
It is possible to access the data in the struct as a character pointer. No need to transfer to a buffer etc.
void loop()
{
  ...
  ...
  const char* dp = (const char*) &dataRequest;
  for (int i = 0; i < sizeof(dataRequest); i++) Serial.print(*dp++);
  Serial.println();
  delay(1000);
  ...
  ...
 }

It might be hard to extrapolate how to receive this?
void loop()
{
  if (Serial.available() > sizeof(dataRequest)) {
     char* dp = (char*) &dataRequest;
     for (int i = 0; i < sizeof(dataRequest); i++) *dp++ = Serial.read();
     Serial.read();
     ...
     ...
  }
}

The Serial.println() and extra Serial.read() could be replaced by a "frame marker" and/or a check-sum.
Cheers!

Okay, but how would I populate the new struct with dp?

It appears to be working, some of the time. I have a Serial.print(dataRequest.options) line to confirm. It sometimes reaches 4, but also reaches a couple other numbers in a looping pattern.


text:
Zeroing a Vernier force probe
For a class assignment I have been tasked with zeroing a Vernier force probe by typing a command into the serial monitor. I am having trouble writing the code for this algorithim. I was hoping to give the monitor the command and have it save the analogread as a variable which I can later subtract from future reads. Does anyone know if I can save the analogread value without it being updated in a loop? If, so how?

Not sure if this is what you mean, but:
const int FP = 0;  // force probe analog pin
const int OFFSET = 10; // your deadband depending on your sensors consistency too
int init_read = 0;  // initial read
int curr_read = 0;  // this will be constantly updated till zeroing is done

void setup(){
  Serial.begin(9600);
  //the rest of your setup()
}

void loop(){
  if (Serial.available() && (Serial.read() == 'z')){  // if you sent anything with the monitor and if 'z' is present
    init_read = analogRead(FP); // initial read from sensor before 'zeroing' begins
    while (abs(curr_read - init_read) < OFFSET){ // here you indicate the condition that would mean the probe has been zeroed
      // make your adjustments or whatever
      curr_read = analogRead(FP);  // take a new reading and check in the next iteration
    }
    Serial.print("Zeroing is done.");
  }
}

z is the command you send from the serial monitor to begin zeroing.

There is usually some jitter in analogRead, so you might want to compare for "almost the same".

Right...will edit...

The main issue i am having is saving an analog read value. This seems to be an issue because the analogread value keeps refreshing. Essentially what i want to do is save an inital analogread value as "x" and then have the proceeding values be realreading-x=reading

@JaimeTorres If you place your variable 'x' in setup() like I did, it wont be updated. Do you understand the code above?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Adafruit Neopixel Library- only the first 16 LEDs respond
I am using Adafruit Neopixel Library to work with a strand of 21 RGB LEDs.
AT this point only the first 16 light up. It is not a soldering problem, battery issue or a short.
This troubleshooting page suggests to

"confirm that the number of LEDs in the LPD8806() constructor match the
  number of LEDs in the strip (both will be 32 if using the strandtest
  example and a single meter of LEDs)."

But looking at the library code below, I am not certain where to modify. Adafruit_Neopixel master zip has 2 files, which contain source code. One is Adafruit_Neopixel.cpp and the other Adafruit_Neopixel.h.
Thank you.

It is not a soldering problem, battery issue or a short. You're driving this thing off a battery? How many Amps is your power supply?

@Paul 2000mAh at 3.7V Lipo battery

Do you have a link/datasheet? Or do you know the "C" rating? And do you have a voltage/multi-meter?

When something works, but not completely, it's often due to power issues.

Embedded things, microcontrollers/Arduino are fairly robust and "logical".
Hence, if your Arduino program works today, it'll work tomorrow.
Analog devices, or electricity is (in my eyes) often a bit vague. A chip can get enough power to run, but not enough to work properly.
The NeoPixel
Adafruit has an extremely elaborated tutorial/userguide.

Powering the NeoPixels

This also seems to fit your problem.

You could try powering the strip from the middle.
Since your voltage isn't stable, your amperage might not be as high and the resistance may be a little big. It's actually quite impressive that it works.

Each NeoPixel can draw up to 60 milliamps at full brightness.

2000mAh does not mean it can (always) deliver 2000mA. It depends on the "C" or discharge rating of the battery. So if your battery is rated 0.5 C it'll only be able to supply 1000mA (for 2 hours).
60*21 would be well over 1000mA, actually 60*16 is just below 1mA, so this would fit your problem.

The voltage of a battery depends on how much charge it has.

Check google for: "LiPo voltage drop"

If all else fails

There is a chance that that particular LED is broken. The signal will not continue to the other LED's and thus the light of the strip will end there.
Try to drive the LED's behind the LED that fails. (With the power supply closer).
I'm also not sure if you can supply 3.7V and then use 5V logic. Things like that would often break a microcontroller (when running on 3.3V, you usually can't receive 5V?)

This is a good answer. I have a strip of 300 NeoPixels, and sending "pure white" to them, the other end has gone yellow. And this is with a power supply that should cope with the current requirements. Your 21 pixels, at full brightness, and consuming 60 mA would need 1.26 amps. Are you powering them from a separate power supply? One with that capacity?

@NickGammon according to the comment in the main question he's powering 21 LED's  off a "2000mAh at 3.7V Lipo battery" but he hasn't yet specified the maximal discharge rate/current (which might be below 2000mA).

See my amended reply. 3.7V is a little low for the specs.

@NickGammon Good point, if you check Li-Po discharge curves, it would also mean that the battery has to have 20%> charge since the voltage drops  when you have less charge. But apart from that it should work, Adafruit itself states that it is possible for wearable projects — a 3.7 Volt lithium-polymer battery. (Adafruit Neopixel Uberguide)

@NickGammon the discharge rate for the battery is 2C. Here is the spec for the battery https://solarbotics.com/product/battr15/

@K.Nadkina That's quite a lot indeed (4 Amps) should be sufficient. But you should try driving the LED's that come after the "faulty" LED. And/or try to power the strip from the middle.

You don't modify the library at all. The page refers to the constructor which is the last line here:
#include <Adafruit_NeoPixel.h>

#define PIN 6

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

So that would send to 60 NeoPixels. Change the 60 to however-many you have.
To compare, try running my library here. That doesn't use the Adafruit library. Use the minimal demo code, and change PIXELS to be 21.
#include <SPI.h>
#include <NeoPixels_SPI.h>

const unsigned int PIXELS = 8; // Number of pixels in the string

void setup ()
  {
  ledsetup();
  showColor (PIXELS, 0xB2, 0x22, 0x22);  // firebrick
  } // end of setup

void loop ()
  {
  } // end of loop

Note that you connect the NeoPixels data to pin D11 of your Uno in this case.

@Paul 2000mAh at 3.7V Lipo battery

according to the comment in the main question he's powering 21 LED's off a "2000mAh at 3.7V Lipo battery"

Yes, well let's look at the specs:

If you lose 0.2V over the first 8 LEDs you are under spec for the voltage.

I did change the num of PIXELS to 21 in every example in your library and still only 16 light up. any thoughts, suggestions?

Maybe that particular LED is broken. Try if you can power/test the LED's after LED 16.

With most led strips you can supply power from both ends if you are experiencing voltage drop.
You can do this with two separate power supply units if you don't have one unit that is capable of powering the entire strip.
I'm not sure if power is your entire problem, but if it is you could try this solution.
If it's a problem with the Neopixel library You could also try the excellent FastLED library and see if that helps you sort out your issues.

Could you expand upon your answer a little, and explain why it might help? Even though your answer may be correct, unfortunately, as it stands, your answer has been flagged for "its length and content" and may be deleted.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino UNO stuck in Setup function when interfacing UNO with ESP8266 module
Following is my code that i am trying to use it with Arduino Uno with ESP8266 module but my code stucked in setup function why is that.
#include "ESP8266.h"
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12,13);
#define SSID        "abcd"
#define PASSWORD    "87654321"
#define HOST_NAME   "www.baidu.com"
#define HOST_PORT   (80)

ESP8266 wifi(mySerial);

void setup(void)
{
    Serial.begin(9600);
    Serial.print("setup begin\r\n");

    Serial.print("FW Version:");
    Serial.println(wifi.getVersion().c_str());

    if (wifi.setOprToStationSoftAP()) {
        Serial.print("to station + softap ok\r\n");
    } else {
        Serial.print("to station + softap err\r\n");
    }

//    if (wifi.joinAP(SSID, PASSWORD)) {
//        Serial.print("Join AP success\r\n");
//
//        Serial.print("IP:");
//        Serial.println( wifi.getLocalIP().c_str());
//    } else {
//        Serial.print("Join AP failure\r\n");
//    }
    delay(500);
    if (wifi.disableMUX()) {
        Serial.print("single ok\r\n");
    } else {
        Serial.print("single err\r\n");
    }

    Serial.print("setup end\r\n");

}

void loop(void)
{
    uint8_t buffer[1024] = {0};

    if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
        Serial.print("create tcp ok\r\n");
    } else {
        Serial.print("create tcp err\r\n");
    }

    char *hello = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n";
    wifi.send((const uint8_t*)hello, strlen(hello));

    uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
    if (len > 0) {
        Serial.print("Received:[");
        for(uint32_t i = 0; i < len; i++) {
            Serial.print((char)buffer[i]);
        }
        Serial.print("]\r\n");
    }

    if (wifi.releaseTCP()) {
        Serial.print("release tcp ok\r\n");
    } else {
        Serial.print("release tcp err\r\n");
    }

    while(1);

}

On Serial Monitor i get the following continuously
setup begin
FW Version:0018000902
to station + softap ok
singl

setup begin
    FW Version:0018000902
    to station + softap ok
    singl

It's always a good idea to put a serial output in the setup of your code.

It seems that your Arduino resets itself.
But why?
I believe the problem would be with too little power for your ESP8266 and Arduino. When the ESP8266 wants to create a network connection, it takes a little more current, possibly leaving your Arduino without enough current to run on itself.
So your Arduino would shut down since the ESP8266 takes up all the current. Creating some kind of bootloop on your Arduino.
Please tell us how you powered the devices and how you connected them.
You might try using a separate power supply or a big capacitor on the Arduino's 5V+GND.

yes i am using separate voltage regulators for both and my other code which is different a little bit works fine thats why i am curious about this code

and i need to run above code

I think you're running out of RAM memory, try using a buffer of only 256 bytes and put the printed text in statments with F() like: Serial.print(F("Write something on the Serial Monitor that is stored in FLASH"));

yes its the buffer issue thanks but i need more memory because esp module send too much data to arduino when get request has been made it means i need to move towards mega board or due

Teensy3.2 might be a good choice. That thing has got some serious bang for buck (but is a little more difficult to use). BUT there are other options, you don't have to receive the whole message at once! You can check it in a per-byte fashion. You should ONLY save the information that you actually need!

If your question is answered with this, you should press the ✔ at the side of this answer. But keep in mind that it's probably still possible with the UNO, but will require some "lower level programming", if you really want to get into that, you should post a new question on how to perform that. But there is indeed nothing wrong with scaling up hardware.


text:
Arduino code for continuous rotation for 3 servos with Bluetooth
This code is working, any ideas?
Please check the code - Bluetooth is connecting but the servo motors are not varying with respect to the app sliders.
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo2 = realservo;
      servo2 = map(servo2, 1000, 1360, 0, 360);
      myservo2.write(servo2);
      Serial.println("servo 2 On");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo3 = realservo;
      servo3 = map(servo3, 1000, 1360, 0, 360);
      myservo3.write(servo3);
      Serial.println("servo 3 On");
      delay(10);
    }
  }
}

pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.

pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.
If you do want to use softwareserial try this code https://gist.github.com/emil01/afedff4c3ba4625ebc75 Here i am using pins 2 & 3.
If you do not want to use software serial you can try this code https://gist.github.com/emil01/9a89800e383ec7f95b3f
In your code
  if (bluetooth.available() >= 2 )
  {
   unsigned int servopos = bluetooth.read();
   unsigned int servopos1 = bluetooth.read();

You are performing 2 consecutive read functions, this is not ideal as there can be data loss. A more ideal solution would be send a string with known string terminators and then parsing this string to get your required data.
For e.g. you could send

S1:90\nS2:180\n

from this string you can clearly figure out the start and end of the string and accordingly manipulate the data for your need

then where do I connect my HC 05 tx rx? @evolutionizer

It says broken pipe error

the Tx pin of the bluetooth would go to pin 2 and Rx to pin 3

@AnitaB broken pipe error in your android log?

I changed the bluetooth tx rx pins to 14 and 15 and that did the work!!! BUT it moves clockwise and anticlockwise I also need to make it stop could you help me with it plz @evolutionizer

As pointed by @evolutionizer , you can't do SoftSerial + Serial (native) from pin 0 and pin 1. So the setup should be like this:
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 2;
int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup USB serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

As for the movement for the servo, more information about data sent from Android is needed.
If the app is sending continuous value instead of sending only if the value is changed, you can do this trick:
unsigned int lastpost;
void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360 && realservo!=lastpost) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10); //delay to wait servo rotate to desired position
      lastpost = realservo;
    }
...
  }
...
}


text:
Motors settings
I'm trying to build my own 3D printer with a guide but I've got a problem with two of my CD/DVD motors: I don't know which settings to set in Marlin (configuration.h) because I can't find any datasheet for them.
So, I tried to set some values by my own, but I'm a little lost. That's why I'm asking for some help!
I'm using an Arduino Mega 2560 (with Marlin firmware), a RAMPS 1.4 and x4 A4988 modules.

The 1st motor has "7810200082AC" engraved on front and "D5X08VF1D" printed on the back.
The 2nd motor has "05Z20P2B" and "092KPL201ACP" printed on the back.

If I wasn't clear or some information is missing, please tell me!

I have played with a few of same looking steppers, burned one up as the one I had was a 3V one, ended up using a 9110 controller for it. So be aware of it getting extremely hot, you might need lower voltage.

Unless you are planning to make a printer with a build area no larger than the length of those screws, those tiny floppy drive motors are probably unsuitable.  Anyway, this is not meaningfully an "Arduino" question.

I don't know your exact setup, but when it comes to steppers, you just need to know a few things:

Meter the coils to get an impression, how much current you can induce.
Limit the current on your driver as low as possible (<= 0.25 A possible?)
Test
Heighten the current, if the motor doesn't turn or stalls

Your motors are quite small, so I would assume, they run with less than 0.25 A at 12 V or 0.125 A at 24 V and so on.
If you limit the current, nothing can go wrong at all. Check the heat from time to time and make sure, your drivers lowers the current, whenever the given axis stands still.
When it comes to to resolution, I would not recommend to use more than 1/4 steps, which would result in 4*48/round steps on a standard stepper and provides very good resolution plus smooth motor action.

Hi, thank you for your answer.
So I, set the Vref at 0.2V (multimeter says 0.199) to get 0.25A with a Rs at 0.1Ohm (0.25A * 8 * 0.1Ohm = 0.2V) and I put a jumper to get 1/4 steps.
Now, I don't know which values to set in Marlin for: DEFAULT_AXIS_STEPS_PER_UNIT, DEFAULT_MAX_FEEDRATE, DEFAULT_MAX_ACCELERATION.
I tried some values and the motor moves smoother than before with driver's settings but I don't know how to find exact values without a datasheet.

Huh .2V seems really less, I thought about .25A@12V which would result in 3 watts. .25@.2V is just 0,05 watts. Not enough to turn your motor, I guess. When it comes to Marlin: You need to know, how much your spindle moves during one turn (lets say: 1cm)  and how much steps your stepper does (substeps included) per round (lets say: 484). So you have 484 Steps per cm. Feedrate is very hard to guess. Try 150 on Z and 4 times more on X and Y. Accelleration is very dependend of your driver. Experiement.

You need to lower/raise the current on the A4988 modules with this tiny screw. Check the manual.


text:
Risks of ftdi_eeprom? - TX always high after flashing
I flashed an Arduino Nano compatible with ftdi_eeprom and the following config:

vendor_id=0x0403    # Vendor ID
product_id=0x6001   # Product ID

max_power=0     # Max. power consumption: value * 2 mA. Use 0 if self_powered = true.

###########
# Strings #
###########
manufacturer="FTDI"     # Manufacturer
product="Arduino Nano"  # Product
serial="arduino_1"      # Serial

###########
# Options #
###########
self_powered=false  # Turn this off for bus powered
remote_wakeup=false # Turn this on for remote wakeup feature
use_serial=true     # Use the serial number string

# Normally out don't have to change one of these flags
BM_type_chip=true       # Newer chips are all BM type
in_is_isochronous=false     # In Endpoint is Isochronous
out_is_isochronous=false    # Out Endpoint is Isochronous
suspend_pull_downs=false    # Enable suspend pull downs for lower power
change_usb_version=false    # Change USB Version
usb_version=0x0200      # Only used when change_usb_version is enabled

########
# Misc #
########

filename="eeprom.new"   # Filename, leave empty to skip file writing

My corresponfing udev rules work and I get /dev/arduino_1 after connecting.
However. After the flash, everything seems to work, But: The TX-LED is constantly on. Even, when the device is not sending. Why?
Update & solution
First, I removed this line, because it threw warning messages (outdated)
# BM_type_chip=true         # Newer chips are all BM type

Then I studied the schematics of the Nano and figured out, that RX and TX  LEDs are indeed connected to CBUS0 and CBUS1. So, I added two lines to my config
  cbus0=RXLED
  cbus1=TXLED

Which had the effect, that now both RX and TX where constantly on. So, I finally read the manual which says on page 11, that the commands in question need a trailing #. I updated my config again:
cbus0=RXLED#
cbus1=TXLED#

Extra:
Indeed, I had to install ftdi_eeprom to get the job done

 apt-get remove ftdi-eeprom
 apt-get install swig libusb-1.0-0-dev libconfuse-dev doxygen
 git clone https://github.com/legege/libftdi.git
 cd libftdi.git
 cmake .
 make
 make install
 ftdi_eeprom/ftdi_eeprom --flash-eeprom myconfig.conf

The ftdi_eeprom utility re-writes the entire EEPROM, not just the selected bits you have chosen.  That includes the "CBUS" pin configurations.
You need to check on the Nano's schematic which LED is connected to which CBUSx pin on the FTDI and set it accordingly.  You do that in your config using:
cbus0=TXLED
cbus1=RXLED

for example.
Possible settings for the CBUS pins are:

TXDEN
PWREN
RXLED
TXLED
TXRXLED
SLEEP
CLK48
CLK24
CLK12
CLK6
IO_MODE
BITBANG_WR
BITBANG_RD
SPECIAL

Except CBUS4 which only has the functions:

TXDEN
PWRON
RXLED
TXLED
TX_RX_LED
SLEEP
CLK48
CLK24
CLK12
CLK6

There is a chance that your pre-packages version of ftdi_eeprom doesn't support those settings, so you will need to download and compile the latest version from source from here: https://github.com/legege/libftdi
Also during testing I accidentally changed the VID of one of my boards thus rendering it unresponsive.  I did that by omitting the 0x from the VID and PID numbers.  Extreme care should be exercised using thin utility.  I have submitted a patch to allow the specification of a default VID for recovery from such situations.

I'll try that today and give a reply. Thanks very much so far


text:
How to disable the write protection of the USART mode register?
I have a device which transmits USART with inverted polarity, and I would like to read data from it with the help of an Arduino. I use an Arduino Due, which has a SAM3X processor, so it should be able to invert the polarity without any external hardware.
The settings accessible from the Arduino SDK are minimalistic, Serial.begin() only allows to set the baudrate and start/parity/stop, nothing else.
In the SAM3X datasheet I found the "USART Mode Register", US_MR, which dedicates bit 23 (INVDATA) to invert the polarity.

Although it seems not to be documented anywhere, I found in a forum that to access the US_MR register, I have to use UART->UART_MR. I can read that register but cannot change it. The SAM3X datasheet mentions that this register might be write protected, and that the write protection can be cleared in the US_WPMR register.
However, the Arduino SDK doesn't seem to know about this register. I tried several possibilities,
US_WPMR
UART_WPMR
WPMR
UART->US_WPMR
UART->UART_WPMR
UART->WPMR

None of which are known.
The string WPMR is nowhere to be found in any of the files in my Arduino installation folder.
EDIT:
Interestingly, the source code for the UART class doesn't contain any reference to the WPMR. It just sets the required configuration registers without bothering with it.
void UARTClass::begin( const uint32_t dwBaudRate )
{
  // Configure PMC
  pmc_enable_periph_clk( _dwId ) ;
  // Disable PDC channel
  _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;
  // Reset and disable receiver and transmitter
  _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;
  // Configure mode
  _pUart->UART_MR = UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ;
  // Configure baudrate (asynchronous, no oversampling)
  _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ;
  // Configure interrupts
  _pUart->UART_IDR = 0xFFFFFFFF;
  _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;
  // Enable UART interrupt in NVIC
  NVIC_EnableIRQ(_dwIrq);
  // Enable receiver and transmitter
  _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;
}

However, when I try to change UART_MR, it remains the same.

Did you try USART0->US_WPMR? Couldn't you add it? The register mapping offset is 0xE4 according to the datasheet.

Under Windows, Arduino puts the source code for hardware specific stuff in User\AppData\Local\Arduino, and not in the installation folder.
/* -------- US_WPMR : (USART Offset: 0xE4) Write Protect Mode Register -------- */
#define US_WPMR_WPEN (0x1u << 0) /**< \brief (US_WPMR) Write Protect Enable */
#define US_WPMR_WPKEY_Pos 8
#define US_WPMR_WPKEY_Msk (0xffffffu << US_WPMR_WPKEY_Pos) /**< \brief (US_WPMR) Write Protect KEY */
#define US_WPMR_WPKEY(value) ((US_WPMR_WPKEY_Msk & ((value) << US_WPMR_WPKEY_Pos)))

I would guess unlocking / locking would take the format:
????->US_WPMR = (US_WPMR_WPEN | US_WPMR_WPKEY(0x555341));
????->US_WPMR = (~US_WPMR_WPEN & US_WPMR_WPKEY(0x555341));


text:
Using 6 axis accelerometers
I've been messing around with accelerometers for Arduino for a school project. I bought the SODIAL GY-521 accelerometer + gyroscope module for Arduino. It uses de Invensense MPU 6050. I managed to connect it onto my board and successfully detect it, but it returns values of -1 on all output ports. I was expecting there to be a port for every axis of acceleration and rotation but it seems that this isn't the case. How should I connect the module into my Arduino, and how should I program the Arduino to read my data?
I tried to follow the Arduino Playground example but the result was as explained above.
Thank you for all answers.

From the Arduino playground:
This sensor board has a voltage regulator. When using 3.3V to the VCC the resulting voltage (after the onboard voltage regulator) might be too low for a good working I2C bus. It is preferred to apply 5V to the VCC pin of the sensor board. The board has pull-up resistors on the I2C-bus. The value of those pull-up resistors are sometimes 10k and sometimes 2k2. The 2k2 is rather low. If it is combined with other sensor board which have also pull-up resistors, the total pull-up impedance might be too low.

I am kind of new to this whole electronic thing, so I may need a little more explaining. I believe I connected the module into the 5V pin but I have no idea about the other stuff you mentioned.

First of all you should measure the pull-up resistor values. Secondly do you have other I2C devices connected?

My circuit consists of an Arduino Uno + accelerometer, nothing else. My question is where do I connect what and why, and how do I code it. So basically everything.

I usually use the following connections for my MPU 6050:
Vcc: 3.3V
GND: Any arduino GND
SDA: A4
SCL: A5
AD0: GND(for address 68)/ 3.3V(for address 69)
I do not usually connect any of the other pins. For the code I usually use a wonderful library written by Jeff Rowberg which can be found here(http://www.i2cdevlib.com/devices/mpu6050#source). This library enables you to also use the Digital Motion Processor on board the MPU 6050 to give you prefiltered rotation data. It also has example code which should make things easy.
You can connect at most 2 MPU 6050s to the I2C port of the arduino by using different addresses for it. If you need to hook up more, you will require a multiplexer.
Hope this helps.


text:
My Arduino Nano clone doesn't show in the serial this simple code. Why?
Here is the code:
void setup() {
  Serial.print("hi");
}
void loop() {
}

The product is in here.
I also installed the drivers.

You haven't "started" the serial interface.  Before you use the serial you need to tell it to initialize the hardware and how fast you want to communicate.
You need to add, for instance,
Serial.begin(9600);

to your setup() function before you do your Serial.print().

What does the command do exactly? Why 9600?

Still can't see nothing in the serial

It makes it work. At the moment you have sat in your car and and are pressing the accelerator - but you forgot to start the engine. You need to make sure that you are communicating at the same speed as you have specified in the begin() function call. Also you may see more if you change your print to a println and place it in loop instead of setup so it sends it over and over again.

still nothing in the serial monitor

Are you sure you are programming the board? Try using the Blink example to make sure you are actually programming it. Then try the AnalogInOutSerial example.

Even the blink example doesn't work in fact, because it doesn't change the blinking on the board.
Here's the proof I'm programming it?
Sketch uses 1,788 bytes (5%) of program storage space. Maximum is 30,720 bytes.
Global variables use 204 bytes (9%) of dynamic memory, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

Houston, same message if I disconnect the board. Now what?

Ohhh I made the verify before the Upload. Now it works


text:
Why can't I see the serial plot with the following code for arduino?
const int GSR=A0;
int threshold=0;
int sensorValue;

void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.print("sensorValue=");
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  }

In what way are you attempting to "plot" it? I see data arriving on serial fine.

"serial plotter" command

Maybe you should get rid of the "sensorValue=" cruft and just prinln() the value? I have never used that plotter so not sure how it handles the data, but from what I have read it just wants raw numbers.

what does cruft mean?

"badly designed, unnecessarily complicated, or unwanted code or software."

so you're reffering to "sensorValue=analogRead(GSR)"?

No, I'm referring to Serial.print("sensorValue=");

I will try to delete it. Plan B?

it works! Any idea on how I can save the data and bring it to excel?

Use a terminal emulator that can save the incoming data to a text file.

I'm trying coolTerm

The serial plotter requires just numbers and nothing else.
It can't understand the data in the format:
sensorValue=49

It just expects:
49

Remove the line
Serial.print("sensorValue=");

and it will start working.

I didn't understand how much readings it takes in a second. It's 1000milliseconds/ delay (=5) = 200?

It takes as many readings as it can. You have no timing specified, so the number of samples will be defined by the speed of the serial data, and the quantity of the serial data. The quantity of the serial data depends on the values being sampled.

How can I specify the timing?

Either with delay() (crude), millis() (pretty good) or a timer (most accurate).

I don't understand how to use the timer. Which kind of argument does it accept?

Timers are hard. Stick to millis(). Look at BlinkWithoutDelay for an example.

You haven't looked at BlinkWithoutDelay, have you?

I don't understand why it uses 3 variables for one function. Is there an easier way to do it? I

Um.... I am sorry, but I have no idea what you are talking about.

const long interval = 1000;           // interval at which to blink (milliseconds)
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;

It has been written in long hand so you can understand what is going on. You can do it with just one variable to store the timestamp - the rest is just the millis() function or a simple numeric literal.

Why do you use dalay is crode and that millis is better?

Delay doesn't take into account the time taken to perform the sampling and send it through serial, so you get clock drift. Millis takes that time into account so you don't get clock drift.

so the best way to make 4hz of sampling is with millis?

It's a good compromise between the simplicity and inaccuracy of delay and the accuracy and difficulty of use of using a timer.

Still, even seeing the example and this page
https://www.arduino.cc/en/Reference/Millis
I don't know how to use it in my case

It's not exactly a difficult concept - millis() gives you the time. If you know what the time was the last time you ran your sample routine, and you know what the time is now, you can know when you should run your sample routine next.


text:
I can't get code transferred to my Arduino Mini Pro
About 3 years ago Sparkfun had a sale on Arduino Minis, so I bought 6 of them (3 x 3.3 V @ 16 MHz and 3 x 5 V @16 MHz). I used two of them for separate projects (everything worked flawlessly) then stored the rest. Then last night I grabbed one of the 5 V and 3.3 V Minis and tried to upload the Blinking LED program to them. But I kept getting this error:
avrdude: stk500_recv(): programmer is not responding

I'm getting similar results on all of these computers: Mac OS X 10.10, Mac OS X 10.7, and Windows 7. I tested with default drivers and I tried installing fresh drivers based on the HardwareID's of the devices. I used both the newest version of Arduino IDE and a few older versions.
I've tried two different USB devices: Sparkfun Basic FTDI and a Generic USB to Serial PL2303 similar to this one. They both produce the same error, however the FTDI seems to be somewhat able to communicate since the RX & TX lights are flashing as well as the Arduino LED. With PL2303, the LED is lit constantly.
While searching last night, I found a few forums where people suggested things like hitting the reset button and selecting different Arduino boards in the IDE.

How did you store them?

@Majenko I stored them in the original box & antistatic case they came in from Sparkfun. The FTDI I stored in a plastic drawer where I organize the rest of my electronics.

Can you show how you wire the USB interfaces up?

The FTDI is a direct connection (BLK->BLK, CTS->GND, 5V->VCC, TX->RX, RX->TX, GRN->GRN) and the PL2303 I had to make jumpers from (GND->GND, RX->TX, TX->RX, 5v->VCC)

I don't know what BLK and GRN are, nor why CTS would be connected to GND...

Here, I took this from the Sparkfun website. They advertised it as a direct connection, and the first two projects I coded worked perfectly using this method.

BLK and GRN aren't pins I suspect you mean GND and DTR respectively.

Things have changed in the three years since you last used your FTDI board.
Most importantly avrdude has changed.
You will most likely find that you can program your boards perfectly fine using Arduino IDE 1.0.1.
What has changed is that avrdude has been modified to counter a change in the FTDI drivers. It used to be that the FTDI drivers would pulse the DTR line when the port was opened, but that stopped happening with newer drivers. So AVRDude started asserting the DTR line instead. However it doesn't pulse it, it just holds it low.
The problem with that is if the DTR is connected direct to the RESET pin the main chip is held in reset mode all the time instead of it just being reset briefly to reset the board.
The "fix" is to place a 100nF capacitor between DTR and RESET instead of directly connecting it. That converts the steady low into a short pulse which resets the board and enters the bootloader.

Thank you! That worked for my 3.3v. One small correction though, there is an inline SMD capacitor on the Mini board between reset and DTR, I needed to connect the 100nf in series rather than bypassing it and going directly to the RESET pin.
Also, this trick didn't seem to work with my 5v board. Is there a different configuration I need for that Arduino?

For programming a Pro Mini, I find the CP2104 adaptor works better than the FTDI or PL2303 based units, on both Mac and PC. You can find the CP2104 adaptor from many sources, such as TxHang Electronic:
http://www.ebay.com/itm/USB-2-0-TTL-UART-6PIN-Module-Serial-Converter-CP2104-STC-PRGMR-Replace-CP2102-/200958955841?hash=item2eca165141
(You may need to install CP2104 software drivers on some platforms)
This is how I wire them together:

CP2104_________PRO MINI

DTR------------DTR
3.3V--------- - * NOT USED (VCC)
5V --------- - -* NOT USED  (VCC)
TXD------------RXD
RXD------------TXD
GND-----------GND

Note: * While you may be able to power your (unloaded) Pro Mini from your CP2104 adaptor, it's better to use a separate supply that is appropriate for the version of the Pro Mini you use. Good luck. /DerrickA


text:
Accelerometer Interrupt Meaning - Wakeup Function
I am working with an LSM9DS1 IMU, and now specifically trying to program a wakeup feature into the system. My idea is to set the accelerometer at the lowest possible read rate, then when the accelerometer value exceeds a predefined level, to have the system wake up.
When programming the sensor, there is a register called INT_GEN_CFG_XL that has a "6-Direction detection for interrupt." I was wondering what this means. Does this perhaps calculate the magnitude of acceleration, and see if that goes above a predefined value? I can see the other interrupt generators are for 1-direction of each of the three axes, but I can't interrupt this one.
Here is a link to the device datasheet

The INT_GEN_CFG_XL 6-Direction detection interrupt apparently is aimed at detecting change of direction of travel, rather than an axis-combined acceleration level.
See the LSM303 discussion at Polulu.com.  That page includes a link to App Note CD00290365.pdf for the LIS3DH.  Here is what that app note says, on page 27:

There are two possible configurations for the 6D direction function:

• 6D movement recognition: In this configuration the interrupt is generated when the device moves from a direction (known or unknown) to a different known direction. ...
    •  6D position recognition: In this configuration the interrupt is generated when the device is stable in a known direction. ...

With the LSM9DS1 that you are using, you can leave OR enabled, set separate X,Y,Z threshholds in INT_GEN_THS_X_XL, INT_GEN_THS_Y_XL, INT_GEN_THS_Z_XL, and set the “Enable interrupt generation on accelerometer's X axis high event” (sim. for Y and Z) bits in the INT_GEN_CFG_XL register.


text:
Java + JSSC + Arduino + Windows
I want to know the basics of Arduino serial communications and connection with a Java application in Windows.
Can anybody provide me with a sample Java program that upon running just makes an Arduino pin high as well as the corresponding Arduino sketch, and some explanation on how the Arduino communicates with the Java app?
I am now starting with Arduino, and I have some experience with Java
I found this code on the net - will this work?
Java code
package arduino;

import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException {

    SerialPort serialPort = new SerialPort("COM3");
    try {
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("o".getBytes()));
        Thread.sleep(1000);
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("f".getBytes()));
        System.out.println("Port closed: " + serialPort.closePort());
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
  }
}

Arduino
  void setup()   {
  Serial.begin(9600);
  pinMode(8, OUTPUT);
  digitalWrite(8,HIGH);
  delay(500);
  digitalWrite(8,LOW);
  }

  int incomingByte = 0;

  void loop()
  {
 // send data only when you receive data:
    if (Serial.available() > 0) {
           int text = Serial.read();
           Serial.println(text);
           if (text == 'o') {

            digitalWrite(8,HIGH);

           }

           if (text = 'f') {

            digitalWrite(8,LOW);

           }
     }

  }

One word: Firmata. Google it. Try it.

I managed to finish my project and here is the code
Useful information:
To prevent reset on serial port open and close
https://tushev.org/articles/arduino/22 /* Add a 10-100 μF capacitor between reset and GND
 JAVA

 /* FIRST IMPORT JSSC LIBRARY */

package arduino;

import java.util.Scanner;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException,     SerialPortException {

    Scanner scan = new Scanner(System.in);
    int nummer = 0;
 SerialPort serialPort = new SerialPort("COM4");

        while (true) {
            menu();
             if (scan.hasNextInt()) {
            nummer = scan.nextInt();
        } else {
            System.out.println("verkeerde ingave");
        }
        switch (nummer) {
            case 0:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("a".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
            case 1:
                 serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
         serialPort.writeBytes("b".getBytes());//Write data to port
         serialPort.writeBytes("c".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;

                 case 2:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("d".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
                 case 3:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("e".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
        }

}
}

public static void menu() {
    final String ANSI_CLS = "\u001b[2J";
    final String ANSI_HOME = "\u001b[H";
    System.out.print(ANSI_CLS + ANSI_HOME);
    System.out.flush();
    System.out.println("");
    System.out.println("    ************************************************************************************");
    System.out.println("    *      ***       ********   *******   **    **  *****  **      **      ******      *");
    System.out.println("    *     ** **      **    **   **    **  **    **   ***   ****    **    ***    ***    *");
    System.out.println("    *    **   **     *** ****   **     ** **    **   ***   ** **   **  **          **  *");
    System.out.println("    *   *********    **   **    **     ** **    **   ***   **  **  **  **          **  *");
    System.out.println("    *  **       **   **    **   **    **  **    **   ***   **   ** **    ***    ***    *");
    System.out.println("    * **         **  **     **  *******     ****    *****  **    ****      ******      *");
    System.out.println("    ************************************************************************************");
    System.out.println("");
    System.out.println("    By Emmanouil Perselis");
    System.out.println("");
    System.out.println("What would you like to do?");
    System.out.println("0.---");
    System.out.println("1.Toggle lights");
    System.out.println("2.Toggle air");
    System.out.println("3.---");
    System.out.println("4.---");

}
 }

ARDUINO SCETCH
 int led = 13;
 int led1 = 2;
 int led2 = 4;
 int led3 = 7;
 int led4 = 8;
 void setup() {
   Serial.begin(9600);
   pinMode(led, OUTPUT);
   pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led4, OUTPUT);
 }

 void loop() {
   char i= Serial.read();

   if(i=='a'){////////////////
     if(digitalRead(led)){////////////
   digitalWrite(led, LOW);  ////////////
  }else if(!digitalRead(led))//////////
   digitalWrite(led, HIGH);  //////////
 }

  if(i=='b'){////////////////
     if(digitalRead(led1)){////////////
   digitalWrite(led1, LOW);  ////////////
  }else if(!digitalRead(led1))//////////
   digitalWrite(led1, HIGH);  //////////
 }

 if(i=='c'){////////////////
     if(digitalRead(led2)){////////////
   digitalWrite(led2, LOW);  ////////////
  }else if(!digitalRead(led2))//////////
   digitalWrite(led2, HIGH);  //////////
 }

 if(i=='d'){////////////////
if(digitalRead(led3)){////////////
   digitalWrite(led3, LOW);  ////////////
  }else if(!digitalRead(led3))//////////
   digitalWrite(led3, HIGH);  //////////
 }

 if(i=='e'){////////////////
if(digitalRead(led4)){////////////
   digitalWrite(led4, LOW);  ////////////
  }else if(!digitalRead(led4))//////////
   digitalWrite(led4, HIGH);  //////////
 }
}

I had this problem with communication with Arduino Uno (I think that the Arduino Uno, and other boards, with this type of scheme, suffer this problem).
The DTR line on Arduino Uno is connected with RESET, including when you use the Arduino IDE Serial Monitor port, such that the parameter of DTR is false. Yeah, you can fix this with capacitor or catch place RESET EN on board. But when you set setting you can just write:
comport3.setParams(9600, 8, 1, SerialPort.PARITY_NONE, false, false);

The last parameter is DTR and its default is true, the second to last parameter is RTS (it defaults to true too). I set both of these parameters to false and my board reads commands from the computer without resetting.
I write this for other people who had this problem.


text:
Arduino SoftwareSerial not receiving data from Neo-6M GPS module
I am trying to hook up my Neo-6M GPS module to my Arduino Uno but am having some trouble getting GPS data out of it.
The code being used was taken from the TinyGPS library. I have set the SoftwareSerial ports in the constructor to 2 and 3 (check images at bottom for reference). I set to the boad rate of the software serial so that it matches that of the Neo-6M. The datasheet for the module can be found here.
The output that comes out of the Arduino serial monitor looks like this:

A new line is added to this every second, and when the line is added the TX light on the Arduino blinks. The 'Chars RX' 0 would indicate that the SoftwareSerial isn't reading any data at all from the module. I can't for the life of me figure out why this is happening! Any help would be much appreciated.
#include <SoftwareSerial.h>
#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

TinyGPS gps;
SoftwareSerial ss(2, 3);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

void setup()
{
  Serial.begin(115200);

  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

  ss.begin(9600);
}

void loop()
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  print_date(gps);
  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  Serial.println();

  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("********** ******** ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

Gray wire should be plug on pin2. SoftwareSerial ss(2, 3);  means pin2 for Receive(RX) and pin3 for Transmit(TX). The Transmit(TX) on Neo-6M should be connected to Receive(RX) on Arduino.


text:
How to exclude a ino/pde file from Arduino projects
I would like to be able to exclude from the auto-including process of the current project (without renaming the extension or delete it) a sketch with pde or ino extension that is used in certain circumstances only.
How can I do this?
I currently use Visual Micro to manage projects on Arduino.

One possible approach is to guard the body of that sketch with an #ifdef ... #endif pair, and use Visual Micro's  “Project Properties” to define (or not) a preprocessor symbol.  [If the .ino or .pde in question is used as a #include file, you would instead guard all the #include instances.]
Refer to the “Project Defines” page at visualmicro.com for how to define a preprocessor symbol and its value. [Via: Tools > Options > Visual Micro > Compiler > Show Build Properties]  Also see  How do I add additional compiler switches in Visual Studio.
If necessary, you can use other tests besides #ifdef to control compilation.  The first link above shows the following example.
#if USBPORT > 3
....your code here....
#endif


text:
How do I run a loop for a specific amount of time?
I currently have a for loop that loops 300 times and then moves on.
Instead, I'd like that loop to run for a specific number of minutes, instead.
Here's the current loop, for reference.
for(int i = 1; i<300; i++){
  if (kill() == true){ break; }

  strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
  strip.show();

  tone(TONE, notes[random(0,3)]);
  delay(100);
}

Also, I have an RTC that's used elsewhere in the app, so real actual time is available for use if it makes sense to do that...though I'd love to know of a way to do it without an RTC module for future projects.

Here is an example that will run for 5 minutes. Note that the loop will begin executing anytime before the time limit is up, including 1 msec before; it can't cut-off something happening at the 5-minute mark, meaning the timing precision will be limited to the duration of the code in the loop.
Update: My first suggestion had a bug related to the 50-some-odd days roll-over period of the millis() clock. This one is more robust:
uint32_t period = 5 * 60000L;       // 5 minutes

for( uint32_t tStart = millis();  (millis()-tStart) < period;  ){
   doStuff();
   moreStuff();
}

This is based on "5 minutes from the start of the Arduino" though, right?

No, it's based on the time of entry to the loop. The for-loop's first clause calculates the ending time, and the second clause compares the current time at the top of each loop to that time.

Just tested and works wonderfully. Thanks!

To your update, does tQuit need to be defined somewhere?

Acch! That what I get for coding on the fly! tQuit is no longer used (the bug was related to tQuit). That should say 'period'. (fixed). Thanks for the catch.

Using this example:
http://playground.arduino.cc/Code/ElapsedMillis
You could try something like:
#include <elapsedMillis.h>

elapsedMillis timeElapsed;
unsigned int interval = 60000; //one minute in ms

while(timeElapsed < interval){
    //do stuff
}

Depending on how accurate you want to be, you might want to opt for a similar method using the RTC.

Nice, "These special variable types automatically increase as time elapses."

You can use a variable that is incremented each time you perform the loop, then you need only to change the loop from using a for to a while.
For example:
   int incremented_variable = 0;
   int incremented_value = 100;
   int max_value = 1000;

   while(incremented_variable < max_value){
   if (kill() == true){ break; }

   strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
   strip.show();

   tone(TONE, notes[random(0,3)]);

   delay(100);
   incremented_variable = incremented_variable + incremented_value;
   }

EDIT: I have just read your update on the question.
You can then use a while with a boolean flag that help you to end the loop or if you prefer, you can keep track of the time by calling the method: millis().

But how does that equate to actual time? i.e. "This loop has been running for 5 minutes."

@Shpigford you can manage to control the time changing the incremented_value that now is set to 100 and the max_value that is set to 1000. As an advice run the script only once to see the time it takes to perform only one time than you set those value accordingly.


text:
Encoding clock signal into linear block codes
In the VirtualWire library, it is possible to encode the clock signal as the library is doing with 4b/6b coding. This is possible because VirtualWire uses convolutinal coding, where the information is spread along the sequence. But, is the same possible for linear block coding, such as LDPC/Hamming?
Otherwise, if it is not possible, then how would I best deal with the signal going out of sync with serial communication, given I want to use LDPC coding.
Lastly, the reason I am using serial communication is because I will have numerous nodes in my wireless mesh network, so to my knowledge, for the sake of: speed, power efficiency, scalability, ease of implementation, etc, serial communication works best. But has anyone had better luck with any other types of communication that can take care of the sync problem, while accounting for speed, power efficiency, scalability, etc?
EDIT: The way I am doing wireless communication is by using simple rf transceivers. There will by one transceiver per node and I am trying to create a stable channel between one node to another. The communication channel isn't very reliable without some error correction. And I don't want to use the existing VirtualWire's convolutional error correction. I want to use LDPC codes, developed by Radford Neal. My goal is to first create a stable channel from one Arduino to another. Then, I will implement the network.

@Majenko Any ideas?

Are you concerned with the transmission between microcontroller and wireless radio or between nodes in the mesh? And could you elaborate on your requirement to transmit a clock signal? Wireless mesh networks normally don't need that in order to communicate.

Except of course if you intend to implement your very own protocol throughout all the OSI layers. ;)

I do actually intend to implement my very own protocol. Long road ahead. @sekdiy

Still, what part of your communication needs a self-clocked data stream (i.e. see my above question)?

Sometimes the receiver doesn't realize which bit is the start bit, and assumes one of the message bits was the start bit. The internal delay between the start bit and the message, and the internal delay between each bit of the message is different. This causes the a leakage of extra bits or loss of certain bits. Does that clarify?

Well, if you want to stream (and maybe later make your own flow control) then why not do it like in other networks before yours (like Ethernet): Manchester Code (https://en.m.wikipedia.org/wiki/Manchester_code). It's been used for that purpose before (see e.g. http://forum.arduino.cc/index.php?topic=63755.0) and there even are libraries available (e.g. from Atmel). Make sure that you have a plan at what layer you have to solve which problem, though. They can't be tackled all at the same level.


text:
Fastest way to test if two integers differ by 4 or equal to each other
I'm searching for the fastest way to test if two integers are equal or differ by 4. The integers can be positive, negative and equal to zero. They are between -1000 and 1000 and are exclusively multiples of 4.
The simplest approach to test this should be this:
if(x == y || x - y == 4 || x - y == -4)
{
     //do something...
}

But since I want to do this 4 times inside of a interrupt sub routine I wanted to know if there is a faster way to do this.

The fastest way could depend on the frequencies of the cases.  You could try using some bit operations to take the absolute value, divide it by 4 (>>2) and then branch on it being one or less.

A search to "the fastest way" would never give you a solid result. You could use a faster microcontroller almost endlessly attempt to optimalize. Check the requirements you need rather than searching for "the best"

Maybe you can do something fancy with the bit patterns. If you XOR them, it might give the difference between your value and the other. It can then be 0b00000000 or 0b00000100 but why steps of 4 if 4 more or less doesn't matter?

If you need to do the same comparison 4 times you can just put the result into a boolean variable.
boolean b = (x == y || x - y == 4 || x - y == -4)

if( b )
{
     //do something...
}

If you are talking about optimizing the actual code, I shouldn't worry about it. The compiler is already pretty good at this. Here is the assembler code for it.
void test(int x, int y)
{
    if(x == y || x - y == 4 || x - y == -4)
  a8:   86 17           cp  r24, r22
  aa:   97 07           cpc r25, r23
  ac:   39 f0           breq    .+14        ; 0xbc <_Z4testii+0x14>
  ae:   86 1b           sub r24, r22
  b0:   97 0b           sbc r25, r23
  b2:   84 30           cpi r24, 0x04   ; 4
  b4:   91 05           cpc r25, r1
  b6:   11 f0           breq    .+4         ; 0xbc <_Z4testii+0x14>
  b8:   04 96           adiw    r24, 0x04   ; 4
  ba:   09 f4           brne    .+2         ; 0xbe <_Z4testii+0x16>
    {
        asm ("wdr");
  bc:   a8 95           wdr
  be:   08 95           ret

first it compare the two values x and y. Then is subtract y from x and compares it with 4. After that it gets the subtracted value from the previous step; adds 4; and check if it is 0.
EDIT
As to Dave X's suggestion; using if(abs(x-y)<=4)
void test(int x, int y)
{
    if(abs(x-y)<=4)
  a8:   86 1b           sub r24, r22
  aa:   97 0b           sbc r25, r23
  ac:   04 96           adiw    r24, 0x04   ; 4
  ae:   09 97           sbiw    r24, 0x09   ; 9
  b0:   08 f4           brcc    .+2         ; 0xb4 <_Z4testii+0xc>
    {
         asm("wdr");
  b2:   a8 95           wdr
  b4:   08 95           ret

So half the number of instructions needed. But as Paul said, this might not the fastest. This code always takes 5 instructions, while the previous code will only take 3 instructions if x==y. So if 90% of the time x==y, the previous code will be faster 90% of the time.
As to the assembler code, you can see how clever the compiler is. It first subtracts y from x. Then it adds 4. If -4 <= x-y < 0 the carry bit is set. Then it subtracts 9 (so it's like (x-y)-5 because of the previous +4). If 0<= x-y <= 4 the carry bit is set. It then check if the carry bits is set by either of the last to instructions. Pretty clever.

(I just learned how to view the assembly code with an avrdump -S on the .elf file).   Maybe if(abs(x-y)<=4) would be a quicker, equivalent test.  It is interesting to see how the compiler optimizes that.

@DaveX We have a winner. I did't think that one would be faster.

avr-objdump has the -C option to demangle C++ symbols. It makes nicer looking assembly listings.

test if two integers are equal or differ by 4

And

are exclusively multiples of 4.

That would mean that when a=20, b should be 16, 20 or 24. (But can't be 17, 18, 19, 21, 22 or 23)
But you should check the most unlikely statement first. If it's likely to be well above x+4, check that first, if it's false, it'll just stop.
Ultimately you only have to check if it's less than x=y+4 or higher as x=y-4, this automatically includes x=y.
So checking if it's the same (which might be unlikely, might be redundant. Unless there is a very high chance of that being true.

"Checking if its less than x = y + 4 or higher as x= y-4"? You might want to clarify

If it can be either 24, 28 or 32 (with steps of 4) you only have to check <33 and higher as 23> that will automatically include the check if it's 28. But is only valid with the steps of 4 rule


text:
Link Arduinos over 5 acre laser tag field
I am building a laser tag system with an Arduino in each gun.
I want the guns to be linked during game play for many different reasons:

Start/Stop game
Nearby teammates
When a flag is captured
etc.

I don't know how to link the guns to one another during game play because the field may be large (e.g. a park). Wifi has too short of a range, cellular would cost, linking to a phone via bluetooth would drain the phone battery (and require each player have a smart phone to play).
Can you think of another way to link the guns? Radio transmitters?
Thanks!

You can use nRF24L01+
The chips offer:

Really high range with power amplifier (1km open field radius (776 acres if I'm right) , but fairly high power consumption 100-150mA @ 3.3V)
High range with PCB antenna (50-80m open field, low power consumption 14mA peak)
Low cost (0.8£-6£ a piece)
Many easy to use libraries available, possible to create a mesh network
High usable voltage range (direct Li-Po for example without step-up)

That's a great idea! Just to clarify, they could transfer custom data packages, like to notify the end of a game? They aren't only used for sending up and down movements to a drone, correct?

Payload and header can be whatever you wish it to be. Check out https://tmrh20.github.io/RF24/ library for more details what the chip can do.

Optionally you could add a single central node. You could place it in a central location. Preferably in a higher location. You could even use a version with an amplifier. That way you get the optimal coverage, even if two players are at opposite ends. To conserve power you could have the player units poll the central node, instead of having to listen all the time, and use power.

So you're saying, place a high powered unit in the central node, and then low powered units in the players guns? Would they have enough range with the low powered? Or is it only the strength/range of the high powered unit that matters in the equation?

@Aaron If the base station beams strong enough and frequent enough it's fairly certain the guns will receive the payload if close enough (1km field, maybe 500m dense forest). (Make it beam at full power, often, to all devices (one pipe, listen to one pipe), no ack and slow transmission speed) It's a matter of testing. Buy a pair. One high powered one and one regular one (make sure it's genuine) and then test the range, make the base beacon transmit as I've told, you can use even multiple and test it.

Perfect! Thanks for your help! This helps a lot!


text:
Piezo connection causing RTC to go haywire
When I connect a piezo (to pin 8), it causes the output of my RTC to go haywire and throw 165 errors into the results.
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 165:37:4 // Connected piezo
2016/3/25 13:36:4
2165/165/45 13:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2165/165/45 13:36:4
2016/3/25 13:36:4
2165/165/45 13:36:4
2165/165/165 165:165:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 37:36:4
2016/3/25 13:36:4
2165/165/27 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4

Here's my current layout...

Worth noting:

Disconnecting the piezo instantly solves the problem.
Connecting to any other pins also caused the issue.

Here is the Fritzing diagram

and schematic

Here's the full code...
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

#define PIN 6
#define TONE 8
const int buttonPin = 7;

long fadeTime = 1 * 60000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int switchState = 1;         // variable for reading the pushbutton status
int timeHour = 13;
int timeMinute = 20;
uint32_t alarmLength = 5 * 60000L; // 5 minutes

Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, PIN, NEO_RGB);

void setup() {
  Serial.begin(57600);

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();

  if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 00){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,0));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
      }
      strip.show();

      tone(TONE, notes[random(0,3)]);
      delay(100);
    }

    noTone(TONE);

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
  }
}

bool kill() {
  if (digitalRead(buttonPin) == LOW) {
    noTone(TONE);

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
    return true;
  }
  else {
    return false;
  }
}

Could you please add a schematics diagram of your circuit, would make it easier to understand your connections as opposed to the picture. Could you also please attach your code

@evolutionizer Done.

Is it only in case of connection or also when you drive the piezo? Might it be because the piezo (and rtc) is drawing more current than the Arduino can supply?

@Paul I'm noticing only in the case of the connection, without trying to drive the piezo.

@Shpigford could you please add pinMode(TONE,OUTPUT); in setup and try again

@evolutionizer Boom! That did the trick. So, the follow up question being...why? :)

@Shpigford arduino by default sets pins to INPUT this could be causing things to screw up

I still don't get it (: but you might add it as an answer. So it can be accepted, this StackExchange  is still a little low on acceoted answers (:

@Shpigford Just an FYI the resistor connected to the LED is not doing anything, as both the legs are shorted

@Paul I am not very clear on why this issue either. I believe what is happening is that because the pin is set as INPUT by default there is not limiting in the amount of current this could lead to the m/c acting funny.

Add
pinMode(TONE,OUTPUT);

to setup() to fix the problem.

authors: Στέργιος Μέκρας


text:
How to Serial read two consecutive chars sent by computer to Arduino?
My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?
    if(Serial.available()>0){
    char character=Serial.read();
    if(character=='a'){
    char leng=Serial.read();
    if(leng=='1'){
    tone(8, 440, 1000);
    delay(1000);
    }
    else if(leng=='2'){
    tone(8, 440, 500);
    delay(500);
    }

    }
    }

Welcome to Arduino SE! Could you please include the full code?

Presuming that code is the interior of loop(), your Arduino will spin until a character arrives, that is, until Serial.available()>0 becomes true.
It then reads the character with Serial.read() and if it's an 'a' immediately does another Serial.read().  In general, some delay occurs between characters arriving via a serial interface.  Whenever the serial buffer is empty, an immediate Serial.read() will return -1 instead of an ASCII character.
To fix this problem, test for availability of a character before doing the second read.  For example, you could add
while (!Serial.available()){}

before the read, to delay until a character is available.


text:
Using two ultrasonic sensors for counting cars when they enter to a garage
I want to use two ultrasonic sensors for counting incoming cars to a garage. What I want is: When both sensors detect the object then the counter should increase.
Can anyone help me and give me an example?

If you have two sensors, you use analogRead.
int sensor1 = A0;
int sensor2 = A1;
int distance = 50; // or whatever you want here
bool car_passing = false;

void setup(){
    int counter = 0;
}

void loop(){
    if(analogRead(sensor1) < distance &&
       analogRead(sensor2) < distance &&
       !car_passing)
    {
        car_passing = true;
        counter++;
    }

    if(analogRead(sensor1) > distance){
        car_passing = false;
    }
}

To prevent the counter keep counting while the car is passing by, we need to make a boolean, so the counter does not wait for count again, before the car has passed.

In order not to count kids in a Kettcar, big dogs or birds, a smarter algorithm should be used to define, what a car is and what not.

@ott that is true. Personally I wouldnt go for two ultra sonic sensors. But yea, that is what he asks for.


text:
Can I specify custom port names in the Arduino IDE on Linux?
On Linux, if you have more than one USB TTY device, the USB port name (/dev/ttyUSBx) changes every time one is plugged in, and there's no easy way to know the new name without going and looking through dmesg.  It's trivial to set up a udev rule that creates a custom symlink so that my Arduino's FTDI can always be accessed through e.g., /dev/ttyArduino, and this is the standard procedure for persistent access to USB devices.
However, I can't make the IDE accept anything other than the /dev/ttyUSBx names.  Even directly editing preferences.txt is ignored.
Is there any way to instruct the IDE to use custom port names in order to access the Arduino through a symlink or other persistent name?

I am not aware of a way in the Arduino IDE, but you can in UECIDE.

Look here: http://arduino.stackexchange.com/questions/3680/in-linux-how-to-identify-multiple-arduinos-connected-over-usb/22323#22323

Consider using a device name of form ttyUSBnn, where nn is fairly large.  For example, in /dev you could say
sudo ln -s ttyUSB1 ttyUSB77

Then, ttyUSB77 shows up in the IDE's ports list and can be selected.
(I don't know how to set up that link using the udev system, but imagine it can be done.)

Excellent hack, and it does work. Thanks.  If nobody answers with an IDE configuration answer in a few days I'll accept this.

This is also very dynamic and will not do what you've asked for

Obviously this is a one-off hack and doesn't work on the next plug-in, but doing it from udev appears to work fine.

Think the other way.
If your device has a port name, that is not supported by the IDE, you can create an additional (static) symlink /dev/USBx that you can identify and select in the arduino IDE.
And yes, it is quite easy to make all of your arduinos unique to udev.

Thanks!   Your link on how to flash a new serial number to an FTDI chip is very cool.  Unfortunately, there's nothing similar for the (all-too-common) CH340 and PL2303 chips -- they have no onboard storage.


text:
Issues with connecting XBee to Arduino Uno R3
I have an Arduino Uno R3, Wireless Proto Shield and a XBee XB24-AWI-001 all hooked together. I'm using X-CTU software to access the XBee and change the properties of it. I did a little research and found out that if I want to access the XBee, I have to connect the GND to the RST pin (on the Proto Shield) or hold the RESET button on the board. This method works and when I do that, I can find the XBee on X-CTU.
The question is - why do I have to do that? I'm probably wrong, but as far as I understand, if I have my Arduino connected to the computer, I'm accessing the ATmega microprocessor and that's the reason I can't access the XBee, but when I do the reset, I'm constantly resetting the microcontroller and that's the reason why I can access the XBee? Hopefully someone can explain this...
The link where I found the information about resetting (or removing) the ATmega microproccesor, Using Arduino to Connect Xbee Serial to Computer.

@Greenonline Done!

I am slightly surprised that you can actually talk to the XBee from your PC over USB with the XBee in the shield. XBee shields are generally designed for the XBee to be used by the Arduino only. The fact that you can actually talk to the XBee from the PC using X_CTU with the XBee in the Arduino shield, by holding down reset, seems to either be a quirk or a feature of the shield1.
Generally to use X-CTU to talk to the XBee, one would use an XBee explorer board or a Development board. One would configure the XBee completely in the Explorer dongle and then transfer the XBee to the shield for the Arduino to use it.
See the thread on the Digi forums, xbee s1 xctu arduino:

The shield is not design for writing and reading firmware to and from
the XBee module. It is only designed for basic two way communications.
If you want to read or write firmware to the module, you need to use a
board that is designed for it such as the XBIB boards from Digi.

See also Can an XBee be programmed with an XBee Shield.
However, hopefully someone with more knowledge of the internals of an Uno and XBee shield than I, could explain the actual electrical reasoning behind this issue. I have attempted to explain it below in the footnote.

1 Having said all of that, looking at some of my XBee shields, a couple have a microswitch, that enables the XBee to talk to either the Arduino or the USB, but not both at the same time. So, I guess that the need to hold the reset on your shield is because you do not have such a microswitch.
So the reason being, is that the Arduino and the USB can not talk to the XBee at the same time, as there would be conflict on the Rx and Tx serial lines - see this thread, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal which hints at the same thing. Two comments of note from that thread are:

It would be a lot simpler to debug the issue if you put the switch in the other position, and used SoftwareSerial to talk to the XBee and Serial to talk to the PC. Using one port to talk to two devices IS going to frustrate you no end.

and

Note that a communication application connected to an arduino that opens a com port, sends data, then closes may cause the arduino to reset.

As a (really wild) guess, I would imagine that the USB-to-TTL IC's DTR line, or equivalent (?), is [logically] tied to the Arduino's RST line, so that if the PC tries to communicate to the XBee, it ends up resetting it, rather than signalling to the XBee that it is ready to communicate.
Note: The USB-to-TTL IC could be a FTDI, ATmega 4U2/8U2/16U2 or an FTDI clone, depending on the variety of Uno that you possess.
Addendum
I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer,  XBee USB Adapter Bluetooth Bee FT232RL USB to Serial Port Module for PC Arduino, is good value for money and compatible with WinTel, LinTel and OS X machines:

About the microswitch- I do have it on the shield! It can either be set to micro or usb, but i've tried both of them and X-CTU still did not find the Arduino.. I guess the best I can do right now to use Xbee for my project is to just restart the board all the time to configure the xbee and then remove the wire from gnd to reset and see where that takes me... Hopefully i'll be able to use it in some way...

@L2PA - Interesting, so in that case the Arduino forums link in my answer, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal, is applicable to you. I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer is good

Sorry for late response. I'll check out the links later and let you know if it worked. ;)

I guess I understood that there's no other way how I'll be able to access the Xbee without resetting the board (because of the resources that I have). Thanks for the answer and research you did!


text:
Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE?
In Arduino Eclipse (v3, nightly build) I have not been able to load 'foreign' libraries, those written by me or someone else, so they are not among the available choices in the include-library dialogs.
I've tried adding them to a project as well as adding them as an available library resource using the built-in dialogs for doing so, but I don't see a way to select a library that isn't already included in those dialogs.
My ideal case would be a way for the Arduino Eclipse plugin to use the same boards and libraries as I use in my Arduino IDE installation, so that:

An upgrade to the Arduino IDE would simultaneously upgrade the core libraries in Eclipse;
An optional library would need installing in only one place;
Modifying an optional library would only need to be done once, in one place.

The goal, as in an earlier question of mine, is to seamlessly permit using either IDE to advance a project. However, I'd be grateful to be able to add to my Eclipse installation any library of my choosing.

I fear that what you want is not 100% possible.
For libraries I am 100% sure it will work but the problem is the platforms.
UPDATE arduino IDE (no longer)? decompresses libraries and as such the libraries are unusable in Sloeber.
Lets start with the Libraries
What you do is:
In arduino eclipse ide remove all libraries from the library manager.
In windows->preferences->arduino->"private libraries path" add the libraries folder in the arduino IDE install and add the libraries folder in the arduino15 folder maintained by the library manager.
It is important to point to the parent folder containing the libraries. All subfolders are assumed to be libraries.
Then the boards
The problem here is that the boardsmanager adds environment variables to link boards to tools. You may have read remarks about A.RUNTIME.TOOLS.AVR-GCC.PATH and A.RUNTIME.TOOLS.AVRDUDE.PATH not being defined. Well it is the boardsmanager that maintains these based on json file content.
If you can limit yourself to 1 version of AVR, SAM, AVRDUDE, BSON,... tool chain you can "make it work" as follows:
Step 1: Keep as little boards as possible installed. You have to keep at least 1 or the plugin will reinstall the AVR boards of Arduino when started.
Step 2: In windows->preferences->arduino->"private hardware path" add the hardware folder in the arduino IDE install and add the packages folder in the arduino15 folder maintained by the Arduino IDE boards manager.
Step 3: Recreate the project in eclipse as described in your other question.
Step 4: If the build fails modify the [eclipse installation]/arduinoPlugin/post and pre processing files to try to get it to work.
Step 5: in project properties->Arduino select apply and OK (this will take your changes in step 4 into account)
Step 6: Goto Step 4
Good luck
Jantje

This works - except for one library set (Blynk) - but I was surprised that #include <someLibrary.h> was not sufficient; that the library had to be imported as well. In the Blynk librarycase, their example program compiles in the Arduino IDE but Eclipse complains that it can't find a Blynk.begin() with a signature matching the call from the example program.

About the boards: Does that mean I can't compile the same code for either an Uno or a Mega2560 at will? Or I can, but not if I upgrade the Arduino IDE (currently v1.6.7 with eclipse plugin 'mac64.2016-03-23_03-43-04')?

The way Arduino IDE finds libraries is different from the Arduino eclipse ide. This may explain why Blynk was not found and needed to be imported. The Arduino IDE searches the content of the library folders for (header)files matching your include. The Arduino eclipse plugin finds libraries based on foldername=include -".h"

I do not understand your board question.

.h files: Are you saying quoted .h file names will be found automatically but bracketed ones won't?  -- Boards: You wrote "For libraries I am 100% sure it will work but the problem is the platforms." and described some limitations due to the board manager. I didn't understand what the consequences are or when they might happen.

Making Blynk libraries, v0.3.6 and (presumably) later, Eclipse compatible.
With much help from Jantje (thank you!), I found 4 easy steps that make the Blynk v0.3.6 libraries Eclipse-compatible:

Create .../libraries/Blynk/Blynk.h (may be empty) and #include it before including any Blynk libraries.
Likewise, create and #include .../libraries/BlynkESP8266_Lib/BlynkESP8266_Lib.h
Delete the entire folder .../libraries/Blynk/linux (unless you're running Linux! In which case, some more discovery needs doing.)
In Blynk projects previously imported to Eclipse Arduino, delete the (possibly hidden) file .ino.cpp and do a clean build.

This recipe works for me under MacOS 10.11.5, the Eclipse Arduino IDE nightly build, and ArduinoIDE version 1.6.9. It should be reproducible by anyone wishing to compile Blynk programs in Eclipse. Under OSes other than Mac, especially linux, step 3 may need to be modified. I deleted the linux folder to prevent Eclipse from compiling main.cpp and BlynkDebug.cpp from there which was resulting in multiple definition errors at link time.
The above is an excerpt from a how-to I posted to the Blynk community but I think this has all of the relevant information.


text:
LED and LCD game
I am making a game where four different colored LEDs are flashing randomly, and when the green LED lights up, the user presses a button. If the user pushes the button when the LED is green, I want my 16x2 LCD screen to record points. And when the user presses the button on the wrong LED, i want the LCD screen to start over at "0 points."
Can you give me some place to start on a code that will feed "data" from  each time the button is pushed to the LCD screen?

Welcome to Arduino SE! Could you please explain further what have you triedand did the examples work that are included with the LCD library?

You need an example that shows you how to right to a screen and an example that shows you how to detect a button press, also you need to be able to light LEDs.  These are all examples supplied with the Arduino IDE, are you using that?  Look at each example in turn, setup the circuit get to understand them, then disect them and understand how they work and can get them to do what you want.
Button presses can be trouble some, you may need to investigate denouncing, either software or hardware.
Hope that gives you a starting point.


text:
"Return" Code Not Working
I'm trying to experiment with a "return" function. Yet each time I try to run my program, there happens to be an error, like "expected declaration before '}' token."
Can someone explain the basics of a return function, and look at my code below to possibly see what the problem could be?
{
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;
else{

return 0;
 }
}

What is the line int checkInput(); supposed to achieve?

return isn't a function, it's a statement. In case the answers didn't make it clear, you change int checkInput(); to checkInput();

It has nothing to do with the retun statements. You have to close each { with a }. you are missing one.
   {
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;}
else{

return 0;
 }
}

That piece of "code" is, I am afraid to say, complete gibberish.
Passed through Artistic Style to reformat it ends up with:
{
    int index;

    pinMode(10, INPUT); //button input

    int checkInput();

    if (digitalRead(10) == 0) {
        return 1;
        else {
            return 0;
        }
    }

Starting from the top of the program the errors are:

You have a bracket hanging at the front of the snippet for some reason
int checkInput(); is a function prototype (forward declaration) and doesn't do anything other than tell the compiler that you will define this function somewhere else in your sketch.
You are lacking the balancing bracket for the first portion of your if statement, so your else { return 0; } never runs.
There is no balancing bracket for the strange one by itself at the start of the snippet.

In short, I have a feeling you need to learn the basics of C syntax.

authors: مؤسسة الصيعري


text:
How to Determine Fuse Settings
I bought an arduino compatible board here: http://unsigned.io/projects/micromodem/
and am trying to flash new supported firmware onto it. The only instructions given to flash the board is to use the command avrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -F -U flash:w:YourFirmwareFile.hex .
I'm trying to follow the tutorial here using an Uno as a programmer: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader#uploading-code---hard-way but I don't know what to use for the fuse settings. I've tried a few different fuse settings such as the one for the Uno, and default 328p ones using a fuse calculator but it seems like they all have unpredictable results. Some fuse settings make it so that I can't connect  to the COM port at all to monitor the traffic, and others let me connect, but send a message of . I'm expecting an introduction message from the firmware that is supposed to be built in.
Thanks for the help.

Hi, I like to use a gui front for avrdude called avrdudess it might help you read the fuse settings from your modem board. Also remember that fuses are inverted, meaning a 0 means activated.

Hey, thanks for the response. I'll definitely check this out as it seems easier, but I'm trying to figure out what settings to use that would work my with the new firmware. I don't think reading the current fuse settings off of the board would help very much unless I had a working one already. Unless I'm understanding what you're saying incorrectly.

Ok, what do you want your fuse settings to do? Are you using a crystal? Do you need power brownout? Do you want to lock your chip from ever being programmed again. There is many settings in the fuses that can mess things up so please tell us what you want and why, and we'll try to help.

I don't really have any information other than the board and the specs of the board. I would like to load a different MicroAPRS firmware than the current one that is on the board and listed on the same project link above. To load that firmware I was trying to find the appropriate fuse settings so that I could get information from the serial port, as well as load my own programs on the board.

Normally you don't need to change the fuse settings, this configuration should be fine with the default arduino setting of
lowfuse=0xff
highfuse=0xde
extendedfuse=0x05
Serial should work fine.

I tried using those fuses. Here is a link to the pictures of what I am trying and the result is the serial port is always busy.
https://imgur.com/a/dU71h
I changed the baud rate that was given for flashing the modem (115200) to (19200) because every time I used 115200 I would get an Out of Sync() error and it wouldn't do anything.

Not sure if you can change fuse settings by serial programming...