text:
Strange behavior on 74HC595 Shift Register IC when its GND pin is used
I was following a tutorial similar to this:
https://www.arduino.cc/en/Tutorial/ShiftOut
That is, an array of 8 LEDs that lit up accordingly to the binary representation of a number, which was given in a loop from 0 to 255.
The problem is that when invoked shiftOut() over certain numbers (such as 5, 9 or 13), the LEDs didn't lit as expected.
I even tried replacing the IC, but what finally solved this issue was to disconnect IC's pin 8 (GND) and let only pin 13 (OE) connected to Arduino's ground pin.
Does anyone know the reason this strange behavior happens on 595 IC?
Here's a video showing the circuit finally working (without IC's GND pin connected): https://www.youtube.com/watch?v=NGfpk-kjemo

Please post your code and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. Please post your schematic. You have done something very very wrong for this to happen.

What size resistor? Check how much current is pulled.

didn't lit as expected. Please expand on that. No leds were lid? Wrong leds were lid? If so which?

As suggested by previous comments, you ought to provide enough information so that replies can give answers instead of speculation.  Besides the video (which seems to show that you correctly oriented the chip), add a couple of clear photos of your breadboard setup, and draw the circuit.

Sorry, I'll try to explain more.
When 595's GND was connected, wrong LEDs were lid only for some numbers. For instance, 3 lid 00000011, 4 lid 00000100, but 5 lid 00000110 (instead of 00000101).
The resistors I used were 150 ohms.
Actually I was following a chapter of this book (in a Brazilian Portuguese version):
https://books.google.com.br/books?id=3TXyAAAAQBAJ&lpg=PR11&ots=vrG79YuC7C&pg=PA111
The project schematics and source code are in this link above. The exceptions are that the 1st edition it recommended 220 ohms resistors (instead of 560 ohms) and the capacitor wasn't present.

The schematics: http://i.imgur.com/WGrNjfY.png?1

Disconnecting the ground pin was not a solution.
It is hard to be certain from video but the resistor values are likely too small because I can't see any color on the bands.  They are 100?
Look closely at the driver data sheet.  It may say an output pin maximum current is +/-35 mA which would suggest that the 100 ohm resistor is okay.
For example, a red LED has a of around 1.6 V.  You are using Vcc=3.3, so a 100 ohm resistor limits the current to <17 mA ((3.3-1.6)/100).  The actual current will be a somewhat smaller as the Vf increases with current..
But you also stay within the maximum Icc and Ignd on the data sheet.  These limits are not necessarily 8 x 35 mA.  For example an NXP max Icc is 70 mA.  That means you cannot drive all the outputs at maximum current, just 2.  This is a logic chip, not a driver.
There is other hint that you should not using all the outputs at the max current spec in the section where the Voh and Vol are described.  The current at which the voltage is specified is 6 mA, which is the maximum you should use if all output are going to source or sink at the same time.
A common LED current is 5 mA, so this chip could drive 8 simultaneously.  If you want high brightness, you need to add a driver such as ULN2003.
Note that the schematic shows red LED's.  The color is important.  Different LED's have different forward voltage.  The blue LED have the highest in the range of 3.3 V and higher.  So with a Vcc=3.3 there is barely enough voltage to light the blue LED.  The red and yellow have much lower forward voltage.  When the chip tries to light the red and blue at same time, the output voltage is dropping enough that the blue is not visible, but the red is easily lit.
From the video, it looks that you have the same resistor on all the LED's.  On different color LED's this will not achieve the same brightness on all LED's.  You need different resistors for each color if you want them the same brightness.
The solution is

Up the Vcc to 5V so that you can reliably light the blue LED's.
Increase the resistor values start with 510 for red and 220 for blue.  This should be about 6 mA for both.

