text:
How to connect an industrial sensor to Arduino Uno?
I want to use a sensor to read pressure in rooms. But sensor like MPX series isn't capable to read air pressure change under 100 Pa. So I want to use industrial sensor like Dwyer 607 Series, and dont have a clue how to connect it to arduino. Anyone can help?
Thanks :)
Fyi, this is the manual instruction for the sensor http://www.dwyer-inst.com/PDF_files/E_76_low.pdf

here is a tutorial which explains how you can connect 4-20mA industrial sensors with Arduino.
How to interface 4-20mA with arduino

That uses the industry standard 4-20mA current loop system. For that you really need a special chip to interface it.
You can buy shields that interface to 4-20mA current loops.


text:
How to increase life of EEPROM?
I want to store a few (8 as of now) IR codes into my Board's EEPROM.
It would be great if someone could suggest a few tips to maximize the lifetime.
The IR codes in my sketch are saved in array of unsigned longs.
I know that the count of times that I will be writing to EEPROM will << 100,000 times, but still would like to optimize my sketch. + would help in future projects

Just out of interest, I tried to "wear out" my EEPROM a while back. It took something like 1.5 million writes before it started to fail.

@NickGammon, what were the failures like?  Random data?

One bit failures, from memory.

It's possible that if you exceed the specifications the memory might become less reliable. I didn't test that. Conceivably you might find that, after a month, a bit would change. My own findings were that you could exceed the recommended ratings by a substantial amount, and still read back the byte you wrote, a moment later.

I can think of a few:

don't power it on unless you have to;
don't write to it unless you have to;
write as little data to you as you can - compress the data; only write to it during brown out or power down, ...;
level the writes to as many cells as possible - increment the write address with subsequent writes;
use a big eeprom;
use fram;
use sram + battery back-up;

...
3 - 7 are really examples of implementating #2.

The other answer mentioned some general ideas; here are a couple of more-specific notes.
• You can direct your writes of single bytes through a routine that reads the EEPROM cell before writing to it, and if its value isn't changing, doesn't write.
• For load-leveling, you can divide the EEPROM address space into k buckets, where k =⌊E/(n+1)⌋, with n = data array size and E = EEPROM size.  Initialize a directory, an array of m bytes all set to k, with m = E-n·k.  When your device starts up, it reads through the directory until it finds current entry, a byte not equal to k. [If all directory entries equal k, initialize the first to 0, and go on from there.]  If the current directory entry contains j, then bucket j contains current data.  When you need to write new data, you store j+1 into the current directory entry; if that makes it equal to k, initialize the next directory entry to 0, and go on from there.  Note that directory bytes get about the same amount of wear as bucket bytes because 2·k > m ≥ k.

Thanks, I will try and implement load-leveling to my sketch also. Great explanation.
I do check if the values are same before writing, so that part is taken care of.

If your data occupies only a small fraction of your EEPROM, you could use one of the wear leveling algorithms. The essence of these algorithms is to write to a different location each time, so writes are spread across several locations while each location stays below the 100,000 writes limit.
There are several such algorithms discussed here, which you could implement yourself. Alternatively, you could just use a library like this one.

These are great links Dmitry! Thanks.
Anyways, now I am using ~the entire EEPROM for data. Write operations are rare in my code and only happen during the start of the lifecycle (configuration period of my device). The lifecycle mostly consists of only read operations.
As the size of my config-files is increasing I am now looking for memory-optimization techniques to fit all that in the EEPROM and no go for any additional storage.

I believe there's a simple way to use only n cells and a single dedicated bit pattern to achieve n/2 increase in durability.
The dedicated bit pattern (e.g. 0xffff) is a marker which indicates an unused cell, and in normal operation at most one cell at a time has this value:
uint16_t readWord (const uint16_t *address);
void writeWord (uint16_t *address, uint16_t value);

#define CELL_COUNT   42
#define BASE_ADDRESS 12
#define MARKER       0xffff  // Best to use EEPROM default for this

static uint8_t curCell = 0;

static void wlInit (void)
{
  for ( uint8_t ii = 0 ; ii < CELL_COUNT ; ii++ ) {
    if ( readWord (BASE_ADDRESS + ii) != MARKER ) {
      curCell = ii;
      // No early return/break here to keep init() execution time
      // constant.  Could also check for corruption here by checking for
      // > 1 cells with MARKER (see below).
    }
  }
  // If we didn't find a non-marker cell we'll end up with curCell = 0
  // per the initial value of curCell
}

static uint16_t wlRead (void)
{
  return readWord (BASE_ADDRESS + curCell);
}

static void wlWrite (uint16_t value)
{
  assert (value != MARKER);   // Storing marker value is big no-no

  uint8_t nextCell = (curCell + 1) % CELL_COUNT;
  writeWord (BASE_ADDRESS + nextCell, value);
  writeWord (BASE_ADDRESS + curCell, MARKER);
  curCell = nextCell;
}

The same approach can be used with structured data provided a bit pattern can be reserved (either in a dedicated byte or from some other field that has a spare pattern).
This approach also has a useful property with respect to interrupted (e.g. power drop) writes: if there are ever two cells without the MARKER value an incomplete (i.e. corrupted) write has occurred. This seems useful, because e.g. the ATmega328P datasheet contains the following unclear and not-particularly-reassuring paragraph about using brown-out detection to avoid corruption:

Keep the AVR RESET active (low) during periods of insufficient power
supply voltage. This can be done by enabling the internal Brown-out
Detector (BOD). If the detection level of the internal BOD does not
match the needed detection level, an external low V CC reset
Protection circuit can be used. If a reset occurs while a write
operation is in progress, the write operation will be com- pleted
provided that the power supply voltage is sufficient.

source: Stack Exchange

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

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

sort: votes


text:
How to connect to pins when using I2C LCD shield?
How are pins used with this shield? The tutorial says that the header pins are inserted into the Arduino but the guide says they are not used for signals. Is there any way of using the other pins?

Update:

What it means is although all pins from the Arduino are connected only A4, A5 5V and Gnd are actually used by the shield.  I think that these 4 pins are shared with other shields and all the rest of the pins are available for shields to either share or use exclusively.
So, if you have this shield and an Ethernet shield, which needs exclusive access to pins d7, d8 and d9 then you would be to use both shields at the same time.

So it's not possible to use the other pins with this shield?

I think it is, I've edited the answer to make that clearer.

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