I used 150 ohms resistors. The input Vcc was 3.3 V (from Arduino's).
I realized that LEDs were quickly blinking just before each transition.


text:
What should I do to communicate with GSM module?
Sorry, im a beginner, i tried to program an automatic doorlock using sms. But, I dont understand what happen with this error, what should I do? Add library? The error said that Pstring wasnt declared, but i dont know how to declare this.
#include <LiquidCrystal.h>
#include "SIM900.h"
#include "sms.h"
#include "SoftwareSerial.h"
#include "sms.h"

SMSGSM sms;
boolean started=false;
char buffer[160];
char smsbuffer[160];
char n[20];
int pintu=5;
int buttonState;
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 50;
boolean st=false;
int buzzer=6;

void setup()
{
  pinMode(pintu,OUTPUT);
  pinMode(buzzer,OUTPUT);

  digitalWrite(pintu,LOW);
 if (gsm.begin(9600))
 {
  started=true;
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
   digitalWrite(buzzer,HIGH);
   delay(100);
   digitalWrite(buzzer,LOW);
   delay(100);
  }
   if(started)
  {
   delsms();
   sms.SendSMS("08970869443","Pintu SMS Menyala");
  }
  else{digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(buzzer,LOW);
  }

   }

   void loop()
   {

   int pos=0;
  if (gsm.begin(9600))
  {
  if (started){
  pos=sms.IsSMSPresent(SMS_ALL);
  if(pos)
  {
   sms.GetSMS(pos,n,smsbuffer,100);
   delay(2000);
    if(!strcmp(smsbuffer,"bukapintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Pintu Dibuka");
    digitalWrite(pintu,HIGH);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    if(!strcmp(smsbuffer,"tutuppintu"))
    {
      PString str(buffer, sizeof(buffer));
    str.begin();
    str.print("Kunci Pintu Ditutup");
    digitalWrite(pintu,LOW);
   // String a=str
    sms.SendSMS(n,buffer);
    }
    delsms();
   }
   }
   }
   }

   void delsms()
   {
   for (int i=0; i<10; i++)
  {
     int pos=sms.IsSMSPresent(SMS_ALL);
    if (pos!=0)
   {
    if (sms.DeleteSMS(pos)==1){}else{}
   }
   }
   }

Error message :
     Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

      D:\Kuliah\Project\Skripsi\pintu_sms\pintu_sms.ino: In function 'void loop()':

      pintu_sms:67: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

      pintu_sms:67: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:68: error: 'str' was not declared in this scope

     str.begin();

     ^

    pintu_sms:76: error: 'PString' was not declared in this scope

       PString str(buffer, sizeof(buffer));

       ^

    pintu_sms:76: error: expected ';' before 'str'

       PString str(buffer, sizeof(buffer));

               ^

     pintu_sms:77: error: 'str' was not declared in this scope

     str.begin();

     ^

     exit status 1
  'PString' was not declared in this scope

The compiler does not know what PString is. It is not declared in any of the libraries you have included.
You could rewrite to something like this.
strcat(buffer, "Pintu Dibuka");
n = strlen(buffer);
digitalWrite(pintu,HIGH);
sms.SendSMS(n,buffer);

Please change the other block in the same way.
There are more errors. You also need to change "int n[20]" to "int n".
That is a good start.
Cheers!

I tried what you told to me, but still error

or i missed any libraries?

Yes there are more errors of the same type (using PString). You might have intended to include that? Cut-and-pasting code?

Try this library http://arduiniana.org/libraries/PString/.

source: Stack Exchange

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

sort: votes


text:
Use only one pin as serial output/input with arduino
I'm looking for a way to use Arduino UNO's as serial outputs or input "individually", I don want to have an RX pin for each TX pin. I know the library SoftwareSerial, but I'm not sure if it is posible to achieve my objective with it.
I have also read that in this library "If using multiple software serial ports, only one can receive data at a time". Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?
Thank you for your time.

The reason you can't receive more than once channel at a time with software serial is that there is only one CPU - how can it process two asynchronous channels at the same time?

@TomCarpenter It's certainly possible but it would require some gnarly interrupt-driven sampling/sending, and would work only at limited (relatively low) baud rates.

@SpehroPefhany I was talking about the SoftwareSerial library which uses busy loops for generating the baud rate. I should have made that more specific. Yes you can potentially do it if you write your own RX code of find one which doesn't block.

@RobhercKV5ROB This one is probably best migrated.

Not about electronics, and you mentioned "arduino".

If you can go asynchronous half-duplex, why can't you set your I/O to OUT, send  your message, set your I/O to IN, wait for the reply and repeat as necessary?

what are you communicating with? could you possibly use another protocol, like I2C/TWI?

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

I adapted the SoftwareSerial library a while ago to omit the receiving part. You can download that from:
http://www.gammon.com.au/Arduino/SendOnlySoftwareSerial.zip
You use that like SoftwareSerial but if you read you will always get -1 returned, and available always returns 0.
The constructor only has the transmit pin:
  SendOnlySoftwareSerial(uint8_t transmitPin, bool inverse_logic = false);

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

You don't want an Rx pin, but you want to receive from more than one pin at a time? Now you've lost me.
Sounds like an X-Y Problem - maybe describe this requirement in more detail.
Having said that, hardware serial can receive from one pin while the processor is doing something else. If you have a Mega you could receive from 4 ports at once (it has 4 x hardware serial ports).

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

Serial ports do not require both directions to work. You can connect just one if you want. Of course you won't be able to reply or receive but you know that. Multiple TX from a microcontroller is easy. Just send the data at the speed required. RX is harder because you have to be able to read multiple high speed random inputs at the same time. It requires careful and complicated coding and will not be small or simple. You may not be able to do it and the rest of your project as well.
There are ICs or setups that can multiplex serial lines though. See https://electronics.stackexchange.com/questions/111491/multiplexing-ttl-serial-lines-with-transistors

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


text:
Serial not working with I2C
I have been working on a hydroponic garden that is controlled with Arduinos. I have everything working except for the user interface. What I would like to do is have an LCD screen paired with a rotary encoder for use on the garden, and an ESP8266 WiFi module set as a server working with a custom Android app that I am writing.
I have been working on writing the app and the code that will allow the Arduino and the app to talk to each other, but I have been running into a problem. Sometimes the serial data between the ESP266 and the Arduino is not being picked up by the Arduino. I have verified that the data coming out of the WiFi module is correct, but the Arduino seems to be missing characters. This seems to happen almost at random. Sometimes it will work, and other times it will simply get stuck. I used a SoftwareSerial library to add an extra serial port and printed what the Arduino was receiving from the WiFi module, and it just seems to be missing random characters.
Up until now I have had the WiFi module connected and the LCD screen. I was using the LCD screen to display debugging messages. I took the LCD screen off and deleted all the LCD code and now everything seems to work just fine.
The LCD screen uses I2C.
Why does disconnecting the LCD screen solve the issue? Is there a way to make both run at the same time? The LCD uses I2C. I am unaware of anything that would prevent this from working.
Thanks.

Without seeing your code, and preferably a schematic, a reply would be guesswork.

I'll guess it's the incompatible voltage levels because ESP8266 is a 3.3V device that'll output 3.3V logic high. Try converting the ESP8266's TX 3.3V to 5V serial and Arduino's TX 5V to 3.3V serial

Please add some info on the memory statistics with and without the LCD code. And the obvious question; are you using String?

Explanation
The SoftwareSerial library requires continually polling the serial ports over short periods of time therefore it presents a problem of having to parse received data into something usable, which is going to be nearly impossible as your program is going to be too busy trying to keep up with all the incoming NMEA characters to assemble it all into something meaningful.
So in your situation the data from the ESP8266 module is probably fine as you say, but parsing it and sending it to the lcd over I2C is a lot of work and sometimes it will "lose" data it simply doesn't have time to process. This explains why the data loss is hit and miss, and gets resolved when you reduce the processing workload of your program by removing the lcd component.
Solution
What you need here is to use an interrupt-driven SoftwareSerial library instead, which works by filling a buffer in the background with received data and allows a little breathing room to process the serial data. A great example is the NewSoftwareSerial library. This link will show you how to use the library , also expand into the details my answer to give you a deeper understanding.

I am using the native serial pins on the Arduino to receive information from the WiFi module.  The SoftwareSerial library was only used to print to the computer to see what the Arduino was receiving from the module.  Would the same problem happen with the native serial pins?

Old thread, but this answer contains incorrect information.  From arduiniana: "NewSoftSerial is in the core!  Starting with Arduino 1.0 (December, 2011), NewSoftSerial has replaced the old SoftwareSerial library as the officially supported software serial library."  So that library still blocks.  I would suggest my library, NeoSWSerial.  It does not block on receive and can transmit and receive at the same time. See also this answer regarding "native serial pins", aka HardwareSerial.

@slash-dev My answer does point to the NewSoftwareSerial library, what exactly is incorrect?. If you have a custom library you think would suit the OP's needs please add a full answer above as a useful reference for anyone with a similar issue.

I agree that the polling approach is causing problems, but but he is already using that library.  NewSoftwareSerial is the current SoftwareSerial.  Although the start of each character causes an interrupt, SoftwareSerial polls for the remaining 9 bits, with interrupts disabled.   :P  I was reluctant to add a complete new answer, because your analysis is correct, but the library suggestion is not.  Alternatives are listed in my other answer, here.  SoftwareSerial is last choice for many reasons, including the OP's problem.


text:
compilation error in arduino
I'm new to arduino. I had found an interesting project to work on with, but unfortunately I'm held up at compilation error. I tried finding answers to this problem but not able to understand.
Here is my code:
    // Include Libraries
#include <Wire.h>
#include <Servo.h>
#include <Adafruit_TCS34725.h>

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

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

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

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

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

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

}

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

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

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

}

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

#ifndef TwoWire_h
#define TwoWire_h

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

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

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

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

    void onService(void);

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

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

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

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

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

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

    uint8_t adapter_nr;
    int i2c_fd;
    int i2c_transfer;
};

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

#endif

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

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

#include "Wire.h"

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

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

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

}

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

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

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

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

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

    return quantity;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void TwoWire::onService(void)
{
}

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

TwoWire Wire = TwoWire(Wire_Init);

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

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

TwoWire Wire1 = TwoWire(Wire1_Init);

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

Here is the error message i got:
libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling.

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

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

I agree with uint128_t - it looks like you have an improper installation. Somehow Wire.cpp is being compiled twice.

Thank you uint128_t. I found that the servo library had wire library files. Removed the files and things are working great.

Please mark this question as answered.

Looks like the Servo library has Wire source files in it for some reason. I checked my Servo library, and it doesn't have those, so not sure what's going on there, but maybe try removing Wire.cpp from Servo/src/? (keep in the file so you can put it back if necessary)
credits to uint128_t(in the comments)
Based on his suggestion i removed the
wire library files present in servo library folder and things worked just fine.