text:
WS2812B strip stopped responding to control
I have a WS2812B LED strip (A clone of the Adafruit one I assume, it's from China via eBay) of 60 LEDs. When I got it, it was all fine - I could load the FastLED examples and they would work perfectly. I then tried to write something more custom, which didn't work for whatever reason. Upon re-loading the FastLED examples, I now get absolutely nothing from the strip.
It's being powered by an ATX computer power supply with ample amperage on 5V, and when I remove and then re-add the power connectors the strip does flash, indicating it's getting power and is capable of lighting up. It just feels like something I have done has caused it to enter a state where it won't respond to control.
I've also made sure my sketches are making it to the arduino by loading the inbuilt LED blink sketch, which works, then trying to switch back to a FastLED example which does nothing.
I'm kind of lost as to what could be wrong here.

Does it work if you connect data line to another pin, changing sketch to match?  Is ground still connected?

I have tried multiple pins, and yes - have ensured power, data and ground connections are solid. Very unusual.

Do you have a way to detach a front segment of LEDs, ie, attach to data a little ways into the strip?  And what was the name or nature of the  “something more custom” ?

Can you check the voltage at the end of the strip? And can you look with an oscilloscope the data line after a couple of leds?

If I was the kind of person who has an oscilloscope I suspect I wouldn't have managed to destroy this strip. :)
Good troubleshooting info though.

I'm in the same situation, so what happened?

@AkınCanŞENOL: the most common error could be to have 2 separate power suppy (one for the Arduino or Arduino over USB and one for the strip) and not connect together the ground

Did you follow the Adafruit NeoPixels best practices guide?
You may have zapped the first NeoPixel in the group. You should be able to, fairly easily, bypass that. Each NeoPixel has to "reshape" the data for the next one along, so if you damage the first one, no data will reach the others.
I strongly suggest you follow the guidelines in the link, including the capacitor and resistor.

Uh, no. I have never seen that page before. As noted, I got these from eBay and instructions were not something they came with. Good to know! I'll try bypassing the first LED and using the instructions listed and get back to this question when I determine if that was it...


text:
Attiny85 DigiSpark: Drive 128X64 OLED screen, no picture problem
Devices used
It's about these devices:

Quick scheme (how I connected those)

Got the wiring info from the TinyWire library

Program I use (also many different examples tried but no luck):
#include <Wire.h>

//~ DEFINES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Some defines for the SSD1306 controller driving a 128x64 resolution OLED display
// PART     - http://www.simplelabs.co.in/content/96-blue-i2c-oled-module
// DATASHEET  - https://www.adafruit.com/datasheets/SSD1306.pdf

// The Slave Address (SLA) of the OLED controller - SSD1306 - is 0x3C
// The LSB is supposed to be the mode. Since we are only going to WRITE to the OLED, the LSB is going to be 0
// SLA (0x3C) + WRITE_MODE (0x00) =  0x78 (0b01111000)
#define OLED_I2C_ADDRESS   0x3C

// The SSD1306 datasheet (pg.20) says that a control byte has to be sent before sending a command
// Control byte consists of
// bit 7    : Co   : Continuation bit - If 0, then it assumes all the next bytes are data (no more control bytes).
//        :    You can send a stream of data, ie: gRAM dump - if Co=0
//        :        For Command, you'd prolly wanna set this - one at a time. Hence, Co=1 for commands
//        :    For Data stream, Co=0 :)
// bit 6      : D/C# : Data/Command Selection bit, Data=1/Command=0
// bit [5-0]  : lower 6 bits have to be 0
#define OLED_CONTROL_BYTE_CMD_SINGLE  0x80
#define OLED_CONTROL_BYTE_CMD_STREAM  0x00
#define OLED_CONTROL_BYTE_DATA_STREAM 0x40

// Fundamental commands (pg.28)
#define OLED_CMD_SET_CONTRAST     0x81  // follow with 0x7F
#define OLED_CMD_DISPLAY_RAM      0xA4
#define OLED_CMD_DISPLAY_ALLON      0xA5
#define OLED_CMD_DISPLAY_NORMAL     0xA6
#define OLED_CMD_DISPLAY_INVERTED     0xA7
#define OLED_CMD_DISPLAY_OFF      0xAE
#define OLED_CMD_DISPLAY_ON       0xAF

// Addressing Command Table (pg.30)
#define OLED_CMD_SET_MEMORY_ADDR_MODE 0x20  // follow with 0x00 = HORZ mode = Behave like a KS108 graphic LCD
#define OLED_CMD_SET_COLUMN_RANGE   0x21  // can be used only in HORZ/VERT mode - follow with 0x00 + 0x7F = COL127
#define OLED_CMD_SET_PAGE_RANGE     0x22  // can be used only in HORZ/VERT mode - follow with 0x00 + 0x07 = PAGE7

// Hardware Config (pg.31)
#define OLED_CMD_SET_DISPLAY_START_LINE 0x40
#define OLED_CMD_SET_SEGMENT_REMAP    0xA1
#define OLED_CMD_SET_MUX_RATIO      0xA8  // follow with 0x3F = 64 MUX
#define OLED_CMD_SET_COM_SCAN_MODE    0xC8
#define OLED_CMD_SET_DISPLAY_OFFSET   0xD3  // follow with 0x00
#define OLED_CMD_SET_COM_PIN_MAP    0xDA  // follow with 0x12

// Timing and Driving Scheme (pg.32)
#define OLED_CMD_SET_DISPLAY_CLK_DIV  0xD5  // follow with 0x80
#define OLED_CMD_SET_PRECHARGE      0xD9  // follow with 0x22
#define OLED_CMD_SET_VCOMH_DESELCT    0xDB  // follow with 0x30

// Charge Pump (pg.62)
#define OLED_CMD_SET_CHARGE_PUMP    0x8D  // follow with 0x14

// NOP
#define OLED_CMD_NOP          0xE3

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Box pattern
uint8_t pattern1[] = {
  0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00,
  0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00
  };

// Cross weave pattern
uint8_t pattern2[] = {
  0x81,0x42,0x24,0x18,0x18,0x24,0x42,0x81,
  0x81,0x42,0x24,0x18,0x18,0x24,0x42,0x81
  };

void setup()   {
  // Init the OLED controller
  OLED_init();
}

void loop() {
  // I2C
  Wire.beginTransmission(OLED_I2C_ADDRESS);
  Wire.write(OLED_CONTROL_BYTE_CMD_STREAM);
  Wire.write(OLED_CMD_SET_COLUMN_RANGE);
  Wire.write(0x00);
  Wire.write(0x7F);
  Wire.write(OLED_CMD_SET_PAGE_RANGE);
  Wire.write(0);
  Wire.write(0x07);
  Wire.endTransmission();

  for(uint16_t i=0;i<1024;i++){
    Wire.beginTransmission(OLED_I2C_ADDRESS);
    Wire.write(OLED_CONTROL_BYTE_DATA_STREAM);
      for (uint8_t x=0; x<16; x++) {
      // Wire.write(0b11000001);
      // Wire.write(0x81);
      // Wire.write(0x02);
      Wire.write(pattern1[x]);
      // Wire.write(pattern2[x]);
      i++;
      }
      i--;
      Wire.endTransmission();
  }

    delay(5000);

}

void OLED_init() {
  // Init the I2C interface (pins A4 and A5 on the Arduino Uno board) in Master Mode.
  Wire.begin();
  // keywords:
  // SEG = COL = segment = column byte data on a page
  // Page = 8 pixel tall row. Has 128 SEGs and 8 COMs
  // COM = row

  // Begin the I2C comm with SSD1306's address (SLA+Write)
  Wire.beginTransmission(OLED_I2C_ADDRESS);

  // Tell the SSD1306 that a command stream is incoming
  Wire.write(OLED_CONTROL_BYTE_CMD_STREAM);

  // Follow instructions on pg.64 of the dataSheet for software configuration of the SSD1306
  // Turn the Display OFF
  Wire.write(OLED_CMD_DISPLAY_OFF);
  // Set mux ration tp select max number of rows - 64
  Wire.write(OLED_CMD_SET_MUX_RATIO);
  Wire.write(0x3F);
  // Set the display offset to 0
  Wire.write(OLED_CMD_SET_DISPLAY_OFFSET);
  Wire.write(0x00);
  // Display start line to 0
  Wire.write(OLED_CMD_SET_DISPLAY_START_LINE);

  // Mirror the x-axis. In case you set it up such that the pins are north.
  // Wire.write(0xA0); - in case pins are south - default
  Wire.write(OLED_CMD_SET_SEGMENT_REMAP);

  // Mirror the y-axis. In case you set it up such that the pins are north.
  // Wire.write(0xC0); - in case pins are south - default
  Wire.write(OLED_CMD_SET_COM_SCAN_MODE);

  // Default - alternate COM pin map
  Wire.write(OLED_CMD_SET_COM_PIN_MAP);
  Wire.write(0x12);
  // set contrast
  Wire.write(OLED_CMD_SET_CONTRAST);
  Wire.write(0x7F);
  // Set display to enable rendering from GDDRAM (Graphic Display Data RAM)
  Wire.write(OLED_CMD_DISPLAY_RAM);
  // Normal mode!
  Wire.write(OLED_CMD_DISPLAY_NORMAL);
  // Default oscillator clock
  Wire.write(OLED_CMD_SET_DISPLAY_CLK_DIV);
  Wire.write(0x80);
  // Enable the charge pump
  Wire.write(OLED_CMD_SET_CHARGE_PUMP);
  Wire.write(0x14);
  // Set precharge cycles to high cap type
  Wire.write(OLED_CMD_SET_PRECHARGE);
  Wire.write(0x22);
  // Set the V_COMH deselect volatage to max
  Wire.write(OLED_CMD_SET_VCOMH_DESELCT);
  Wire.write(0x30);
  // Horizonatal addressing mode - same as the KS108 GLCD
  Wire.write(OLED_CMD_SET_MEMORY_ADDR_MODE);
  Wire.write(0x00);
  // Turn the Display ON
  Wire.write(OLED_CMD_DISPLAY_ON);

  // End the I2C comm with the SSD1306
  Wire.endTransmission();
}

Source: https://github.com/SonalPinto/Arduino_SSD1306_OLED/blob/master/oled_test/oled_test.ino

Other examples I have been tried:

http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/
http://www.instructables.com/id/ATTiny85-connects-to-I2C-OLED-display-Great-Things/

Question
What could be wrong, do I miss something inhere? Wires seems to be OK, do I use the correct pins (sometimes a little confusing on Attiny85, digital versus analog)? Tried also another OLED_I2C_ADDRESS, 0x3D instead of 0x3C but no luck at all. Tried both screen and both remain black.

Got scope pictures?

Nope, got no scope :-(

With I2C you always need pull up resistors on the data lines, otherwise nothing works.  Normally ones around 4.7K for a Uno, not sure what they should be for a Tiny.
If you are unsure about the I2C address get "I2CScanner" (An Arduino program) and that will tell you.

Ah, this is useful info, thanks! Got no 4,7K resistors but desoldered two from a spare board and guess what..... It works like a charm! Thank you very much for the execellent info. I'm happy, thumbs up!

Hmm not strictly true I've currently got mine working without resistors, and the screens I get often do work without them, for example the Arduino Nano and ESP8266/NodeMCU I have used without resistors.
I had a bit of a pain with this board, the drivers for Windows originaly not working or detecting the board correctly and then the board not seeing the OLED mine is the 128x32 version. I edited the code to reflect the screen size in the DigiSparkOLED.cpp
0xA8, 0x1F,      // Set multiplex ratio(1 to 64)

And change:
0xDA, 0x12,      // Set com pins hardware configuration

To:
0xDA, 0x02,      // Set com pins hardware configuration

Also on several sites it does say to use PINS SCL on P5 and SDA on P2 so if its not working maybe try that pinout. I used the one mentioned above and the I2C scanner is now seeing it on address 0x3C (I wouldn't try changing the address in my experience the pinout will be wrong)
Do your usual checks to see if the screen is drawing power on all lines with a multimeter, also run I2C Scanner program to see if it sees anything and if not then try the alternative pinout.

ESP8266/NodeMCU is another puppy comparing to the Attiny85, Attiny is very basic and limited. However it might work now, it can change when connecting more i2c peripherals or using longer wires. Also the pin versus GPIO naming isn't the same, see also: https://github.com/esp8266/Arduino/blob/master/variants/nodemcu/pins_arduino.h#L37-L59 . About the display, used a 128x64 oled and it feels very buggy, especially at boot, sometimes it works, sometimes it don't. The ESP8266 is very picky on timing. See my topic on this on stackoveflow when it is using the wire library:

https://stackoverflow.com/questions/48350250/i2c-communication-between-atmega328p-and-esp8266ex-can-only-send-8-bytes-bug


text:
How to interpret the data from GPS GY-NEO6MV2 using Arduino Uno?
I am trying to get GPS data from my GY-NEO6MV2, but the results are not readable with SoftwareSerial or other libraries. I have used the following code that has worked for others on the net, but I don't get any results from it. The GPS data appears perfectly in the serial monitor, but the interfaces such as SoftwareSerial fail to receive it. Instead, I receive a bunch of -1s. Here is the code:
#include "SoftwareSerial.h"

// Constants
#define txPin 1      //tx pin in GPS connection
#define rxPin 2      //rx pin in GPS connection

// Set up the GPS serial port
SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
// Variables
byte byteGPS = 0;
int i = 0;
int state = 0;
char dataGPG[100] = "";
char *pch;
char *GGA[15];
int sat = 0;
void setup() {
  //setup for Serial Port
  Serial.begin(9600);
  Serial.flush();
  //setup for GPS Serial Port
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  gps.begin(4800);
  gps.flush();
  //setup satellites signal
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  // Turn off the led until a satellite signal
}

void loop() {
  gps.flush();
  Serial.flush();
  Serial.println("Waiting GPS data...");
  // Prepare all for reading GPS Serial Port
  memset(dataGPG, 0, sizeof(dataGPG)); // Remove previous readings
  byteGPS = 0; // Remove data
  byteGPS = gps.read(); // Read the byte that is in the GPS serial port
  delay(1000);
  // Find the desired string
  while (byteGPS != '$') {
    byteGPS = gps.read();
   /******* Here I just get -1 *************/
  }
  // Save the string in an array
  i = 1;
  dataGPG[0] = '$';
  while (byteGPS != '*' ) {
    byteGPS = gps.read();
    dataGPG[i] = byteGPS;
    i++;
  }
  dataGPG[i] = '\0';
  string(); // Call to the function that manipulates our string
}

/*
  This function will allow us to identify the data we need to get the longitude, latitude ...
*/

void string() {
  i = 0;
  memset(GGA, 0, sizeof(GGA)); // Remove previous readings
  pch = strtok (dataGPG, ",");
  // Analyze the saved interval in pch to see if it the needed string
  if (strcmp(pch, "$GPGGA") == 0) {
    while (pch != NULL) {
      pch = strtok (NULL, ",");
      GGA[i] = pch;
      i++;
    }
    plot(GGA, "$GPGGA");
    // Call to the function that is going to display the data
  }
}

/*
  This function organize the gps data received for printing in the serial monitor.
*/

void plot(char **GGAPrint, char *trama) {
  state = atoi(GGAPrint[5]);
  sat = atoi(GGAPrint[6]);
  if (trama == "$GPGGA" && state == 1) {
    digitalWrite(13, HIGH);
    // Then there are satellites, the LED switch ON
    Serial.println("");
    Serial.println("----------------------------------------------");
    Serial.print("UTC Hour -> ");
    Serial.println(GGAPrint[0]);
    Serial.print("Latitude -> ");
    Serial.print(GGAPrint[1]);
    Serial.println(GGAPrint[2]);
    Serial.print("Longitude -> ");
    Serial.print(GGAPrint[3]);
    Serial.println(GGAPrint[4]);
    Serial.print("GPS quality: 0=null; 1=GPS fixed -> ");
    Serial.println(GGAPrint[5]);
    Serial.print("Number of satellites -> ");
    Serial.println(sat);
    Serial.print("Horizontal Dilution of Precision -> ");
    Serial.println(GGAPrint[7]);
    Serial.print("Antenna altitude -> ");
    Serial.print(GGAPrint[8]);
    Serial.println(GGAPrint[9]);
    Serial.print("Geoid Separation -> ");
    Serial.print(GGAPrint[10]);
    Serial.println(GGAPrint[11]);
    Serial.println("----------------------------------------------");
    Serial.println("");
  } else {
    // If no satellite connection
    digitalWrite(13, LOW); // Turn off the LED
    Serial.println("");
    Serial.println("-----------------------------");
    Serial.print("|--- Satellites Used -->");
    Serial.print(sat);
    Serial.println(" |");
    Serial.println("|----Waiting location----|");
    Serial.println("-----------------------------");
    Serial.println("");
  }
}

The result wasn't correct and I only saw this sentence:

Waiting GPS data...

I updated the code by adding gps.available() and delay(2) before every gps.read() and it worked. I still don't know why, but this worked:
#include "SoftwareSerial.h"

// Constants
#define txPin 2      //tx pin in GPS connection
#define rxPin 3      //rx pin in GPS connection
char gps_data[200];

SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
char byteGPS = 0;

void setup() {
  Serial.begin(9600);
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  gps.begin(9600);
}

void loop() {

  byteGPS = '0'; // Remove data
  memset(gps_data, '\0', 200);

  while (gps.available())
  {
    while (gps.available())
    {
      byteGPS = gps.read(); // Read the char that is in the GPS serial port
      if (byteGPS == '$') break;
    }
    int i=0;
    while (gps.available())  // Available3
    {
      delay(1);
      gps_data[i++] = byteGPS;
      byteGPS = gps.read();
      if ((byteGPS == '\n')) break;
    }
    if (i > 1)
    {
      delay(1);
      parse_gps_data();
    }
  }
}

The code in parse_gps_data() parses the data from gps. It works fine.

Do the flush calls in setup not in loop, or you'll loose data, possible the $ you are looking for.

Do you mean   "gps.flush()"    and  "Serial.flush()" ? I did, but I think this code has a bug and I can't understand very well, because when I reset the arduino I could see some numbers and strings ( those weren't correct actually) and It seems there is no loop!!

I mean both, but mainly gps.flush().  If you clear the input buffer that is receiving the GPS data every second or so its possible you will loose data.

I did it for both of them, but I don't know why I have to reset the arduino for receiving the data?

Your sketch has many problems:

The flush method waits for everything you have written to go out.  You haven't written anything to the GPS or Serial, so there's no reason to flush the output.  And you don't need to call it at the beginning of loop.

Calling delay is the surest way to lose GPS characters.  Never use delay in a GPS sketch.

You are calling read without calling available first.    Because you called delay, there are probably chars available, but not necessarily, and they will not be a complete sentence.  This explains the partial NMEA data in your question.

You are printing too much in the plot routine.  After 64 characters are printed (actually queued for printing), the Serial.print call must wait for some characters to be sent (making room in the output buffer). At 9600, each character takes 1ms to be sent.  During that time, the GPS device is still sending characters.  Eventually, the input buffer overflows and GPS characters are lost.  When properly structured (see below), there is barely enough time to print all those messages.

You have connected the GPS to pins 1 & 2, but pins 0 & 1 are the HardwareSerial pins (Rx & Tx), dedicated to Serial .  They are conflicting with each other, and may interfere with uploading new sketches via USB.

You do not have good satellite reception, according to the GPS data fragments you show.  Check the antenna, get near a window, or go outside.  It may take 10 minutes before a "fix" is acquired.

You are using SoftwareSerial for the GPS port.  SoftwareSerial is very inefficient, because it disables interrupts for long periods of time.  At 4800, the Arduino is dedicated to receiving each char for 2ms, an eternity for a 16MHz processor.  This will interfere with other parts of the sketch or other libraries.  This answer gives several alternatives, like AltSoftSerial, on different pins.

Solutions:
First, you have to get the hardware connections corrected.  The NEO-6M is a 3.3V device, so you shouldn't connect it directly to the 5V Arduino.  You could connect just the GPS TX to the Arduino, but you may not receive data reliably. Connecting an Arduino transmit pin to the GPS RX could damage the GPS module, as it is only rated for 3.6V MAX.  It is best to "level-shift" between the two devices.  You can use a few discrete parts (resistors + a diode, or resistors + FETs) or a level-shifting module.  I recommend the latter, because they are cheap, and they also work for high-speed interfaces like SPI.
When you have level-shifting ready to add, move the GPS RX & TX connections to Arduino pin 9 (to GPS RX) and 8 (to GPS TX).  This will let you use AltSoftSerial instead of SoftwareSerial.  If you configure the NEO-6M to run at 9600 (that is the default), you could use NeoSWSerial on any two pins (besides 0 & 1 !!!).  I'm not sure why your NEO-6M is running at 4800, unless you used the u-center utility to configure it permanently.
Finally, I would suggest trying my NeoGPS library.  It is smaller, faster and more accurate than all other libraries, and it includes distance and bearing calculations that you might eventually need.
The Installation instructions guide you through several examples, after which you should try NMEAloc.  NeoGPS also has a diagnostic program, and lots of tips on the Troubleshooting page.  You can download it from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.
After going through those first examples, you should be ready to try your own sketch.  Here is your sketch, modified to use NeoGPS and either AltSoftSerial, NeoSWSerial, or the built-in Serial1 on a Mega2560, Leo or Due:
// Set up the GPS serial port (pick *one* of these choices)

//#include <AltSoftSerial.h>
//AltSoftSerial gps_port; // always 8 & 9 on an UNO

//#include <NeoSWSerial.h>
//#define rxPin 2
//#define txPin 3
//NeoSWSerial gps_port( rxPin, txPin );

#define gps_port Serial1  // for a Mega2560, Leo or Due

// Variables
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#ifndef NMEAGPS_PARSE_GGA
  #error You must uncomment NMEAGPS_PARSE_GGA in NMEAGPS_cfg.h!
#endif

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

  gps_port.begin(4800); // 9600 is the default for NEO-6M

  //setup satellites signal
  pinMode(13, OUTPUT);

  // Turn off the led until a satellite signal
  digitalWrite(13, LOW);

  Serial.println( F("Waiting GPS data...") );
}

void loop() {
  while (gps.available( gps_port )) {
    fix = gps.read();  // a new fix structure has been parsed
    plot();
  }
}

/*
  This function organize the gps data received for printing in the serial monitor.
*/

void plot() {

  if (fix.valid.location) {
  // or if (fix.valid.status && (fix.status >= gps_fix::STATUS_STD)) {

    digitalWrite(13, HIGH); // Then there are satellites, the LED switch ON

    Serial.println();
    Serial.println( F("----------------------------------------------") );
    Serial.print  ( F("UTC Hour -> ") );
    if (fix.valid.time)
      Serial.println( fix.dateTime.hours );
    Serial.print  ( F("Latitude -> ") );
    Serial.println( fix.latitude(), 6 );
    Serial.print  ( F("Longitude -> ") );
    Serial.println( fix.longitude(), 6 );
    Serial.print  ( F("GPS status: 0=NONE; 1=EST, 2=TIME, 3=STD, 4=DGPS -> ") );
    if (fix.valid.status)
      Serial.print( fix.status );
    Serial.println();
    Serial.print  ( F("Number of satellites -> ") );
    if (fix.valid.satellites)
      Serial.print( fix.satellites );
    Serial.println();

    #ifdef GPS_FIX_HDOP
      Serial.print  ( F("Horizontal Dilution of Precision (x1000) -> ") );
      if (fix.valid.hdop)
        Serial.print( fix.hdop );
      Serial.println();
    #else
      #error You must uncomment GPS_FIX_HDOP in GPSfix_cfg.h!
    #endif

    Serial.print  ( F("Antenna altitude (m) -> ") );
    if (fix.valid.altitude)
      Serial.print  ( fix.altitude(), 2 );
    Serial.println();

    #ifdef GPS_FIX_GEOID_HEIGHT
      Serial.print  ( F("Geoid Separation (m) -> ") );
      if (fix.valid.geoidHeight)
        Serial.print  ( fix.geoidHeight(), 2 );
      Serial.println();
    #else
      #error You must uncomment GPS_FIX_GEOID_HEIGHT in GPSfix_cfg.h!
    #endif

    Serial.println( F("----------------------------------------------") );
    Serial.println();

  } else {
    // If no satellite connection
    digitalWrite(13, LOW); // Turn off the LED

    Serial.println();
    Serial.println( F("-----------------------------") );
    Serial.print  ( F("|--- Status -->") );
    if (fix.valid.status)
      Serial.print  ( fix.status );
    Serial.println();
    Serial.println( F(" |") );
    Serial.println( F("|----Waiting location----|") );
    Serial.println( F("-----------------------------") );
    Serial.println();
  }
}

Note: Using #if statements, it verifies the configurations in NMEAGPS_cfg.h and GPSfix_cfg.h.  The Geoid Height field is not enabled in the default NeoGPS configuration.

Since I am using Uno, is it ok to use Serial instead of Serial1?

This code causes an error error: ‘pgm_read_ptr’ was not declared in this scope which is a result of __AVR__ not being defined. Is there a work around to this? I tried defining it in GPSfix_cfg and NMEAGPS_cfg, but it didn't work.

What IDE version?  1.6.8 and 1.8.1 work fine for an UNO.  1.7.x did not compile, but it had a different error.  I've updated NeoGPS_cfg.h to accommodate 1.7.x (again :-/).

My IDE version is 1.6.X but I updated NEoGPS_cfg.h and now I see more errors.

Which IDE exactly?  (1.6.x could be any of 13 IDEs.)  What errors?  If it is about "hdop", you have to enable HDOP in GPSfix_cfg.h, too.  I've added that check to the above sketch.

I updated the IDE to 1.8 and I got it compiled with no errors. However, I still have exactly the same issue; I get no results. The problem is that the GPS output appears in the "Serial Monitor" correctly, but SoftwareSerial, NewSoftwareSerial and NeoSWSerial fail to get it and pipe it to my program. I get a bunch of -1 s instead of actual characters.

I updated my question. The problem is that I am receiving -1 in gps.read() since the buffer is empty.

So the NeoGPS program displays the GPS data in the Serial Monitor correctly?  What do you mean by "pipe it to my program"?  The NeoGPS program is reading gps_port correctly, parsing the characters, and filling out the fix structure.  Then it prints the parsed values to Serial, but you could do whatever you want with fix.latitude() (for example).  Your original program would never work, for the 7 reasons listed above.  The -1 you get from gps.read() is reason #3.  You only fixed reasons #1 and #2.

After I updated my arduino from 1.6 to 1.8 things have changed. Now, when I do byteGPS=gps.read() and Serial.print(byteGPS), it works perfectly and prints the gps data in Serial Monitor. However, when I put it in an array, some data goes missing. I am not sure if it is because of the speed of arduino uno, which is less than the gps data coming or not.

Also, when I use your code, it says that gps is not available, but when I use my code, the gps is available. I have already made that change in my code.

Let us continue this discussion in chat.

Sorry I couldn't make it to the chat. I updated the code once again and it worked. I just needed to put gps.available() and a delay before every gps.read(). However, your code still doesn't work on my device.


text:
Am I able to connect an anti static wrist strap to the ground pin on the Arduino uno?
So you have the pin on the arduino uno which is ground, are you able to use a jumper wire to send the ground source out the other end of the wire to the alligator clip for the antistatic wrist strap?

Maybe see Connect anti-static wrist strap to earth wire?

Like @NickGammon I exercise sensible precautions when handling electronic components. However I have NEVER used a wrist strap, and in over 40 years of designing and building microelectronics have NEVER damaged a chip with static (lots damaged with wrong voltages, wrong connections). If you are going to use one the 0V pins (incorrectly labelled Gnd), or any equivalent,  is the best option. Modern chips are a lot more robust than the 1970s vintage MOS chips.

I was about to write that I wouldn't do that, but in view of the post I linked to - I am changing my mind.
The point to the wrist strap it to have you, and the thing you are touching, at the same potential (whatever that is relative to the known Universe). Now if you connected the strap to the earth on your power point, that would not achieve anything unless your Arduino was also grounded (eg. via a USB cable).
So using the ground wire on the Arduino sounds sensible enough. Personally I don't usually do that, however if I have moved around (and might have shuffled over some carpet, etc.) I always touch some metal part to ground myself (for example, a metal switch on a lab power supply) and discharge any static that might have built up by moving around on the floor.


text:
Bluetooth signal returns 0
I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that  immediately it becomes 0.
Why does it become 0? And how can I get rid of that problem?
Here is my code:
int x,y;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0)
  {
    x=Serial.parseInt();
    y=Serial.parseInt();
    Serial.print("x:");
    Serial.print(x);
    Serial.print("\n");
    Serial.print("y:");
    Serial.print(y);
    Serial.print("\n");
  }
  else
  {
    ;
  }
}

and here is the result:

Serial.parseInt() has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, Serial.parseInt() will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs parseInt() just returns 0.
IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial here.


text:
Strange power comsuption into sleep mode
I've finished my project and now I'm measuring the current but there is something wrong. I'm using an Arduino Pro Mini board and the LowPower library but the consumption is about 3.5 - 5 mA and not less than 500 uA (the board remains into sleep mode almost all the time).
When I began to work with the board its LED was removed but I think that this work was not made correctly. How can I check that LED was removed correctly?
Thanks to all.
EDIT1: The strange power consumption is not associated with board's LED.
EDIT2: @Gerben has suggested me to review the state of SPI pins connected to the board. I use in this project a SD card module and GSM/GPRS module but the guilty of this excessive power consumption is the first. Then I've disconnected all SD card module's pins and then I get about 60 uA, so the problem is on those pins but I can't reduce the power consumption. SD card module pins are 10,11,12 and 13 so I've used statements like digitalWrite(10, LOW), digitalWrite(11, LOW) and so on after reading/writing on the SD card but it is useless.
EDIT3: I've decided to upload a representation of my project using Fritzing. The external modules are not identical but they contain the same pins.
General view of the circuit:.
Detail of the connections:

I use these external components:

SD card module
A6 GPRS/GSM module