text:
Need some explain before desigin my own custom Arduino Due board
I'd like to ask you some questions about ARM processor from Atmel like the SAM3X8E, the one used in the Arduino Due. I have found this [AVR programming guide] from abcminiuser on avrfreaks very helpful.
Q1. Why are there no ICSP pins in Arduino Due to use it to program the SAM3X8E from an external programmer instead of the USB port in the Due board?
Q2. If I want to program an Arduino Due from an external programmer which of the programmers in abcminiuser guide will do the job and give me the ability to program 8/16/32bit AVR and ARM chips from Atmel at the same time?
Q3. On the Arduino Due website I read this:

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

What is that mean?

What is an Arduino Duo? I believe you mean "Arduino Due"

Did you look at Chap. 18. Enhanced Embedded Flash Controller (EEFC) in the datasheet. http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf. If you are constructing a board I would recommend starting there.

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

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

Thank for this info, but any other alternative chip to SAM3X8E, It 3.3v and 512K.B of RAM , and have many IO pins , There is no 3.3v with 512K.B RAM chip in AVR family, by the way I make some search and find that Atmel have two programmer Atmel-ICE and JTAGICE3 the last is less expensive and about half price the one and support AVR like Atmega2560 and ARM like SAM3X8E, So can I use it to programming SAM3X8E if I design custom SAM3X8E board and remove both USB port from Arduino Due design, Also what pins should I connect this programmer to the chip to programming It?

Maybe you should look furthrt afield? Btw, it has 512k flash, not ram. It only has 96k ram. I use PIC32 chips mostly.

There are many makes of microcontroller that are better than the sam chips. Many manufacturers make them, so shop around. Define your requirements then fit the chip to those requirements, don't fit your requirements to the chip just because some toon at Arduino is a fan of it.

Maybe you should look Dear Majenko thank for your advise, the reason that make me choice AVR because it's very simple and can be programmed by C,also if there is library for and sensor work with Arduino I could make this library work with AVR with little change in it's code that's why i decide to upgrade from AVR to ARM from Atmel.

All microcontrollers of this ilk can be programmed in C or C++. Many have an Arduino compatible API as well, such as Teensy, chipKIT, Energia, etc. so programming is almost identical.


text:
Store TinyGPS++ latitude value into a variable of type string or float
I want to get the GPS ordinates in degrees with 6 decimal accuracy. I can obtain this by creating a gps object with TinyGPS library. but In the TinyGPS example codes, its written
Serial.println(gps.location.lat(), 6);

But I actually want to store this latitude degrees in a variable of type string or float. when i write this;
double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude);

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

"double lat = gps.location.lat();" but I think there is more to this question?

double and float , both are not working. both giving me 33.55 as an answer. check my updated question ...

double and float are the same on AVR. The answer to the number of decimals printed is here https://www.arduino.cc/en/Serial/Print. The default is two.

Try Serial.println(Tiny_latitude, 6); But remember the max number of digits is 6-7. https://www.arduino.cc/en/Reference/Float

O man, You're a life saver ! Thanks a bunch :) Serial.println(Tiny_latitude, 6); worked like charm.

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

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

The issue is simply the number of decimal places. That can be added to the Serial.println().
double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude, 6);

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

I would use sprintf() for that but as that requires some additional build parameters the easiest way is to use String. Some special care is needed to increase the number of decimal places.
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

Cheers!


text:
Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?
How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?
ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.

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

That looks to be an excellent starting point for what I'm trying to do, thank you very much indeed Mikael.

Something crucial in the example is puzzling me...
The arduino is a listening UDP client which returns an acknowledgement to any sender(s). But the processing sketch which should be broadcasting a message seems to only be sending it to the specified client, rather than globally to all listening clients...
void keyPressed() {
String ip       = "192.168.1.177"; // remote IP address
int port        = 8888;        // destination port
udp.send("Hello World", ip, port );   // message to send
}
Is it possible to broadcast to all of the subnet by using something like 0 as the address byte?

More reading https://tkkrlab.nl/wiki/Arduino_UDP_multicast.


text:
How to append float value of into a string ?
I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with
    char charVal[5];               //temporarily holds data from vals
    String stringVal = "";     //data on buff is copied to this string

    dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
    //convert chararray to string
    for(int i=0;i<sizeof(charVal);i++)
    {
    stringVal+=charVal[i];
    }
    GPS_string = GPS_string + "Car location: \nlat:" + stringVal;
    stringVal = "";

and it given me an error :
error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,

This has been answered in the previous question but I can repeat it here:
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

An alternative is to use dtostrf() as in your snippet:
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  const int BUF_MAX = 64;
  char buf[BUF_MAX];
  const int VAL_MAX = 16;
  char val[VAL_MAX];
  strcpy_P(buf, (const char*) F("your location is \nlat:"));
  dtostrf(latitude, 8, 6, val);
  strcat(buf, val);
  strcat_P(buf, (const char*) F("\nlong:"));
  dtostrf(longitude, 8, 6, val);
  strcat(buf, val);
  ...
}

Cheers!


text:
I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04
I'm using the Arduino Starter Kit so I have a Uno R3 and going through the examples I'm trying to read temperature data from my controller in Arduino Studio.
In essence my problem can be reduced down to
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.print("stuff");
}

Which I'd expect to keep printing "stuff" on the serial monitor.
(In practice I'm running this exact code but all the temperature-reading going on feels irrelevant to my problem, I'm simply mentioning it because I can observe that mye LEDs light up when the temperature rises so I know the code is uploaded and running on the Duo).
I'm not seeing any errors in the studio console, and if I connect using gtkterm or screen I can see data being sent so the problem seems to be isolated to the AndroidStudio serial monitor itself.
I'm running Ubuntu 14.04 and I've connected via USB on /dev/ttyACM3.
I tried running

stty -F /dev/ttyACM3 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as suggested here and I also tried with baud 115200, taking care to also change the value in my setup function.
I also ran

chmod a+rw /dev/ttyACM3

But I'm still not seeing any errors or output. How do I proceed to debug this issue?
Running ls -l /dev/ttyACM* gives

crw-rw---- 1 root dialout 166, 0 feb.  20 14:22 /dev/ttyACM0
crw-rw---- 1 root dialout 166, 1 feb.  20 14:22 /dev/ttyACM1
crw-rw---- 1 root dialout 166, 2 feb.  20 14:22 /dev/ttyACM2
crw-rw-rw- 1 root dialout 166, 3 feb.  20 14:30 /dev/ttyACM3

Test GtkTerm or PuTTY.

@MikaelPatel Thanks, that should help me isolate the problem at least :)

What's the output of "ls -l /dev/ttyACM*"?

@Avamander I've edited that into the question, along with what I'm getting from gtkterm

If it matters, my user is in the dialout group

Try putting the string "stuff" into double quotes instead of single quotes.

@Avamander Oh.. yeah.. double quotes. That's embarassing. It's still not showing in the IDE but now I get sensible data with both screen and gtkterm. Oh my... I guess the problem with the AndroidStudio still persists but since it's working with the terminal I guess I should go see if they have an issue tracker somehere. Thanks, if there's a close-reason here for a problem that can no longer be reproduced or a simple typographical error I guess it won't be misplaced here.

Android Studio issue? Have you solved your issue you mentioned in the question or not?

It's not solved as I still don't see any data in the serial monitor but I've isolated the problem after fixing the quotes and using gtkterm to confirm that the Arduino is indeed sending data. I'm still diggin into why the IDE doesn't show it but I suspect it's not an error I've done but rather an issue with the software itself.