In my project there are some important details:

GPRS module is powered individually. The other battery is dedicated to power on the Arduino board and the SD card module.
Batteries are 6v.
Transistors base are controlled by 2 and 3 digital pins respectively.
The 8 and 9 pins of the Arduino board act like RX and TX pins using AltSofSerial.h library.

See Power saving techniques for microprocessors for some tips. I doubt it is anything to do with the non-existent LED.

How would you remove an LED in such a way that the missing LED draws 5 mA? That doesn't make any sense. Either it is still there, or it is not there. If the removal shorted the pins then you would have a lot higher current drain than 5 mA.

@NickGammon I think that the problem is the SD card module because if I disconnect the CS, DI, DO and CK pins then the consumption is around the 60 uA.

@PinaGamer did you just disconnect those pins or also the VCC and GND pins of the SD card module? If you didn't, try leavinf those pins connected: if it is a module it should have an onboard converter and maybe a level shifter which remain powered (if it is the case, power it through an arduino pin and turn it off when not needed). If you only disconnected those pins and left VCC and GND connected, see with an oscilloscope if the status is changing. If it isn't, try measuring also the current sinked by the SD card (module) when in sleep

@frarugi87 I've only disconnected the pins that I mentioned above so VCC and GND remain connected. So do you recommend me remove the transistor and activate or deactivate the SD card module using a digital pin?

@PinaGamer what is the transistor you mentioned? I suggest you to 1) try measuring the current flowing in the SD module only when in sleep. 2) leave the SD module connected, but disconnect only VCC and measure the whole current. 3) post a link to the SD module you are using; maybe some other ideas can come.

@frarugi87 The consumption in your proposed cases are: 1) 4.8 mA 2) 3.9 mA. The SD card module is this.

Wait, you blocked the ground of the modules?? If so, try writing a HIGH value on all the SD card pins, not LOW (otherwise you are trying to power the device through the digital pins). And.. Consider using a PMOS instead to block the VCC pin...

digitalWrite(10, LOW) or better digitalWrite(10, HIGH) don't work if you don't disable SPI first.

@frarugi87 I don't understand why I need HIGH value instead of LOW value to switch off the SD card module. Why do I need a PMOS transistor?

@PinaGamer because if you switch off the transistor, every node on the SD should float up to VCC, the only remaining connection. If you apply a 0V on any pin, you put a differential voltage over the board, thus turning on something. Try with a high value (so everything is at VCC) or put the pins in high impedance (aka input mode). A PMOS transistor (or a PNP) is used to interrupt the VCC pin instead of the GND one, so you can keep the grounds together (it's usually a better approach, since usually grounds are designed to be together)

@Gerben Do you recommend me to put digitalWrite(10, HIGH) to enable the internal PULL-UP of this pin? Why? With this statement current goes down to 80 uA.

See frarugi87's comment. Nothing to do with pull ups

@Gerben frarugi87 suggests me put the pins in high impedance so in void setup() I've put digitalWrite(10, HIGH)

digitalWrite(10, HIGH) doesn't mean high impedance. High impedance if when you change the pin to an INPUT. So pinMode(10, INPUT). But I was referring to him saying you should set the pin to Vcc not GND. Also there is no point in doing this in setup. But please, re-read all the comments, cause I feel you are totally missing the points we are making.

If you considered your question answered, please accept an answer of post you own answer to close it.

SOLUTION [by OP]
My problem was that the SD card module was consuming when it was controlled by a transistor and my Arduino board was into the sleep mode. So I wrote into the void setup() the digitalWrite(PIN, HIGH) statements where PIN represents all pins connected to the board that belong to the SD card module (DI, DO, CS, and CK pins), to enable the internal resistor of that pins. Then, I checked the power consumption and I reached less than 100 uA.

If you physically removed the LED make sure the pads for it aren't shorted together by old solder. If they aren't then you removed it correctly.
However: 5mA may be a perfectly reasonable current consumption for your project. Without seeing a full schematic and analysing your code it's impossible to say what kind of current you would expect to see.

I've upload a simple project like this: #include <LowPower.h> void setup(){  LowPower.powerDown(SLEEP_TIME, ADC_OFF, BOD_OFF); } void loop(){ }
And the consumption is a bit less than 3.5 mA. So I think that the code is not the problem

Like what? Also, how are you powering the board?

I power the project using 4 AA batteries with 1900 mAh.

TBH I'd be less worried about the 5mA consumption that I would be by the 30% power loss from the linear regulator. What else is connected to the board?

Interesting... I've isolated the board, I've measured again the current and now I'm getting 60 uA. So the problem is in the circuit... There are connected an SD card and GSM modules both controlled using transistors.

@PinaGamer If you remove power using a transistor, you must also make sure not the the SPI/UART pins are HIGH. Otherwise power will flow into the modules via this pin (and the clamping diodes in the modules ICs).

@Gerben I use AltSoftSerial.h library to communicate with the GSM module using digital pins 8 and 9 and pin 10 to begin the SPI communication with the SD card module but there is no any statement like digitalWrite(8,HIGH) or something like that.

@PinaGamer I'm not going to read all the library code to figure out if an output is set to HIGH while idle. You can do this yourself. Or you can do it the easy way, and while the arduino is sleeping, disconnect the modules, and use a multimeter to see if any of the output-pins that where connected to the modules read 5v. I recently did a project where I had to disable SPI and set the MOSI pin low, before powering down the device connected to the SPI bus.


text:
I can't receive data from Arduino through Bluetooth
I am developing an app that controls an Arduino robot. For that I need to communicate through Bluetooth. That means sending and receiving data. Why receiving? Because I also have sensors on the robot. I am already able to successfully connect with the Arduino Bluetooth bridge and send data, but I can't receive data from the Arduino. If someone can help me, I will appreciate it.
Here is the  main Java code:
public class MainActivity extends AppCompatActivity {
    Button  forward_btn, forward_left_btn, forward_right_btn, reverse_btn, reverse_right_btn, reverse_left_btn, btnConexao, turbo;
    public static final int SOLICITA_ATIVACAO = 1; // é o codigo numero 1, é diferenciado o codigo pq pode haver varias solicitações na msma tela
    public static final int SOLICITA_CONEXAO = 2;
    BluetoothAdapter meuBluetoothAdapter = null; //declarar o meu adptador bluetooth
    BluetoothDevice meuDevice = null;
    BluetoothSocket meuSocket = null; // faz transiçao dos dados
    TextView myLabel;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    volatile boolean stopWorker;
    boolean conexao =  false; //variavel para a conexao que indica se a conexao está em andamento ou nao
    private OutputStream outputStream  ;
    private static String MAC = null;
    private  InputStream mmInputStream;
    final int RECIEVE_MESSAGE = 1; // Status  for Handler
    Handler h;
    private StringBuilder sb = new StringBuilder();
    byte [] command = new byte[256]; //string variable that will store value to be transmitted to the bluetooth module
    UUID MEU_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // canal de comunicaçao bluetooth, UUID- ID do canal
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      forward_btn = (Button) findViewById(R.id.forward_btn); //definir botoes e associar ao ficheiro xml
      forward_left_btn = (Button) findViewById(R.id.forward_left_btn);
      forward_right_btn = (Button) findViewById(R.id.forward_right_btn);
      reverse_btn = (Button) findViewById(R.id.reverse_btn);
      reverse_left_btn = (Button) findViewById(R.id.reverse_left_btn);
      reverse_right_btn = (Button) findViewById(R.id.reverse_right_btn);
      btnConexao = (Button) findViewById(R.id.btnConexao);
      turbo = (Button) findViewById(R.id.turbo);
      myLabel = (TextView) findViewById(R.id.label);
      forward_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) { // comandos bluetooth correspondentes do arduino
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "1".getBytes();
              try {
                outputStream.write(command); //transmite o valor do comando para o modulo bluetooth
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      reverse_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "2".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
              }
            }
          }
          return false;
        }
      });

      forward_left_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "3".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
              }
            }
          }
          return false;
        }
      });

      forward_right_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "4".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      reverse_left_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "5".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      reverse_right_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "6".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      turbo.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "9".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      meuBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //obter o adaptador do dispositivo e definir como meubluetoothADpt
      if (meuBluetoothAdapter == null) { //se o adptador for "null", ou seja nao tem adptador
        Toast.makeText(getApplicationContext(), "O seu dispositivo nao possui bluetooth", Toast.LENGTH_LONG).show();
      } else if (!meuBluetoothAdapter.isEnabled()) { // != não, so o bluetooth nao tiver ativao, pedir permissão
        Intent ativaBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(ativaBluetooth, SOLICITA_ATIVACAO);
      }

      btnConexao.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          if (conexao) {
            try {
              meuSocket.close();
              conexao = false;
              btnConexao.setText("Conectar");
              Toast.makeText(getApplicationContext(), "Bluetooth foi desconectado", Toast.LENGTH_SHORT).show();
            } catch (IOException erro) {
              Toast.makeText(getApplicationContext(), "Ocorreu um erro ao desconectar:", Toast.LENGTH_SHORT).show();
            }
          } else {
            Intent abreLista = new Intent(MainActivity.this, ListaDispositivos.class);
            startActivityForResult(abreLista, SOLICITA_CONEXAO);
          }
        }
      });
    }

    void beginListenForData () {
      final Handler handler = new Handler();
      final byte delimiter = 10; //This is the ASCII code for a newline character
      stopWorker = false;
      readBufferPosition = 0;
      readBuffer = new byte[1024];
      workerThread = new Thread(new Runnable() {
        public void run() {
          while (!Thread.currentThread().isInterrupted() && !stopWorker) {
            try {
              int bytesAvailable = mmInputStream.available();
              if (bytesAvailable > 0) {
                byte[] packetBytes = new byte[bytesAvailable];
                mmInputStream.read(packetBytes);
                for (int i = 0; i < bytesAvailable; i++) {
                  byte b = packetBytes[i];
                  if (b == delimiter) {
                    byte[] encodedBytes = new byte[readBufferPosition];
                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                    final String data = new String(encodedBytes, "US-ASCII");
                    readBufferPosition = 0;
                    handler.post(new Runnable() {
                      public void run() {
                        myLabel.setText(data);
                      }
                    });
                  } else {
                    readBuffer[readBufferPosition++] = b;
                  }
                }
              }
            } catch (IOException ex) {
              stopWorker = true;
            }
          }
        }
      });
      workerThread.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      switch (requestCode) {
        case SOLICITA_ATIVACAO:
          if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(getApplicationContext(), "O Bluetooth foi ativado", Toast.LENGTH_LONG).show();
          } else {
            Toast.makeText(getApplicationContext(), "O bluetooth nao foi ativado, App será encerrada", Toast.LENGTH_LONG).show();
            finish();
          }
          break;
        case SOLICITA_CONEXAO: // pede resultado da solicitaçao, se nao obter o resultado exibe toast
          if (resultCode == Activity.RESULT_OK) {
            MAC = data.getExtras().getString(ListaDispositivos.ENDERECO_MAC);//vai buscar info à lista, ao ENDERECO_MAC
            meuDevice = meuBluetoothAdapter.getRemoteDevice(MAC); // obtem dispositivo remoto atraves do MAC
            try { // tenta a conexao
              meuSocket = meuDevice.createRfcommSocketToServiceRecord(MEU_UUID); // cria um canal de comunicaça0 Rfcomm
              meuSocket.connect(); // tenta conexao  exibre
              try {
                outputStream = meuSocket.getOutputStream();
              } catch (IOException e) {
                e.printStackTrace();
              }
              try {
                mmInputStream = meuSocket.getInputStream();
              } catch (IOException e) {
                beginListenForData();
                e.printStackTrace();
              }
              conexao = true; // apos conectado, passa a true
              btnConexao.setText("Desconectar");
              Toast.makeText(getApplicationContext(), "Você foi conectado com" + MAC, Toast.LENGTH_SHORT).show();
            } catch (IOException erro) { // se falhar conexao exibe
              conexao = false;
              Toast.makeText(getApplicationContext(), "Ocorreu um erro:" + erro, Toast.LENGTH_SHORT).show();
              //retirar o "+erro" se for publicada a app
            }
          } else {
            Toast.makeText(getApplicationContext(), "Falha ao obter o mac", Toast.LENGTH_SHORT).show();
          }
      }
    }
}

This is the code I added in order to receive data:
  void beginListenForData () {
  final Handler handler = new Handler();
  final byte delimiter = 10; //This is the ASCII code for a newline character
  stopWorker = false;
  readBufferPosition = 0;
  readBuffer = new byte[1024];
  workerThread = new Thread(new Runnable() {
    public void run() {
      while (!Thread.currentThread().isInterrupted() && !stopWorker) {
        try {
          int bytesAvailable = mmInputStream.available();
          if (bytesAvailable > 0) {
            byte[] packetBytes = new byte[bytesAvailable];
            mmInputStream.read(packetBytes);
            for (int i = 0; i < bytesAvailable; i++) {
              byte b = packetBytes[i];
              if (b == delimiter) {
                byte[] encodedBytes = new byte[readBufferPosition];
                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                final String data = new String(encodedBytes, "US-ASCII");
                readBufferPosition = 0;
                handler.post(new Runnable() {
                  public void run() {
                    myLabel.setText(data);
                  }
                });
              } else {
                readBuffer[readBufferPosition++] = b;
              }
            }
          }
        } catch (IOException ex) {
          stopWorker = true;
        }
      }
    }
  });
  workerThread.start();
}

Can you receive data through bluetooth using a standard terminal emulator program?

I used the "Bluetooth terminal " to check if the arduino is sending data , and it is working well but i can't receive it in my app .

So it sounds like it's something Android specific then - you may be better off asking on an Android site where they have more Android knowledge.

You were right , the problem was it the arduino code , thank you for your time.


text:
DS18B20 and Arduino - Internall Pull-Up
Can this DS18B20 sensor be used with Arduino internal pull-up or it require exactly 4.7k pull-up resistor?

The Arduino internal pull-up is something like 50k. That is a lot different from 4.7k. You would probably find that the pull-up is not strong enough to get clean pulses from the device. Also if you are using it in one-wire (parasitic) mode notice this from the datasheet:

To assure that the DS18B20 has sufficient
  supply current, it is necessary to provide a strong pullup on the 1-Wire bus whenever temperature
  conversions are taking place or data is being copied from the scratchpad to EEPROM.

Notice the words 'strong pullup'. The internal pullup is not strong.

Yeah you are right. Also I find out that these internal pull-ups depends also from type of Arduino (Uno, Nano, Mega etc.) so they have different values as well.

It varies from chip to chip in the same family, and even pin to pin depending on what other functions the pin has. Last time I measured them on a range of chips they varied from about 25k to 40k

If the datasheet specifies a 4.7kΩ resistor then a 4.7kΩ resistor is what you need.

Do people not like the fact that the datasheet knows best? They don't put these things in datasheets for fun you know.

4.7kΩ is a great starting point, but you should choose differently depending on your supply voltage. At 5V with 4.7kΩ pullup, the device has to sink about 1mA to pull the line low. If instead you're operating at 3.3V you should use 2.7kΩ to sink the same current.


text:
Why is the stack pointer out of range?
I have a function that dumps the contents of the arduino's ram, and it works, but I still dont understand why it says my stack pointer is at 0x08C9 If the ram of the arduino is 2kb, or 2048 bytes, shouldent the max addressable size be 0x0800?
RAM: SP->0x08C9 HP->0x0371 FREE:1368