Edited to clarify that the issue has been narrowed down by the help received in comments.

What version of the IDE are you using? Also, can you add the output of an lsusb?

Are you 100% sure that your arduino is seen on your computer as /dev/ttyACM3 ?
if you unpug the arduino, run "sudo dmesg -C", plug the arduino and then issue "dmesg" what do you get back ?
My Arduino nano clone (with ch340) shows up as /dev/ttyUSB0.

@louigi600 I don't own either the arduino itself or the computer I was using any more, but if someone else has the same issue I encourage them to try that and provide information.

this is how my ch340 based nano clone is seen on my linux pc:
[14429.560354] usb 1-2.2: ch341-uart converter now attached to ttyUSB0
I don't have any genuine arduino products but I suspect you may have been looking at the wrong device file

What serial port are you running on?

I'm voting to close this old unresolved question because the asker reports in comments that  "I don't own either the arduino itself or the computer I was using any more" which means that it will be impossible to ever conclusively resolve this issue.

By default, on a linux system without specific
udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB* and not to /dev/ttbACM*. I suspect that you were just looking in the wrong place.
I think it defaults to /dev/ttyUSB* for any usb to serial dongle:
usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";

In order to make sure you're looking in the correct device file run "sudo dmesg -C" priot to plugging in the Arduino, and subsequently just 'sudo dmesg" to see where teh usb to serial converter was attached. You should see a message much like this:
ch341-uart converter now attached to ttyUSB0
where the ch341-uart is replaced by what your arduino has (most likely FT232'ish)

This is probably not applicable.  The post claims to be using an Uno R3, which does not have an FTDI but rather has a custom USB serial implementation in an ATmega16u2 which will map as a ttyACM device  not a ttyUSB one - that only happen on boards using other USB serial solutions, like older Arduinos and assorted clones and compatibles.

Ok but still doing the dmesg thing will tell you which is the correct device that linux is assigning to the arduino .... it won't show ch340 or FT* .... but it will still report what's the assigned character special file in /dev .


text:
Arduino Nano PWM output acting strange after running for a day or so
I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):
Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it here.
There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an int and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.
The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.
So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.
Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.
So, any ideas on what could cause this?

Update:
I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested here), which is kind of similar to the NMEA 0183 protocol (basically a simplified version of that). The sender sends the data in the following format now:

A single $ character to indicate the beginning of the data
The data itself (which is the textual representation of a single integer)
A single * character to indicate the end of the data
An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between $ and * (not including those). Letters (if any) are always uppercase.
The packet is finished up with either \n or \r\n

An example would be $178*3E\n, where \n of course means a newline character.
The code running on the Arduino now is the following:
#include <Time.h>

#define _analogWrite(a, b) analogWrite(a, 255-(b))
#define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

const PROGMEM int pwmPin = 3;
time_t lastUpdate = 0;
String incoming = "";
int pwmValue = 0;

inline void flushSerialBuffer() {
    while (Serial.available()) Serial.read();
}

void setup() {
    Serial.begin(9600);
    Serial.setTimeout(500);
    pinMode(pwmPin, OUTPUT);
    _analogWrite(pwmPin, 0);
}

void loop() {
    time_t currentTime = now();

    if (Serial.available()) {
        delay(250); // Just to make sure that all data has arrived in the buffer
        incoming = "";
        incoming = Serial.readStringUntil('\n');
        flushSerialBuffer();
        int b = incoming.indexOf('$') + 1;
        if (b == 0) return; // -1 was returned
        int e = incoming.indexOf('*', b);
        if (e == -1) return;
        int checksum = 0x0;
        for (int i=b; i<e; i++) checksum ^= incoming[i];
        String hexString = String(checksum, HEX);
        hexString.toUpperCase();
        if (hexString.length() < 2) hexString = String("0") + hexString;
        if (!hexString.equals(incoming.substring(e+1, e+3))) return;

        pwmValue = incoming.substring(b, e).toInt();

        if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
        lastUpdate = currentTime;
    }

    if (currentTime - lastUpdate > 30) pwmValue = 0;

    _analogWrite(pwmPin, pwmValue);

    delay(250);
}

It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.

Update 2:
Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.

The Arduino is outputting wrong PWM values; could you be more specific? Does "resetting" the program that is sending the serial data also fix the problem? Just something that I noticed, is that you don't actually check if a newline has been sent. If your loop reads the serial buffer while the x86 is still sending the data, your program could read e.g. 25, while the x86 is trying to send 250\n. Serial.readStringUntil('\n') could help in that case.

@Gerben Please read my comment here

How often are you sending values to the arduino?

It's in the question. Once every 5 minutes. Also, I should say that using Serial.readStringUntil('\n') creates potential bugs. Imagine if the other device sends faulty data, or maybe noise gets into the system, so there would be junk characters after the end line character. That command would only read up until and including that character, but no further. Anything after it would be left in the buffer and picked up by the next iteration of the loop, and that junk data could potentially be converted into an integer causing wrong output.

Edit: once every 5 seconds. Sorry.

You might consider having the Arduino echo back what it thinks it should do, and logging this on the PC.  Then you can very quickly grep the log for any spurious values.

Personally I would get rid of String and use arrays of char. You might be getting memory fragmentation. Also, names starting with an underscore in global scope (eg. _analogWrite) are reserved by the C++ Standard.

Yeah, you might be right. The thing that frustrates me the most about String is that it doesn't have any member functions like string::clear in C++. So whenever I want to get rid of the contents, I just go myString = "" in which case I have no idea what happens to the previous contents. I hope it properly deallocates everything. I would need to look into the implementation of String to be sure. I used it because it was more convenient than raw char arrays. But you might be right. Having everything under full control would be a good thing. I might rewrite it at some point.

After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.
Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.
You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the *, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.

The two devices are literally right next to each other, the cable that connects them is about 10 inches long. I don't think it's interference. Although I will implement characters that mark the beginning and end of the data plus a checksum value, that's always a good idea.

I did some modifications to the system based on your suggestions. See the updated part in the question. I'm still testing if it works properly now.

You have a
race condition in your
code: if you try to read a message while it's being sent, you may catch
only a partial message, and end up reading the wrong numbers. My bet is
that this is exactly what is biting you. Once this happens once, it is
bound to happen again for some time, since 5 seconds is a multiple
of your 100 ms delay.
The right thing to do would be to wait until you get the new-line
character (then you know you have a complete message) before trying to
parse the message. A quick and dirty hack is to just delay(10) after
Serial.available() but before Serial.readString().

Serial.readString() does have a timeout associated with it. In my case it's 250 milliseconds. Which means the following: Serial.available() returns true, indicating that there's incoming data. Then Serial.readString() reads all data that it can read in the next 250 milliseconds which is plenty enough time for the transmission to finish, and the entire data to be in the buffer. This is what guarantees that the entire message is read correctly. So I'm constantly reading the input for 250 milliseconds.

If Serial.readString() did not have a timeout, but instead just read the buffer exactly once, and returned, you would be right. But instead it waits a certain amount of time before returning, waiting for potential incoming data. Since I don't think that transferring a couple bytes at 9600 baud takes anywhere near 250ms, this should be fine.