And the code:
void printAddress(uint16_t val)
{
  Serial.print(F("0x"));
  if(val < 16)
{
 Serial.print(F("0"));
}
if(val < 256)
 {
  Serial.print(F("0"));
}
if(val < 4096)
{
  Serial.print(F("0"));
}
Serial.print(val,HEX);
}

void setup(){
Serial.begin(115200);
//0x0800 2048
uint8_t *heapptr, *stackptr;
stackptr = (uint8_t *)malloc(4);        // use stackptr temporarily
heapptr = stackptr;                     // save value of heap pointer
free(stackptr);                         // free up the memory again (sets stackptr to 0)
stackptr =  (uint8_t *)(SP);            // save value of stack pointer

Serial.print(F("RAM: SP->"));
printAddress(stackptr);
Serial.print(F(" HP->"));
printAddress(heapptr);//(int)&__heap_start);
Serial.print(F(" FREE:"));
Serial.print(stackptr - heapptr);
Serial.println();
}

As a note, Comments are not mine.

Your code comments contain serious conceptual mistakes - free() should not alter the stack pointer at all, and its effect on what it is freeing is undefined (or perhaps better said, access to what was free()'d is subsequently undefined)

Okay, let me rephrase that in light of the edit; the uncredited author of the code you posted has made serious conceptual errors.  You should probably find a different source of inspiration.

Sure... if the RAM started at address 0, which it doesn't.
According to the datasheet the RAM starts at address 0x0100, below which are all the SFRs:

Is the internal Rom mapped below that?

No. The flash (not ROM) is on a separate bus with its own address range.

Sad, cause if it was mapped below the sram that would make it it easy to handle Progmem variables...

That's why there are special helper function ctions to assist you.

True, but it makes it difficult. PROGMEM Variables are treated as char* so creating functions to determine if I need to load it from ROM (Flash, ROM potato, potahto) or not is a crap-shoot. The F() macro Is all well and good to solve that but cant be used with Static variable so that wouldn't work. Had to Use the FLASH_STRING library to do what I wanted. Would have made alot more sense to keep with the memory hierarchy then just throwing it off somewhere else.

But then you need a larger address register to address a larger address space. That adds lots more complexity, not only to the logic implementation in the chip, but also to the instruction set, the ALU, everything. If you want a princeton memory map instead of harvard then you want a PIC32 or an ARM based chip instead of a little 8-bitter.

You could synthesis a linear address space with C++ smart pointers. Writing a byte threaded virtual machine for the Arduino has to deal with the fact that AVR is a Harvard architecture (and not Von-Neumann). https://github.com/mikaelpatel/Arduino-FVM Anyway this is a very interesting challenge and hiding the physical address spaces with C++ even more so.

free up the memory again (sets stackptr to 0)

Freeing memory alters the heap, not the stack. In any case the heap is not like the stack, it is a piece of memory from which memory is allocated, not necessarily contiguously. If you were to allocate A B C from the heap, and then delete B, the heap pointer would be untouched, because it would now have a gap: A ... C

shouldn't the max addressable size be 0x0800?

As Majenko pointed out, RAM starts past the "internal registers" of the processor, so the maximum RAM would be 0x8FF in this particular case.


text:
How to define SoftwareSerial pins on ESP8266
I'am new to arduino yun and ESP. In fact, i have an arduino yun which has a sim808 dfrobot shield on it which uploads GPS data online at a regular time interval.
I want to connect the dfrobot sim808 shield to esp so that the latter will send the data online thus making the system low cost by not using the arduino yun
#include  <DFRobot_sim808.h>
#include  <SoftwareSerial.h>
#include  <Console.h>

#define PIN_TX    10
#define PIN_RX    11
SoftwareSerial mySerial(PIN_TX, PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

I want to know which pin on the sim808's TX and RX pin should be connected to the ESP8266 like define above, pin 0,1 are used by the yun for Wifi connectin so pin 10 and 11 are used. . By the way, I am currently using ESP8266 12E nodemcu. Please help me with that.


text:
Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int'
My 10 year old received great gift from older brother (Crate Creations) and I am trying write the program and getting this error. It looks to me that I matched the required code word for word symbol for symbol but I just can't figure out what I did wrong:
void loop () {

  for (float x = 0; x < PI; x = x + 0.00001) {
    RGB[0] = power * abs(sin(x * (CommonMathVariable)));
    RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable)));
    RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable)));
    ambientLight = analogRead(ldrPin);
    if (ambientLight > 600) {

    analogWrite (redLed.RGB[0]);
    analogWrite (greenLed.RGB[1];
    analogWrite (blueLed.RGB[2];

  }

I get this error:
request for member 'RGB' in 'redLed' , which is of non-class type 'int'

Nick,  Thanks so much...that got me past the error i have been stressing over... the booklet just looks like a period and not a comma....you rock..here is the rest of the code...after i corrected the comma i am getting an error for 'pulseSpeed not declared'

for (int i = 0; i < 3; i++) {
if (RGB[i] < 1)  {
delay (20 * pulseSpeed);
}
else if (RGB[i] < 5)  {
delay (10 * pulseSpeed);
}
else if (RGB[i] < 10)  {
delay (2 * pulseSpeed);
}
else if (RGB[i] < 100)  {
delay  (1 * pulseSpeed);
}
else {}
}
delay (1);
}

I can't really make out that comment. This sounds like a different question. Can you make a new one please? On the face of it you haven't declared pulseSpeed, unless there is more code you haven't shown. A declaration looks like: type name, for example: int pulseSpeed;

Probably you didn't spot commas:
    analogWrite (redLed,   RGB[0]);
    analogWrite (greenLed, RGB[1]);
    analogWrite (blueLed,  RGB[2]);

The function analogWrite takes two arguments, separated by commas. You were missing some brackets as well.


text:
Optimization Teensy 3.6 Arduino IDE fast I/O Multiplexing Led Matirx
I'm currently working on a 10x10 LED Matrix which is controlled by 5 Shift registers using multiplexing. I've the problem that the Teensy 3.6 is too fast/slow.
One part of my code is the Shiftout function. If I use normal digitalWrite() its working perfectly fine, but its slow. If I use digitalWirteFast() or something like GPIOA_PSOR = (1 << 12); the matrix starts to display crap.
Teensy 3.6 180MHz
74HC595 shift register
SS8050 BJT's to protect the whole thing
scematic here: circuits.io
void ShiftOut(uint8_t myDataOut) {
// This shifts 8 bits out lngMsLoopstartB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
uint8_t i = 0;
//clear everything out just in case to
//prepare shift register for bit shifting

//digitalWriteFast(dataPin, LOW);//Data aus
GPIOA_PCOR = (1 << 12); // Datapin low

//digitalWriteFast(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//for each bit in the uint8_t myDataOut
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i = 0; i <= 7; i++)  {

//digitalWrite(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1 << i) ) {
  //digitalWriteFast(dataPin, HIGH);//Data an
  GPIOA_PSOR = (1 << 12); // Datapin high

} else {
  digitalWrite(dataPin, LOW);//Data aus
  //GPIOA_PCOR = (1 << 12); // Datapin low
}

//register shifts bits on upstroke of clock pin
digitalWrite(clockPin, HIGH);//Clock an
//GPIOA_PSOR = (1 << 13); // Clockpin high

digitalWrite(clockPin, LOW);//Clock aus
//GPIOA_PCOR = (1 << 13); // Clockpin low

//zero the data pin after shift to prevent bleed through
digitalWrite(dataPin, LOW);//Data aus
//GPIOA_PCOR = (1 << 12); // Datapin low
}
}

if somebody needs the complete code, please let me know!

How it looks like when I use GPIO 2.Picture how it should look like: Imgur

Problem
The thing I want is to make the whole multiplexing faster. Currently 1 Time all 10 rows takes about 480 microseconds. Then add a 4 Bit Bit angle modulation (480*16) its: 7680 microseconds (7.68ms). So if you now divide 1000 by 7.68 = 130,2 Hz refresh rate. Thats ok and Im fine with that.
The main problem is that I want 8 bit. so same thing again 480 * 256 = 112880 (112,88ms). So now divide 1000 by 112,88 = 8,86 Hz refresh rate. That looks really bad. I would like to get about 60-100.
The Problem is not the big LED array or setting each value every frame new. This only takes 80 microseconds.