I checked the source code of Stream::readString(). You are right, it waits for every byte. I thought it would only wait for the first, the documentation is not clear about that. Then, I cannot see the problem with your code. I can only suggest you echo back what you read, with some extra delimiters to show what you interpreted as message boundaries. This could hint you about what is going on.

Yeah maybe. The problem is that it's very hard if not impossible to reproduce the problem on demand. I'll try though.

@adam10603: If you send the messages at a higher frequency, the problem is likely to show up sooner.

I changed the code around, and I ran into some different issues while doing so, but I managed to fix those, so now I have a different piece of code that's seemingly working right now. We'll see how this code performs if I leave it on for a day. I basically changed how the data from the serial port is read and interpreted. Sadly, I'll be leaving for the next week, so I can only get back to this the next weekend. I'll let you know what happened!

Here is the current code I'm trying out

Your problem may be related to the dynamic memory allocation of your String objects. Each time the Arduino receives data, you are creating two new String objects. Perhaps the memory is not being released properly, causing eventual exhaustion of your RAM.
You could make your Strings global and empty them out each time, but a far better solution would be to replace all your string manipulation with a call to Serial.ParseInt() so your big if block becomes
if (Serial.available()) {
        pwmValue = Serial.ParseInt();
        while(Serial.available() > 0 {
          Serial.read();    // flush anything after the integer
        // Save the current time
        lastUpdate = currentTime;
    }
Serial.ParseInt also makes use of the timeout so you don't have to worry about partial values being read.

This is exactly what I did :) See my comment here. I'm still testing it

In the posted code, no String survives the return from loop().

The Strings don't survive but apparently the heap can still get fragmented and eventually run out of space. I have not verified that this is what is causing the problem here, but I think the code I suggested above is more robust.

I tried the original code and it does not appear to have a memory problem. See 2nd answer below.


text:
Shaft Encoder Accuracy
So, first of all I just want to point out this code is from: Reading Rotary Encoders and is not mine.
I have a magnetic shaft encoder mounted on a regular DC motor, my problem is that I cannot receive the exact angle of the motor. The encoder outputs +1 each 90 degrees (I then multiply by 90). And is there any relationship between valx, valy, valz and the angle?
#define encoder0PinA 2
#define encoder0PinB 3
int rounds= 0;
volatile unsigned int encoder0Pos = 0;
unsigned int tmp_Pos = 1;
unsigned int valx;
unsigned int valy;
unsigned int valz;

boolean A_set;
boolean B_set;

int enA = 9;
int in1 = 10;
int in2 = 11;

void setup() {

  pinMode(encoder0PinA, INPUT);
  pinMode(encoder0PinB, INPUT);
  // encoder pin on interrupt 0 (pin 2)
  attachInterrupt(0, doEncoderA, CHANGE);

  // encoder pin on interrupt 1 (pin 3)
  attachInterrupt(1, doEncoderB, CHANGE);
  Serial.begin( 9600 );

  pinMode(enA, OUTPUT);

  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(enA, 225);
  Serial.begin (9600);
}

void loop(){
//Check each second for change in position

  if (tmp_Pos != encoder0Pos) {
    Serial.print("Index:"); Serial.print(encoder0Pos * 90,DEC);
    Serial.println();
    Serial.print("valx:");Serial.print(valx,DEC);
    Serial.println();
    Serial.print("valy:");Serial.print(valy,DEC);
    Serial.println();
    Serial.print("valz:");Serial.print(valz,DEC);
    Serial.println();
    tmp_Pos = encoder0Pos;
  }
}

// Interrupt on A changing state
void doEncoderA(){

  // Low to High transition?
  if (digitalRead(encoder0PinA) == HIGH) {
    A_set = true;
    if (!B_set) {
      encoder0Pos = encoder0Pos + 1;
      valx=analogRead(0);
      valy=analogRead(1);
      valz=analogRead(2);
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinA) == LOW) {
    A_set = false;
  }
}

// Interrupt on B changing state
void doEncoderB(){

  // Low-to-high transition?
  if (digitalRead(encoder0PinB) == HIGH) {
    B_set = true;
    if (!A_set) {
      encoder0Pos = encoder0Pos - 1;
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinB) == LOW) {
    B_set = false;
  }
}

Provide a link to the rotary encoder used.

Wiring?  Picture?

If the motor speed is fairly steady with only gradual speed up slowdown, you may be able to model it with a software locked loop running faster and adjusted to match the timing of the four pulses you do get.  You can then use that to interpolate the likely position at any point in time to a higher resolution.

If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.
In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

My project is a data loger where three analogue inputs are sampled
  each time a rotary encoder pulse steps clockwise. On an Arduino, time
  is of the essence to get this data sampled and saved somewhere (I have
  not included the 'saving somewhere' part of this project yet.) In
  order to save some processor cycles, I have slightly redesigned the
  interrupt system to maintain a pair of boolean states outside of the
  interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.


text:
FCC Certification
I noticed that both the Uno and Wifi101 are FCC certified.  Does this mean that these components can actually be used in commercial applications?  This never really occured to me before I noticed the markings.
I'm sure there is more to a commercial product than just FCC certification but I know that the certification process isn't cheap!

FCC certification is not transfered just because components are certified. You can have a non-certified transmitter that is shielded so that the product becomes FCC certified. Anyway, please improve your question as it is relevant for anybody considering using Arduino as a starting point for a product.

Recommend changes.  I do not know what you mean by "improve your question."

@acpilot
in my opinion, your scenario makes the product compliant for commercial use as i beleive arduino guys got all required certificates before bringing products to the public Jake C
I am unable to comment due to less reputation points. thanks alot for your detailed answer.can i borrow your advise for this:if we are making an IoT product that contains this arduino mkr and couple of sensors like DHT11 etc, what kind of certifications needed apart from FCC?and do we need certifications for sensors that are collecting data only (temp sensor, smoke sensor, fire sensor etc)

These products are not certified, they merely have been verified and issued a Declaration of Conformity. The WiFi module on the WiFi shield itself has been certified, as indicated by the FCC ID on its label.
To explain what that means, I am going to give a simplified explanation. If you are looking to make a commercial product and you are not sure what you need to do to be compliant, hire out a professional to help you through the process.
In the eyes of the FCC, devices fall into one of two categories, devices that are intentional transmitters, and devices that are not. Devices that are intentional transmitters need to be certified. Certification is a process of making sure that it is only transmitting on the frequency band it specified, that it is maintaining certain power limits, and that it will not cause interference with other devices. This is a very expensive testing procedure.
Devices that are not intentional transmitters, only need to get a verification. What this means is that the devices is not designed to transmit anything and is test to makes sure that it indeed does not. If you pass the verification you are issued a Declaration of Conformity basically stating that the device is not unintentionally transmitting any frequencies. This is usually a lot less expensive than than certification (but still in the few thousand USD range).

So taking the WiFi shield as an example, the module shown above circled in red is an intentional transmitter, i.e. it is designed to transmit on a particular frequency band (in this case 2.4 GHz ISM band). The device is certified to make sure that its emissions are within FCC specifications and it is issued an FCC ID.
Now at this point only the module is certified and is good to be used in a product, however, now that it is on a shield with extra circuitry added to it, the extra circuitry could be unintentionally transmitting. So now the whole shield is tested to make sure that the added circuitry does not have any emissions exceeding the FCC specifications and is issued a Declaration of Conformity.
So now fast forward to making your own thing, the module is certified, the WiFi shield and the Uno are verified, you add your own additional circuity around those components that may emit electromagnetic fields. You now may have to get your product verified to ensure that the added components to the system have not caused it to unintentionally emit radio frequencies.
The whole process, conditions, and requirements are a lot more nuanced than my description above. So this should in no way be used as the basis for product development or legal advice.
(Image borrowed from https://www.arduino.cc/en/Main/ArduinoWiFiShield101)


text:
Connecting Winbond W49F002U-12B to Arduino Mega
I am trying to connect a CMOS flash memory Winbond W49F002U-12B to an Arduino Mega, but failing.

What I did:

Read the Winbond W49F002U-12B datasheet. The key points are: CE - chip enabled; OE - output enabled; WE - write enabled and this table:

Wrote this code and uploaded to Mega2560:
int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
int CE = 50;
int OE = 49;
int WE = 48;

char ch;
char addrs[5];
unsigned long address;
unsigned int result;
void setup() {
  Serial.begin(9600);
  for(int i=0; i<18; ++i)
      pinMode(A_pins[i], INPUT);
  for(int i=0; i<8; ++i)
      pinMode(DQ_pins[i], OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(OE, OUTPUT);
  pinMode(WE, OUTPUT);
  digitalWrite(WE, HIGH);
  digitalWrite(OE, HIGH);
  digitalWrite(CE, LOW);

}

void func(unsigned long adr)
{
  for(int i=0; i<18; ++i){
    if(adr & (1ul << i)){
      digitalWrite(A_pins[i], HIGH);
      Serial.print("A_pins[");
      Serial.print(i);
      Serial.println("] = HIGH");}
    else{
      digitalWrite(A_pins[i], LOW);}}
  digitalWrite(OE, LOW);
  delay(100);
  for(int i=0; i<8; ++i){
    if(digitalRead(DQ_pins[i]) == HIGH){
      result|=1<<i;
      Serial.print("DQ_pins[");
      Serial.print(i);
      Serial.println("] = HIGH");}
  }
  Serial.println(result);
  digitalWrite(OE, HIGH);
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print("address = ");
   Serial.println(address);
   func(address);
   }
}

What this code is doing is basically after reading serial:
-> takes the value as address
-> changes pins A0-A17 to select particular address cell
-> changes OE to LOW
-> reads DQ0-DQ7
-> coverts those readings into int
-> prints result out.
Example of Arduino IDE Serial Monitor inputs/ouputs stuff:
address = 0
0
address = 1232
A_pins[4] = HIGH
A_pins[6] = HIGH
A_pins[7] = HIGH
A_pins[10] = HIGH
0
address = 131072
A_pins[17] = HIGH
0
address = 245760
A_pins[14] = HIGH
A_pins[15] = HIGH
A_pins[16] = HIGH
A_pins[17] = HIGH
0

Arduino Mega board is 100% functioning. I don't think Winbond w49f002u-12b is not working. Where am I wrong?

UPDATE: Here is fixed code:
int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
int CE = 50;
int OE = 49;
int WE = 48;

unsigned long address;
unsigned int result;
void setup() {
  Serial.begin(9600);
  for(int i=0; i<18; ++i)
      pinMode(A_pins[i], OUTPUT);
  for(int i=0; i<8; ++i)
      pinMode(DQ_pins[i], INPUT);
  pinMode(CE, OUTPUT);
  pinMode(OE, OUTPUT);
  pinMode(WE, OUTPUT);
  digitalWrite(WE, HIGH);
  digitalWrite(OE, HIGH);
  digitalWrite(CE, LOW);

}

void func(unsigned long adr)
{
  result = 0;
  for(int i=0; i<18; ++i){
    if(adr & (1ul << i)){
      digitalWrite(A_pins[i], HIGH);
    }
    else{
      digitalWrite(A_pins[i], LOW);}}
  digitalWrite(OE, LOW);
  //delay(100);
  for(int i=0; i<8; ++i){
    if(digitalRead(DQ_pins[i]) == HIGH){
      result|=1<<i;
    }}
  Serial.println(result);
  digitalWrite(OE, HIGH);
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print(address);
   Serial.print(": ");
   func(address);
   }
}

UPDATE: Changed code using PORTs, Thanks to @MikaelPatel for reminding about PORTs:
unsigned long address;

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

  DDRL = B00000000; //  DQ7-DQ0 42-49
  DDRA = B11111111; //  A7-A0   29-22
  DDRC = B11111111; //  A15-A8  30-37
  DDRG |= B00000011; // A17-A16 40-41
  DDRB |= B00000111; // WE, OE, CE

  PORTB = B00000110; // WE - HIGH, OE - HIGH, CE - LOW
}