I have also written a driver for LED matrices based on shift registers. To quickly shift out the bits to the shift registers for each scan update, I used SPI. On the Teensy 3.6, this works quite well.
But what I suspect your issue is (since you didn't post your whole code) is that you are calculating each of the bit updates in between each shifting out. If you are doing this, I suggest that you don't. Instead, buffer the bit calculations, and use a timer interrupt to shift out each row update. This approach takes advantage of the fact that you are likely to recalculate the bit layout for the matrix overall at a much slower frequency than the need to send our row updates to effect the multiplexing of the LED rows. I explain this design in much more detail in this Instructable.
Using the interrupt allows you to cleanly do the heavy lifting of recalculating the bit layout into a buffer while the row updates will consistently go out, creating a very stable image. It's the closest thing you'd to true threading on Arduino-like platforms. Also, this approach will allow a much smaller base interval for row updates. In my code, I use a 5 µs update interval, that gets modulated in order to be able to create a 12-bit color palette. I probably could get a richer color depth on the Teensy 3.6 given it's clock speed, but I wanted my code to be universal, so I am able to get the 12-bit color on 8-bit AVR micro controllers too (e.g., Arduino Mega).
You can study (or use) my code at this GitHub repository, and read more about my LED matrices (hardware and software) at my website.

wow! Thanks for that. Will have a look in to that.
Using interrupts makes sense :D. Well in the meanwhile I built a new LED Matrix. But this time with TLC5940 LED Drivers: https://scholliyt.github.io/LED-Matrix-16x16/


text:
Weird characters at the end of LCD
I have written a simple sketch that displays temperature and humidity on a 16x2 LCD. Here's its output:
Temp: 28▒▒
Humidity: 68▒▒
The library I used for DHT11 sensor is not from Adafruit. This is the sketch:
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include<dht.h>

#define DHT11_PIN 12
#define I2C_ADDR       0x3F
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define SCL_PIN        12
#define SDO_PIN        11

dht DHT;
LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

void setup() {
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
  lcd.begin (16, 2);
  lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home ();
}

void loop() {
  lcd.setCursor(0, 0);
  int chk = DHT.read11(DHT11_PIN);
  lcd.print("Temp: ");
  lcd.println(DHT.temperature,0);
  lcd.setCursor(0, 1);
  lcd.print("Humidity: ");
  lcd.println(DHT.humidity,0);
  delay(2000);
}

You say “The library... is not from Adafruit”, which is not helpful -- instead, say which DHT11 library you are using.  Without that info, one doesn't know the declarations of DHT.temperature and DHT.humidity, hence doesn't know which println() was invoked and what it does with second param which causes a character in the range 0 to 7, the custom character generator codes, to print.    Please edit your question to include that info

"The library I used for DHT11 sensor is not from Adafruit" - is it also not from Sparkfun? Give us a break and give a link to the library.

@jwpat7 The library is linked here: link

The function println usually appends a carriage-return and linefeed to what it prints. It wouldn't surprise me if those two extra characters are its attempt to "render" that.
Try replacing println with print and see what happens.


text:
Java NetBeans sending value and receiving value from Arduino
This is my Java code to send a value to Arduino and a receiving value from Arduino. Can anyone tell where I made a mistake? I am able to send the value but can't receive a value from Arduino.
package hell;

import com.panamahitek.ArduinoException;
import com.panamahitek.PanamaHitek_Arduino;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class led extends javax.swing.JFrame
{
    PanamaHitek_Arduino Arduino  = new PanamaHitek_Arduino();
    private BufferedReader input;
    SerialPort serialPort;

    public led(){
        initComponents();
        try {
            Arduino.arduinoTX("com3", 115200);
        }
        catch (ArduinoException ex) {
            Logger.getLogger(led.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent)
    {
        System.out.println("lol 31");
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                System.out.println("lol 1.1");
                Scanner s = new Scanner(serialPort.getInputStream());
                int mes =Integer.parseInt( s.nextLine());
                System.out.println(mes);
                System.out.println("lol 1");
            } catch (Exception e) {
                System.err.println(e.toString());
                System.out.println("Syncronice ");
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(0);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is off");
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(1);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is on");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new led().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;

    try{
        Arduino.sendByte(1);
    }
    catch(Exception ex){
        Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
    }

    System.out.println("led is on");

    private javax.swing.JButton jButton2;
}

Here is my Arduino code, which receives a value from Java and prints it accordingly:
int val = 0;
int led = 8;

void setup() {
  Serial.begin(112500);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available()>0) {
    val = Serial.parseInt();
    if(val == 1) {
      //Switch on the LED, if the received value is 1.
      digitalWrite(led, HIGH);
      Serial.println("Succesfully received.");
    } else if(val == 0) {
      //Switch off the LED, if the received value is 1.
      digitalWrite(led, LOW);
    }
  }
}

EDIT:
There is no problem to controlling arduino via Java code, the problem is that I can't received message from Arduino to display in a Java.

I don't see any initialization of serialPort or serialEvent being called anywhere. And I doubt you will be able to open the port again, if it's already opened by Arduino object. Also you are reading a line from the Arduino and parse it as an integer, but the only thing you are sending from the Arduino is the string "Succesfully received.".

You are writing a number as a single byte and expect it as a string on the other end.
Replace
val = Serial.parseInt();

with
val = Serial.read();

sorry i forget to mention that there is no problem to controlling arduino via java code, the problem is i cant received message from arduino to display in a java..

i have added java jbutton code to control arduino


text:
Storing data on AT24C02 EEPROM chips with Arduino
I have recently come across some  8-pin 128-byte EEPROM chips. I've seen those USB EEPROM chip programmer units, but I was wondering if there is any way I could manually store data on the chip with my Arduino.
I don't have any application for the chips yet, but I would just like to see if I can read / write data on the chips.
Here's the data sheet for the chips.

Did you try googling the keywords "Arduino" with the name of the chip?

@gre_gor http://fritzing.org/projects/readwrite-serial-eeprom-via-i2c would this work?

Please edit your question and add the part numbers of the EEPROM chips.  Some chips have different specs than others.

@jwpat7 it's in the link i believe

Ok, I overlooked that link.  Still suggest editing the part number into title and question

@jwpat7 I did it

Ok, +1, but note that the AT24C02 is the 256-byte model rather than 128

You wire your chips on a breadboard, with the +/- left rail for Vcc/GND, and the right +/- rail for SCL/SDA, plus a little acrobatics to connect everything.
Your chips can have 8 addresses, 0x50 to 0x57, set up with the A0/1/2 pins: all low = 0x00, all high = 0x07. The you read and write to the EEPROM of your choice with:
char i2c_eeprom_read_char(int deviceaddress, unsigned int eeaddress) {
  char rdata = 0xFF;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void i2c_eeprom_write_char(int deviceaddress, unsigned int eeaddress, char data) {
  int rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(rdata);
  Wire.endTransmission();
}

If you have more than 8 chips (well throw them away and get larger ones, but anyway, for completeness sake): wire all of them with A1/A2 to GND, and each A0 to a different digital pin. When you need to access a chip, set all A0s to LOW, except the one you want to HIGH, and use 0x51 as the address. By doing this you're setting all chips except the one you want to address 0x50 (which doesn't matter) leaving only one at 0x51. That enables you to have as many chips as you have free digital pins...

When I use the I2C Scanner, I see 8 addresses 0x50..0x57with only one connected to the I2C bus, I have A0..A2+GND connected to ground (LOW). Any ideas? Before I had no connections made and saw this article so I thought this could be the solution but for me it is not. I can read the EEPROM and write it but only first 256 bytes.

A0/A1/A2 connected to ground means address 0x50. Do you have anything else connected to the I2C bus? Maybe write a question, explaining your setup. Easier than in comments.

Hi dda, there is nothing else on the bus. I posted a question yesterday about the capacity and the adresses on stackoverflow: https://stackoverflow.com/questions/47823243/can-read-write-eeprom-address-however-can-only-read-write-first-memory-page/47829869#47829869 About the capacity, read documention wrong, capacity is in bits and not in bytes so there is only 256 bytes available. Why manufacturers use bits instead of bytes to specify the capacity? All capacity is always measured in bytes, very confusing and explains my error.


text:
How should I initialize a RepRap Discount 12864 on u8glib?
I was taking the advantage of an existing piece of hardware (RepRapDiscount Full Graphic Smart Controller) for my present project.
Here is a link for the RepRap wiki about the controller
#define LCD_PIN_SCLK   A4
#define LCD_PIN_MOSI   6
#define LCD_PIN_CS   8
U8GLIB_ST7920_128X64_1X u8g(A4,6,8, U8G_PIN_NONE);

But all I got is a blank screen with no light at all. What has happened?

I solved the problem myself. It turns out to be a problem of wrong pinouts.
My PCB of the project was originally designed for the LCD2004 counterpart, and I thought it was a drop-in replacement for 12864. But no, it's not.

This is the "Smart Adaptors". Notice that the orientation are 180 degree different.
If you have the same problem not lighting up a 12864 when switching from 2004, or vice versa. Check your orientation as above.
My solution will be crimping a different JTAG wire instead.

I had a similar issue with figuring out how to get the Zyltech.com RepRapDiscount Full Graphic Smart Controller (with their Mega 2560 clone) to work with u8glib. After some fiddling it looks like the correct settings for me were:
// SPI Com: SCK = en = 23, MOSI = rw = 17, CS = di = 16
U8GLIB_ST7920_128X64_1X u8g(23, 17, 16);


text:
What happens if device sends data to arduino over serial port (UART) and arduino is unable to read it
Suppose delay(10000) function is executed, so Arduino cannot do any other work.

During this time if the other device sends the data to arduino what
  will happen ?

Depending on the memory available, between 16 and 256 bytes will be stored in a ring buffer. Any bytes that arrive after that will be just thrown away.
The reception code in the core is:
void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0)) {
    // No Parity error, read byte and store it in the buffer if there is
    // room
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    // if we should be storing the received character into the location
    // just before the tail (meaning that the head would advance to the
    // current location of the tail), we're about to overflow the buffer
    // and so we don't write the character or advance the head.
    if (i != _rx_buffer_tail) {
      _rx_buffer[_rx_buffer_head] = c;
      _rx_buffer_head = i;
    }
  } else {
    // Parity error, read byte but discard it
    *_udr;
  };
}


text:
Turning an electric vehicle
I am not sure if what I am asking is possible. I was wondering if I would be able to program my Arduino to have my car go straight until one of the wheels hits a certain amount of wheel rotations then initiating a different code within the same causing that wheel to increase that wheels speed. I have already created a code to make it go and stop in a certain amount of rotations.
/* motorshield_code
Pins Utilized
Digital 2 = encoder0APinA
Digital 3 (PWM) = MotorASpeed  //motorshield utilized
Digital 4 = encoder0PinB
Digital 8 = MotorBBrakePin // motorshield utilized
Digital 9 = MotorABrakePin // motorshiled utilized
Digital 11 = MotorBSpeedPin // motorshiled utilized
Digital 12 = MotorADirectionPin // motorshiled utilized
Digital 13 = MotorBDirectionPin // motorshiled utilized
*/

//Encoder values
const int encoder0PinA = 2;
const int encoder0PinB = 4;
const int encoder1PinA = 7;
const int encoder1PinB = 6;
int encoder1Pos = 0;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int encoder1PinALast = LOW;
int n = LOW;
int i = 0;

//Motorshield Pin Values
const int MotorADirectionPin = 12; //digital pin value for A direction
const int MotorASpeedPin = 3; //analog pin value for A speed (PWM)
const int MotorABrakePin = 9; // digital pin value for A brake
const int MotorBDirectionPin = 13; //digital pin value for A direction
const int MotorBSpeedPin = 11; //analog pin value for A speed (PWM)
const int MotorBBrakePin = 8; // digital pin value for A brake
//Motor Control Values
int BrakeA = LOW; //Brake for motor A, LOW = motor off, HIGH = motor on
int BrakeB = LOW;
int DirectionA = HIGH; //Direction for motor A, LOW/HIGH are opposite (based on wiring) assume Low is forward
int DirectionB = LOW;
int SpeedA = 0; //Speed for motor A, PWM value from 0 - 255 (0 is off)
int SpeedB = 0;
int encoder0stop = 469.125; //stop value for encoder 0
int encoder1stop = 469.125; //stop value for encoder 1