void func(unsigned long adr)
{
  PORTA = adr;
  PORTC = (adr>>8L);
  PORTG = (adr>>16L);
  PORTB = B00000100; //OE - LOW
  Serial.println(PINL);
  PORTB = B00000110; //OE - HIGH
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print(address);
   Serial.print(": ");
   func(address);
   }
}

RESET is connected to 5 VCC. Windbond chip's pins are not shorted (checked). Breadboard is good, everything is connected.

That was a great update and it looks like you did the optimization. There are some small details if you intend to move towards a general device driver library but this is a good starting point! Nice work!

What this code is doing is basically after reading serial: ... -> reads DQ0-DQ7

But all the DQn pins are in OUTPUT mode and the A pins in INPUT mode. Seems to be a mix up. BW: it is the same with all of the pins. The pin mode is from the Arduinos point of view and not the memory chip.
Cheers!

Hi. Maybe I'm understanding you incorrectly, but from Arduino board point of view, atmega2560 controls/sets address A, and then reads DQ, therefore A - output, DQ - input

Your code says the opposite. Check the setup().

omg, what a dumb. I am ashamed. Such stupid mistake. Thank you for pointing this out. Now it works :D

You might want to consider using the port directly and assigning the address and read/write data in a single operation. With all the digitalWrite() and digitalRead() this will more less be the same performance as a serial EEPROM on I2C. An SPI EEPROM/Flash would be faster.

I just have this chip. Just wanted to read data, to use it in some way. Don't want to throw it out. But what do you mean saying "using the port directly"?

You can get 100X performance by using the port directly. http://tronixstuff.com/2011/10/22/tutorial-arduino-port-manipulation/. For instance, connect A0-A15 to D22-D37 allows setting all 16-bits in two write operations (PORTA and PORTB). A16-A17 to D40-41 requires a two bit update (PORTG). And last DQ0-DQ7 to D42-D49 and port access (PORTB) in single operation. You are doing 100X more operation than needed to access the memory.

Thanks, I will try it. Now I'm trying to write some data. Could you please help me? The "Byte Program" operation requires 4 cycles: 5555:AA, 2AAA:55, 5555:A0, Ain:DQin. Did I understand correctly that cycles are ruled by WE signal?

And yes, I have to erase chip's memory before writing anything


text:
Is it OK to Serial.print(message), when the USB cable is not connected to a host PC?
Often I put a bunch of Serial.print( F("debugging messages") ) in my Arduino sketch.
Normally those messages go up a USB cable to a host PC so those messages can be seen on the serial monitor.
I want to install this Arduino as part of a stand-alone system far from any PC and plug the "host" end of the USB cable into a wall-wart USB charger.
Without anything to accept those messages, the buffer on the Arduino eventually fills up, right?
Do I need to do anything to keep the Arduino from overflowing and crashing when it's not connected to a host PC?
Does it make any difference if I'm using a (1) "single-chip" Arduino-compatible where the processor includes on-chip USB, vs. (2) an Arduino-compatible with separate "USB interface chip" and "processor chip"?
(By "single-chip Arduino-compatible", I mean things like the Arduino Leonardo, Arduino Yún, LilyPad Arduino USB, Arduino Micro, the Teensy-LC, etc.)