void setup() {
  //Set Digital I/O pins 2 and 4 to inputs for encoder
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  pinMode (encoder1PinA, INPUT);
  pinMode (encoder1PinB, INPUT);
  //Set Digital I/O pins as outputs for motorshield
  //Analog pins are already set so don't have to initialize speed pins
  pinMode(MotorADirectionPin, OUTPUT);
  pinMode(MotorABrakePin, OUTPUT);
  pinMode(MotorBDirectionPin, OUTPUT);
  pinMode(MotorBBrakePin, OUTPUT);
  //Start serial monitor at 9600
  Serial.begin (9600);
  delay (0);
  Serial.print("Last Enc State");
  Serial.print(" ");
  Serial.print("Current Enc State");
  Serial.print(" ");
  Serial.print("Encoder Count");
  Serial.print(" ");
  Serial.print("Speed");
  Serial.print(" ");
  Serial.print("Brake");
  Serial.print(" ");
  Serial.print("Direction");
  delay(2000);
}

void loop() {
  if (i == 0) {
    analogWrite(MotorASpeedPin, 255); //set motor A speed
    analogWrite(MotorBSpeedPin, 255); //set motor B speed
    i++;
  }
  //Set values to write to arduino
  if (encoder0Pos < encoder0stop) {
    //if hasn't reached end encoder value
    //Direction Forward, Brake OFF, speed 125
    DirectionA = HIGH;
    DirectionB = LOW;
    BrakeA = LOW;
    BrakeB = LOW;
    SpeedA = 254;
    SpeedB = 253;
  } else {
    //if has reached encoder value
    //Direction Forward, Brake ON, speed 0
    DirectionA = HIGH;
    DirectionB = LOW;
    BrakeA = HIGH;
    BrakeB = HIGH;
    SpeedA = LOW;
    SpeedB = LOW;
  }

  //Write all values to the arduino
  digitalWrite(MotorADirectionPin, DirectionA); //set motor A direction
  digitalWrite(MotorBDirectionPin, DirectionB); //set motor B direction
  digitalWrite(MotorABrakePin, BrakeA); //write motor A brake on/off
  digitalWrite(MotorBBrakePin, BrakeB); // write motor B brake on/off
  analogWrite(MotorASpeedPin, SpeedA); //set motor A speed
  analogWrite(MotorBSpeedPin, SpeedB); //set motor B speed
  //Read Encoder
  //This is reading PinA which should be set to pin 2 and storing it as n
  n = digitalRead(encoder0PinA);
  //Check to see if pin 2 has changed from LOW to HIGH
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    //Check to see if pin 4 is LOW -> this determines which direction the encoder is going
    if (digitalRead(encoder0PinB) == LOW) {
      //encoder is going "backwards" decrease encoder position
      encoder0Pos--;
    } else {
      //If pin 4 is HIGH
      //encoder is going "forward", increase encoder position
      encoder0Pos++;
    }
    //Tell us what is happening!
    Serial.print (encoder0Pos);
    //go to the next line of code
    Serial.print(" ");
    Serial.print(encoder0PinALast);
    Serial.print(" ");
    Serial.print(n);
    Serial.print(" ");
    Serial.print(encoder0Pos);
    Serial.print(" ");
    Serial.print(SpeedA);
    Serial.print(" ");
    Serial.print(BrakeA);
    Serial.print(" ");
    Serial.print(DirectionA);
    Serial.println();
    encoder0PinALast = n;
  }
  //Set what the last read of pin 2 was so we can compare to see if it changes
  encoder0PinALast = n;
  //End Code for Encoder Reading
}

If your car is capable of having one wheel change speed, and your Arduino is capable of controlling the speed of that wheel, then of course it is possible. You just have to work out how to program it.

And can you make it run at different speeds? You don't give us any details about what you have - what type of motor etc - so it's hard to know what your setup can do.

yes I can make the motors run at different speeds. the motors are also DC motors and I'm using c++ coding I can also put a picture of the coding I already have

I would say that one of the solutions would be to arrange the code in your car into a finite state machine. So your states would be something like:

Start (reset the encoders and set the initial speed)
Go straight (both motors at 100%)
Turn left (left motor at 75%, right at 100%)
Turn right (right motor at 75%, left az 100%)
Stop (stop both motors)

Example code:
//TODO: Init program and variables
void go_straight()
{
    if(number_of_rotations > 10)
    {
        state = TURN_LEFT
    }
    else
    {
        motor_left = 100;
        motor_right = 100;
    }
}
void turn_left()
{
    if(number_of_rotations > 10)
    {
        state = TURN_RIGHT
    }
    else
    {
        motor_left = 100;
        motor_right = 75;
    }
}
//TODO: Implement remaining methods

void loop()
{
    //Update number of rotations since state change
    update_rotations();
    if(state == START)
        start();
    else if(state == GO_STRAIGHT)
        go_straight();
    else if(state == TURN_LEFT)
        turn_left();
    else if(state == TURN_RIGHT)
        turn_right();
    else
        stop();
    //This code gets executed on every loop cycle and is not dependent on state
    print_status();
    wait(100);
}

is there any way to program it with the code I already have and without rewiring my Electric Vehicle?

Why do you think you would have to rewire your vehicle? My answer was abstracted in a way that it is not dependent on the actual hardware.

You never reset the number of rotations, so it will go from straight, "directly" to turn_right.


text:
Connect my Arduinos to central server, despite different IP adresses
Community,
A team of friends just built, with an Arduino UNO, a system where one can open a door lock from the internet.
The Arduino UNO has an Ethernet Module (ENC28J60). When the command prompts, the Arduino will let a solenoid receive 5v, which will open it and, therefore, open the door.
The novel thing is, this door-opening-arduino connects via the Internet to a central server, a webpage that 'centralizes' the door-opening process. So, in a certain URL, we'll get a screen which goes:

All these doors are in remote locations, connected to very different routers. Some of these routers will go 192.168.1.1, whereas others will go with the 0.1 ending.
So far, my friend has hard-coded the internal IP address 192.168.1.143 for identifying the Arduino, so, he's given up on DHCP.
Afterwards, he's chosen port 6560 to be the open port and connect the door to the Internet. (VPN is not a option).
So the public IP address and port 6560 are our way in into the door. This info is shared with his webpage, where commands can be given: 'open it'.
But with these hard-coding of the 1.143 IP and the router's different default addresses, we've had trouble. You know what I mean: sometimes, the whole code must be changed for our Arduino to connect to the router. Not even close to 'plug-n-play'.
My questions seems natural: how can we ensure the Arduino connects each time to the router, without any problems?
Most devices just connect: an IP camera in these routers will connect, and will never care which IP address the router has given it. If the router resets, things will be fine, and connection will restart.
So, why not DHCP? As far as my understanding goes, a problem my friend mentioned that would happen if he chose to use DHCP would be the communication between his Arduino and his online server: 'how can I know which IP I should speak with in order to open the door? By choosing the .143, I know which would should be'.
Another problem comes in with port forwarding. Apparently, by choosing the .143 and then using port 6560, we ensure that we can access via the Internet, because there's a standarized procedure: 'please open port 6560 for this IP'.
This is a bit cumbersome. Most devices just don't work this way. We want to be able to just plug it in, let our Arduino and the router get any IP, and by just opening port 6560, we're in. Pretty simple.
How can we ensure that:

Our Arduino just connects to the router, and
that communication between our Arduino and the centralized server
just flows?

Another friend suggested configuring each router so that a device with a certain MAC address (our Arduino) gets this IP* and this port forwarding. But what if the default address is 192.168.0.1 (instead of 1.1), for example? wouldn't we be facing a problem?
We're seeking a kind of plug-n-play thing, like most access control systems work. Hardware's ok, it's connection the thing that bugs us.
Any suggestions, advice, or plain responses are really welcome. I think we're just a step away from our commit, which is creating a reliable connection for these doors. It may be just a line of code, or a config trick. Thank you for your time.
(you'll soon notice we're not that savvy on routing and switching, so If we got our premises completely wrong, don't hesitate to correct us)

I'd forgo the port forwarding and ip-fixing, and just have the Arduino poll the central server, to see if there's any action that needs to take place. Alternatively use something like pagekite.

Your problem is two-fold, and neither are easy for an Arduino to overcome.
First you have the problem that the router's internet-facing IP address is (unless you have a special arrangement with your ISP) liable to change at any time. You need to keep your sever up to date at all times with what that IP address is, and the only real way of doing that is for the router, or something behind the router, to connect with your server so it can update its IP address.
Secondly you have the port forwarding. The router has to know where to forward the port to. That means that either the IP address of the Arduino has to be static, or the Arduino has to somehow tell the router to do the port forwarding.  The simplest method is just to allocate a static IP address as you have done. The alternative is to use UPnP to instruct the router "I need you to forward this port through to me" - assuming the router understands UPnP. The hardest part of that though is getting the Arduino to speak UPnP. I am not aware of any UPnP libraries for the Arduino.
So keep the static IP address for the Arduino, it is simplest. One thing to note with manually allocating an IP address though is that it is vitally important you allocate it outside the IP address range of the DHCP server. Otherwise it is possible that the DHCP server could then allocate the IP address to someone else, and you'd then get a conflict. Most routers allow you to choose the range of IP addresses so you may want to go in and check that the DHCP server isn't able to clobber the IP address you have chosen.
To help solve the first problem some routers provide a "DDNS" (Dynamic DNS) facility, whereby they will periodically connect to a DDNS service to update a DNS record with the public IP address of the router. Not all provide it and those that do usually only provide access to a couple of DDNS services, so check your router to see if it does support it and if there is a suitable one for your needs there. If there is you can configure that and then, instead of connecting to the IP address of your router for issuing commands you instead connect to the DDNS domain name allocated to your router.
However, there is one much simpler option that solves all the problems in one go: reverse the communications.
Instead of the server connecting to the router to forward the port through to the Arduino to issue a command, it is far simpler (though I will admit not as responsive) for the Arduino, from whatever IP address it happens to be on, to just connect to the server itself and ask it for any pending commands.
If you have the ability to run your own software on the server you could even create your own small TCP server which the Arduino connects permanently to. The server can then send commands down that TCP connection just as if you were working with an Arduino directly connected by serial.
In both those situations it doesn't matter what IP address your router is on. You don't need to do any port forwarding. The Arduino can be on any IP address on your network.
And further more you have more security - no one could connect to your Arduino through the internet and cause havoc.

thank you! just shared this with my programmer friend and he thinks it's a great idea. He´s suggested using Heroku as a server, although we should pay a monthly fee for it, as Heroku "falls asleep" if it isn't used for 30 minutes, and we can't risk that.
Do you have any further advice? such as a platform to use (i.e, it could be Heroku), or a free alternative, or just any other suggestion in programming and deployment? We'll be expectant.

I would use socket.io for this. Here is a goos presentation on this:
http://www.robojay.us/wp-content/uploads/2016/08/NRB-socket-io.pdf