It is OK to write out serial data with nothing connected.
In case (2) "Arduino + USB interface chip", the arduino has no idea if anything is connected or listening to the serial port. The code will transmit the bytes and act exactly the same whether plugged in to anything or not.
In case (1) "arduino with built in USB" it has some idea, but just drops bytes that are going to be transmitted when the USB port is not connected.
Hardware serial (case 2) has an output buffer, but that just makes the program a little faster. When the buffer is empty, a call to serial.{print, write} will place bytes in the buffer and move on. When it's full, Serial.{print,write} will wait until there is enough room to put the rest of the message in the buffer and move on. The hardware UART and interrupts it generates will keep taking bytes out of the buffer and transmitting them at a constant rate whether something is plugged in or not. In any case, the buffer is a fixed size and will never overflow.
As far as I can tell USB-Serial (case 1) only buffers incoming data. Since the calls to Serial.{print, write} do nothing when not connected, they may take less time than they would otherwise. If your code is really unsafe about timing, that could cause a problem, but I doubt it will.
Many examples that come with the Arduino IDE have the following bit of code that pauses native USB Arduino-compatibles until the USB connection is initialized:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

This code stops the Arduino from doing anything until the USB cable is connected.
Comment out or delete those 3 lines if you want the Arduino to run "stand-alone" without a USB cable connection (Arduino Cookbook p. 117) --
after you delete those lines, if you later plug in a USB cable, the USB will initialize correctly, and then you will see on your serial monitor everything printed by any later Serial.print() commands that run. (Tested on a Teensy LC).

When it's full, Serial.{print,write} will wait - to clarify, it fills up because of speed (ie. you are printing too fast) not because there is nothing connected.

In case (1), when you say "drops bytes that are going to be transmitted when the USB port is not connected" do you mean it transmits them (maybe into nothing) through hardware TX?

Sorry, @NickGammon, but it seems to me that, at least on a Leonardo-based board (with in-CPU USB support), if I upload a quite complex sketch with plenty of Serial.print (tested at both 9600 and 115200), I see that: 1) if I power-up the board, with external-USB connected to a PC; everything work perfectly. And still work if I "disconnect" the cable; 2) if I power-up the board WITHOUT any cable connected, the board never enter even the main loop()! - It seems to me that when buffer "fills", everything hang.
Is this an expected behaviour (...that I should circumvent at app level)?

Sketches with the Leonardo style chips with onboard USB often have a loop in setup : while (!Serial.available()) { } which loops indefinitely until the serial connection is established via the USB. It will be this loop that causes it to appear to hang. On the other boards that call returns immediately and any data sent just disappears "off the end of the wire" if nothing is plugged in. You could always make that loop exit after (say) 10,000 iterations, or after a couple of seconds have elapsed.

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


text:
Code to control servo with shield
I recently bought an Arduino MEGA2560 and a SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control.
I understand how to control a servo in the method described in Sweep. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?
Please help me I am a beginner in robotics and I need this for a project.

Add more info about this shield.

I got the shield at this link: http://www.sainsmart.com/sainsmart-instabots-robot-controller-shield-for-arduino-mega2560-r3-robot-arm-control.html?gclid=CKDOq-7Mh8sCFVZbhgodfeUBWQ

However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

With the limited amount of info you have provided about the shield this will have to be a wild guess. I am assuming that the pins are S(ignal), V(cc) and G(nd) for pins 8-13. On an Arduino Mega these can be used for PWM and therefore Servo control.
Include the Servo library, attach the pin and set the angle.
#include <Servo.h>

Servo servo[6];

void setup()
{
  ...
  for (int i = 0; i < 6; i++)
    servo[i].attach(8 + i);
  ...
}

void loop()
{
   ...
   servo[i].write(pos);
   ...
}

Cheers!
NB: Do not forget to provide the correct power supply. If USB Port is left, then the upper pin is positive and the lower pin negative.

Wouldn't the servo.attach() number refer to the pin area near the green light?

@samuelli97 - Yes, you could use the output pins (near the green light), but for ease of use, the servos are (usually) connected to controller shields via a three pin plug, which plugs straight into the 6 sets of SVG pins, on your board. You will first need to solder 6 sets of 3 pin headers (which should have come with the board) to the PCB holes, that you have outlined in red, in order to be able to plug the servos in. As Mikael also states, you will also need to attach an external power supply to the green terminals as the Arduino can not supply enough power to the servos by itself.

Sainsmart STILL refuses to supply documentation for this board.Supposedly, it can control 6 servos and two motors, up to 4 Amps, with digital encoder inputs. There is NO documentation on the hardware or the software for the mega to drive this.

The SVG connectors on your board appear to be lacking header pins:

These should have been supplied with the board. If not you will need to source some. Either way, you will need to solder them on. I don't understand why they are not already attached.
If you look at the other images of the board on the SainSmart web page, the header pins are clearly visible:

The S pin of each SVG is the same as the output pins, near the green light, but for ease of use, they are replicated in the SVG pins, so that a servo plug can be easily, and conveniently plugged in, with out the user having to wire up power and ground separately.  If you look at the plug attached to the end of the cable coming from your servo, you will see the servo connector, like so:

As the board has arranged the pins in the SVG order, that means that it will support the Futaba J type connectors (but not the Airtronics, as the power and ground pins are reversed):

Also, Hitec and JR Radio connectors are supported by your board, as they have the same pin out:
.
For more information, take a look at Choosing RC Servos.
In addition, as Mikael says, you will also need to attach an external power supply to the green terminals

as the on board power regulator of the Arduino can not supply enough power to the servos, via the shield, by itself, neither with the USB, nor an external wall wart PSU, supplying power to the Arduino. So, use a bench power supply, battery pack, or otherwise and supply that power directly to the board via the Green power terminals at the end of the board.
Once you have done all of that, and got the hardware out of the way, then the software provided in Mikael's answer will work perfectly.

I have the header pins I can solder them without a problem. Do I need to connect my battery to the shield, or can I attach it to the Arduino?

Sorry you said that it has to be directly to the shield. Thank you so much!


text:
Loop behaves oddly in I2C receiveEvent
I am messing around with an ATmega328P hooked on a Raspberry Pi, communicating over I2C. The ATmega is the slave (details at the end). While testing the basics of the concept, I faced an interesting problem.
This is the code on the ATmega:
#include <Wire.h>

#define SLAVE_ADRESS 0x1A
#define LED 6

int count = 10;
void setup()
{
    pinMode(LED, OUTPUT);
    /*for(int i=1; i<=3; i++)
    {
      digitalWrite(LED, HIGH);
      delay(100);
      digitalWrite(LED, LOW);
      delay(100);
    }*/
    Wire.begin(SLAVE_ADRESS);
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);
}

void loop()
{
  delay(10);
}

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

void requestEvent()
{
  Wire.write(count);
}

What you would expect it to do is blink the LED connected to pin 6 five times when the Pi sends a byte to the ATmega slave. (Things like if(1) are there because the code was much more specific originally.) The strange thing is that this is not the case:
The LED only blinks 1 time.
I honestly have no idea why. This "stdio-fitted" version of the problematic loop ran on the RPi as expected, prints 5*2 times:
#include <stdio.h>

int main()
{
  int j = 5;
  while(j>0)
  {
    printf("LED, HIGH\n");
    printf("LED, LOW\n");
    j-=1;
  }
  return 0;
}

Circumstances:

I compile the code in the Arduino IDE on the Pi, then upload it
using AVRDUDE to the ATmega with the Pi's GPIOs. No error messages
over the process.
The ATmega gets 3.3 V supply voltage from the Pi, and operates on
16.000 MHz. Only the LED and the Pi is connected to it.
The (Python) code I use on the Pi to write and read a byte is the following. Reading works well, and I know by tests that the ATmega actually receives the correct byte:

import pigpio
import time

pi = pigpio.pi()
atmega = pi.i2c_open(1, 0x1A)

for i in range(6):
    a = pi.i2c_read_byte(atmega)
    print a

pi.i2c_write_byte(atmega, 0x05)
time.sleep(1)

Side note. Better use for(;;) for controlling loops. Just one clear instruction vs three unrelated ones. Example: for (int j=5; j > 0; j--) do the same, it's shorter and express your intention clearly to any other programmer.

void receiveEvent(int received_bytes)
{
  while(Wire.available())
  {
    unsigned char i = Wire.read();
    if(1)
    {
      int j = 5;
      while(j>0)
      {
        digitalWrite(LED, HIGH);
        delay(300);
        digitalWrite(LED, LOW);
        delay(300);
        j-=1;
      }
    }
    delay(1);
  }
}

receiveEvent is an ISR (interrupt service routine). Don't do delay in an ISR. That will hang indefinitely. Thus the LED only blinks once. You could do delayMicroseconds for testing. In general an ISR should be short.

Interrupts
I2C

Thank you! So I should move as much as possible to the main loop from an ISR, or only avoid timed functions?

It is valid to receive the data in the ISR (make the global variable (buffer) volatile). After that, set a flag (also volatile) and do the rest in the main loop.

I should move as much as possible to the main loop from an ISR - yes you should.


text:
ICT Bill Accepter
I have a ICT a6-15scp-usd4-ii. I have all of the wires for it. I dont have the gambling machine it came out of and it was laying around. Is it possible to make a Light come on when a bill is put in? Can it be wired to the arduino to act as a switch per-say? If more info is needed let me know. I will make a tutorial for this if it works.

Bill acceptors are notoriously hard to work with because usually the datasheet and or manual are usually only available under NDA. You will probably just have to reverse engineer it.

ill give it a shot, but it is not looking good.

Looking at the only doc I can find, http://www.ict-america.com/docs/a6v6/A6.V6-MXP4.pdf it looks like if you have the A6 version there is an RS232 port somewhere, which means the most you would have to do is level translation. If you have the V6 it will be using MDB, which is typically a 9-bit UART. There is an implementation of MDB found here: https://github.com/MarginallyClever/MDB-Sniffer

What kind of interface does your model have? Because when you have RS232 it should be fairly simple to see what it'll print out when you enter bills into it.

frst you're going to have to send an command to the bill acceptor to tell it to accept bills, they you just need to find the wire that pulses when a bill is inserted.

Go to ICT's website to download the Installation manual (one used for many different models), there is info on the pinout for every pin on your model, along with recommended I/O interface circuit.
I am using a different model, but from what I know, if your model is a "Pulse" model, which means that when a bill is accepted, there are pulses that you can captured (the pulse width is pre-set by toggle switches, and the number of pulses depends on the value of the bill).
What I would do is to use interrupt to listen to these pulses. When the interrupt triggers, light up your LED.

So I know this is an old post, but I have interfaced with a BV20, and noticed most of the ICT validator's have a "busy" line that is asserted whenever the unit is transporting, validating, or storing/stacking a bill.  If you want to light something up when a bill is being handled, but not necessarily validated, that might be what you are looking for.

ICT a6-15scp-usd4-ii is a pulse/parallel bill acceptor. Here is the datasheet, the link in the comments is broken. A6 version uses pulse/parallel protocol (V6 version is MDB). The 110V version that you use has only pulse protocol.
Take care with the wiring, the acceptor uses dangerous  110VAC voltage.
I understand you want to make same kind of pay per time device like those used in kiddie rides machines.
There are many examples on the internet on connecting a pulse bill acceptor to Arduino. The theory is simple the bill acceptor has a PULSE output, usually in negative logic, high in idle, that send a low pulse for each monetary unit, 1 for 1$, 5 for 5$ and so on.
Sometimes, like in your case, the bill acceptor has an enable input through which you can enable or disable the acceptance. But in A6 110V this input must be connected to hot 110v lines so it's harder to handle through Arduino so you will need to use a relay or to leave-it active all the time by setting dip SW 8 to ON, see page 6 and page 9 in the manual.
The electrical connections.
See the connector pinout , page 5
The credit (pulse) output uses an optocoupler so it has two lines CREDIT_RELAY_COM (pin 1) on the above connector that must be connected to Arduino GND and CREDIT_RELAY(N.O.) (pin 16) that must be connected to the digital input of Arduino that read the pulses, this digital input must have a pull-up resistor to 5V, it might be the built in pull-up activated by using pinMode(PIN, INPUT_PULLUP) but better an external resistor 1k to 4.5k.
And, of course, the main power supply , pin 4 and pin 20 to main 110 voltage and don't forget the earth ground, pin 21 for safety.
Bill acceptor dip switch settings
See the page 6 of the manual. For the moment just put SW8 to ON (acceptor enabled) and all other to OFF (all bills enabled, one pulse one dollar, 50ms/50ms pulses)
The Arduino source code
To count the pulses from a pulse bill acceptor or coin acceptor there are many examples on the internet but I did one myself, very easy to use, find the source code here, that counts the pulses in background using timer1 interrupt. In this way the main loop is free for other tasks you need. You can strip the LCD part of the code if you don't use.
To work with ICT A6 you need to modify the some defines in the code: PULSE_WIDTH to 50 form 100 and PULSE_DELTA to at least 4 from 2 (because it's to small).
Connect Arduino A0 input to pin 16 (CREDIT RELAY) and to a pull-up resistor to 5V as I pointed above, and Arduino GND to pin 1 (CREDIT_RELAY_COM) and power the Arduino from some different source or through USB and the example should work now. Obviously the BILL_ACCEPTOR_ENABLE and BILL_ACCEPTOR_DISABLE macros will not work the acceptor is always enabled.
To actually make-it work as pay-per-time machine a suggestion of code will look like this:
unsigned long finish_time = 0;
#define MS_PER_DOLLAR 600000 //10 minutes
//add to setup
turn_off_the_light();// Switch a pin or something

void loop(){
  unsigned long temp_millis;
  unsigned long temp_credits;
  temp_millis = millis()
  temp_credits = read_and_clear_pulses();
  if (finish_time < temp_millis) finish_time = temp_millis;
  finish_time += tempcredits * MS_PER_DOLLAR;
  if (finish_time > temp_millis)
     turn_on_the_light();
  else
     turn_off_the_light();
// Do something else
}

If you use the device uninterrupted for more than 49 days you will have the millis rollover issue  but you can find examples on the internet how to handle this.