text:
Script on pc only gets 640 characters via serial
I experience that if the Arduino (Teensy 3.2) writes a rather long stream of characters to serial, the python script on the other end only receives the first 640 characters. I have found this result both by printing chars, printing lines and by using ArduinoJson's prettyPrintTo(Serial).
Note, that it does not matter what chunks of characters I read in the Python scripts, whether it is read(5) or read(1000).
With the Arduino Serial Monitor, I get all the data, ie more than the 640 characters.
From what I can understand, it is not possible for a sketch to write "too fast" or "too much" to the serial, so there must be something on the pc side receiving the data. However, the Python script for some reason does not get all the data.
What is the problem here? Where should I look for the problem/solution? Perhaps this is more a Linux or Python question, but I will try here.
Sketch - printLines()
void printLines() {
  for (int i=0; i<100; i++) {
    // length below is 40 incl end of line character
    Serial.printf("abcdefthijklmnopqrstuvxyz123456789--%03d\n", i);
  }
}

void setup() {
  Serial.begin(9600);
  delay(500);
  printLines();
  //printChars();
  //printJson();
}

void loop() {}

Sketch - printChars()
void printLines() {
  for (int i=0; i<1000; i++) {
    Serial.write('x');
  }
}

Sketch - printJson()
void printJson() {
  StaticJsonBuffer<10000> jsonBuffer;
  JsonArray &root = jsonBuffer.createArray();
  for (int i=0; i<700; i++) {
    root.add(i);
  }
  root.prettyPrintTo(Serial);
}

Python script
import serial

ser = serial.Serial('/dev/ttyACM0')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
for i in range(num_iterations):
    s = ser.read(num_chars)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))

Terminal output
jan@jan:~/Desktop/batlogger/localserver$ sudo python localserver.py
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
### i: 2, reading 100 chars, char 200 to 299, len(s): 100, total chars: 300
### i: 3, reading 100 chars, char 300 to 399, len(s): 100, total chars: 400
### i: 4, reading 100 chars, char 400 to 499, len(s): 100, total chars: 500
### i: 5, reading 100 chars, char 500 to 599, len(s): 100, total chars: 600
### i: 6, reading 100 chars, char 600 to 699, len(s): 40, total chars: 640
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 640
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 640
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 640

You're not actually using a serial connection there - you're using a USB CDC/ACM connection, which is a whole different ball game. Are you sure you're not just missing the first chunk of the data while you're sending without the python program running?

Typically CDC/ACM will discard characters if the port is not open at the remote end - or it will discard characters after the buffer is full. This is different to UART since a UART can transmit regardless of what is wired or not wired to it - CDC/ACM can only actively transmit if the port is open at the remote end.

I am sure I don't miss the first chunk, because when I ask it to print, it shows that the first 640 characters is the start of the data.

It could well be that the Teensy is able to buffer 640 bytes in the USB buffer and discards everything else. When you open the port on the PC it then receives the 640 bytes that have been buffered.  Make the Teensy wait for the port to be opened before doing any sending (while (!Serial);)

CDC/ACM packets are 64 bytes in size. It makes sense that there may be 10 packet buffers allocated, which makes 640 bytes.

@MadsSkjern Have you tried the suggestions in both answers? Any improvements or differences? Still reading exactly 640 chars every time?

You are not using a serial connection, you are using a USB CDC/ACM connection, and that is a very very different thing.
With a serial connection when you send data it gets sent regardless of whether there is anything listening for it - the TX IO pin toggles high and low regardless.
However, with a CDC/ACM connection it's only possible to send data when there is something actively listening at the remote end - that is, when the port /dev/ttyACM0 has been opened by an application.
Until that port has been opened any data sent will remain in internal buffers.  These buffers are 64 bytes each in size (that's the size of a CDC/ACM packet), and there are (I would guess) 10 of them on the Teensy3.  After these buffers are full, because there is nothing receiving the data, there can never be any more room made for more data, so instead of blocking like a serial connection does it just discards the data.
So you have filled the buffers with 640 bytes of data and thrown away the rest.  That data just sits there.
Then eventually you open the /dev/ttyACM0 port and the Teensy3 is now able to send CDC/ACM packets through the USB.  And it has 10 of those packets sat there waiting to go out, so it sends them.  So you receive the 640 bytes of data that you had buffered up.
Your mistake is basically not waiting for the port to be opened before sending data to the remote end.  You can test the state of the port (kind of, but that's a whole other subject) by examining the Serial object:
if (Serial) {
    // ... the port is open
}

In general you can usually just wait at the start of your program before starting anything else with a simple while:
while (!Serial); // Wait for the port to be opened

Great, while(!Serial) fixed it. I knew of that "trick", I know people write it. But I thought the serial connection was in place as long as the pc had "registered" the /dev/ttyACM0. Obviously there is no connection before some proces on the pc opens a connection, fx serial monitor or a python script.

I wouldn't be running as root. Why do that, just to execute a Python script?
Anyway, your problem is that you are not waiting for input. Your Python script is executing faster than the Arduino can pump out the bytes. At 9600 baud you send one byte every 1/960 of a second, so to send 4000 bytes (100 x 40) would take 4000 * 1/960 = 4.166 seconds. However your Python script powers along, getting the first 600 or so which may have been buffered already, and then finishes. You need to rewrite so you wait for a line to arrive. For example:
import serial

ser = serial.Serial('/dev/ttyACM0')

while True:
  s = ser.readline()
  print (s)

When I ran that I saw all 100 lines.
Of course, you need to modify that to break out of the loop. Maybe a special character would do that. Typically a newline is used.

PySerial's read function is blocking by default. - or it has a long timeout anyway

Not when I tested it. Using the code in the question, and without the Arduino even plugged in, I get:
### i: 0, reading 100 chars, char 0 to 99, len(s): 0, total chars: 0
### i: 1, reading 100 chars, char 100 to 199, len(s): 0, total chars: 0
### i: 2, reading 100 chars, char 200 to 299, len(s): 0, total chars: 0
### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 0
### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 0
### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 0
### i: 6, reading 100 chars, char 600 to 699, len(s): 0, total chars: 0
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 0
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 0
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 0

Execution time: 5.5 s.
Of course, the code sets the timeout to 0.5s. But that isn't good enough. You can't assume that 400 bytes will arrive within 0.5s. They should if both sides are perfectly synchronized (at 9600 baud it would take 0.416s).
But serial doesn't work that way. You can't just read for 0.5s and hope everything you want arrives in that time. Heck, it may not have even started sending.

OK, I admit I tested with my Uno and not a Teensy, but this amended Python script shows similar results:
import serial

ser = serial.Serial('/dev/ttyACM2')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
result = ""
for i in range(num_iterations):
    s = ser.read(num_chars)
    result = result + str(s)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))
    print ("String = " + str (s))
    print ()

print ("-" * 70)
print ("Total output =")
print (result)
print ("Total length =", len (result))

Output:
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
String = b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'

### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
String = b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'

### i: 2, reading 100 chars, char 200 to 299, len(s): 21, total chars: 221
String = b'opqrstuvxyz123456789\xff'

### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 221
String = b''

### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 221
String = b''

### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 221
String = b''

### i: 6, reading 100 chars, char 600 to 699, len(s): 100, total chars: 321
String = b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'

### i: 7, reading 100 chars, char 700 to 799, len(s): 100, total chars: 421
String = b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'

### i: 8, reading 100 chars, char 800 to 899, len(s): 100, total chars: 521
String = b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'

### i: 9, reading 100 chars, char 900 to 999, len(s): 100, total chars: 621
String = b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'

----------------------------------------------------------------------
Total output =
b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'b'opqrstuvxyz123456789\xff'b''b''b''b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'
Total length = 669

Since the output of the Uno would be deterministic (it would do the same thing every time) the problem is in the way you are processing the data at the Python end. Look at the line numbers in the above list. They don't even start at 0.

PySerial's read function is blocking by default. - or it has a long timeout anyway

See amended answer.

The exact round value (640) every time suggests something more exact than a few characters getting lost every time though.

See even more amended answer.

My user does not have privileges to communicated with /dev/ttyACM0. Running with sudo is just temporary until I figure another way out.

See Changing permissions on serial port


text:
NewliquidCrystal example HelloWorld_i2c just flickers
I've bought a cheap I2C LCD display (specs in the end of this question).
I can't make it print. I've tested with two displays of same model, so nothing is broken.
I am using the NewliquidCrystal 1.3.4 library, ie not the "normal" LiquidCrystal library. I'm trying with the I2C example called HelloWorld_i2c (link to example code). I've only changed the address from 0x37 to 0x27.
It compiles fine, but the result is only that the display flickers.
What is wrong and how do I fix it?
Super simple example flickers too
Well, this one gives just one blink.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27);  // Set the LCD I2C address
void setup()
{
  lcd.begin(16,2);               // initialize the lcd
  lcd.home ();                   // go home
  lcd.print("Hello, ARDUINO ");
}
void loop()
{
}

Pictures
In the light it shows that the writing to the display is randomly jumping around.

In the dark, it shows that the background light flickers:

Details about the LCD display
Text on the backside
YwRobot Arduino
QAPASS
LCM1602 IIC V1

Text on the chip
TLPCF85747
HA
T62281
A N 1
I L knM988223

First hit on google: https://arduino-info.wikispaces.com/LCD-Blue-I2C - have you followed all that first?

This is probably an issue of wiring; include your schematic.

@Majenko: in fact I did look at that example before posting. I thought that did not work either; though in a different way; it just did not show anything. In fact the Arduino-Info example did work! But the display contrast setting was bad, my room is very bright, and most important: I was looking at it at a bad angle; and therefore I could not see any text. So if the contrast would have been set right, I would have had luck with the Arduino-Info example.

Regarding the HelloWorld_I2C example; by using this constructor call it worked: LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

@Majenko: If you like, you can post an answer; to use this other constructor.

Feel free to answer it yourself since it was you that worked out how to get it working. I merely showed you the path :)

I was able to make the example run as intended, by using a different constructor call:
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

I am not able to tell you, what these parameters and values mean. However, the documentation for this constructor is shown below (source).
/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d0[in] LCD data 0 pin map on IO extender module
    @param      d1[in] LCD data 1 pin map on IO extender module
    @param      d2[in] LCD data 2 pin map on IO extender module
    @param      d3[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C( uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3 )
;

Try to pull the I2C sensor at the back of the LCD board, you can see that it is shorted to the SMD mounted on the back,  just pull it a little so that it won't touch and short the conductors. This has happened to me, try it if this works.

source: Stack Exchange

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

sort: votes


text:
Arduino Mega different SPI Pins
I am working on a project that uses Arduino and Water Level Sensor MS5540C sensor that uses SPI to communicate with Arduino.
When I use Arduino UNO, it was working like a charm using pins 11, 12 and 13, and pin 9 as clock.
Then When I switched to Arduino MEGA, I changed SPI pins to 51, 50 and 52, and I can't get right reads input from the sensor.
Is there any tricks that should be used when switching between Arduino UNO and MEGA ?
Here's the code I use.
Thanks.
#include <SPI.h>
int clock = 9;

void resetsensor() //this function keeps the sketch a little shorter
{
 SPI.setDataMode(SPI_MODE0);
 SPI.transfer(0x15);
 SPI.transfer(0x55);
 SPI.transfer(0x40);
}

void setup() {
 Serial.begin(9600);
 SPI.begin(); //see SPI library details on arduino.cc for details
 SPI.setBitOrder(MSBFIRST);
 SPI.setClockDivider(SPI_CLOCK_DIV32); //divide 16 MHz to communicate on 500 kHz
 pinMode(clock, OUTPUT);
 delay(100);
}

void loop()
{
 TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
 analogWrite (clock, 128) ;

 resetsensor();//resets the sensor - caution: afterwards mode = SPI_MODE0!

 //Calibration word 1
 unsigned int word1 = 0;
 unsigned int word11 = 0;
 SPI.transfer(0x1D); //send first byte of command to get calibration word 1
 SPI.transfer(0x50); //send second byte of command to get calibration word 1
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 word1 = SPI.transfer(0x00); //send dummy byte to read first byte of word
 word1 = word1 << 8; //shift returned byte
 word11 = SPI.transfer(0x00); //send dummy byte to read second byte of word
 word1 = word1 | word11; //combine first and second byte of word

 resetsensor();//resets the sensor

 //Calibration word 2; see comments on calibration word 1
 unsigned int word2 = 0;
 byte word22 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0x60);
 SPI.setDataMode(SPI_MODE1);
 word2 = SPI.transfer(0x00);
 word2 = word2 <<8;
 word22 = SPI.transfer(0x00);
 word2 = word2 | word22;

 resetsensor();//resets the sensor

 //Calibration word 3; see comments on calibration word 1
 unsigned int word3 = 0;
 byte word33 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0x90);
 SPI.setDataMode(SPI_MODE1);
 word3 = SPI.transfer(0x00);
 word3 = word3 <<8;
 word33 = SPI.transfer(0x00);
 word3 = word3 | word33;

 resetsensor();//resets the sensor

 //Calibration word 4; see comments on calibration word 1
 unsigned int word4 = 0;
 byte word44 = 0;
 SPI.transfer(0x1D);
 SPI.transfer(0xA0);
 SPI.setDataMode(SPI_MODE1);
 word4 = SPI.transfer(0x00);
 word4 = word4 <<8;
 word44 = SPI.transfer(0x00);
 word4 = word4 | word44;

 long c1 = word1 >> 1;
 long c2 = ((word3 & 0x3F) << 6) | ((word4 & 0x3F));
 long c3 = (word4 >> 6) ;
 long c4 = (word3 >> 6);
 long c5 = (word2 >> 6) | ((word1 & 0x1) << 10);
 long c6 = word2 & 0x3F;

 resetsensor();//resets the sensor

//Temperature:
 unsigned int tempMSB = 0; //first byte of value
 unsigned int tempLSB = 0; //last byte of value
 unsigned int D2 = 0;
 SPI.transfer(0x0F); //send first byte of command to get temperature value
 SPI.transfer(0x20); //send second byte of command to get temperature value
 delay(35); //wait for conversion end
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
 tempMSB = tempMSB << 8; //shift first byte
 tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
 D2 = tempMSB | tempLSB; //combine first and second byte of value

 resetsensor();//resets the sensor

 //Pressure:
 unsigned int presMSB = 0; //first byte of value
 unsigned int presLSB =0; //last byte of value
 unsigned int D1 = 0;
 SPI.transfer(0x0F); //send first byte of command to get pressure value
 SPI.transfer(0x40); //send second byte of command to get pressure value
 delay(35); //wait for conversion end
 SPI.setDataMode(SPI_MODE1); //change mode in order to listen
 presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
 presMSB = presMSB << 8; //shift first byte
 presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
 D1 = presMSB | presLSB;

 const long UT1 = (c5 * 8) + 20224;
 const long dT =(D2 - UT1);
 const long TEMP = 200 + ((dT * (c6 + 50))/1024);
 const long OFF  = (c2*4) + (((c4 - 512) * dT)/4096);
 const long SENS = c1 + ((c3 * dT)/1024) + 24576;

 long PCOMP = ((((SENS * (D1 - 7168))/16384)- OFF)/32)+250;
 float TEMPREAL = TEMP/10;
 Serial.print("pressure =    ");
 Serial.print(PCOMP);
 Serial.println(" mbar");

 const long dT2 = dT - ((dT >> 7 * dT >> 7) >> 3);
 const float TEMPCOMP = (200 + (dT2*(c6+100) >>11))/10;
 Serial.print("temperature = ");
 Serial.print(TEMPCOMP);
 Serial.println(" °C");
 Serial.println("************************************");

 delay(300);
 }

Transferring Pin 9 to 12 truly works. Thanks.

The problem was basically because some limitations in Arduino MEGA,
You can't use pin 9, instead use pin 12.
It works like a charm.
Thanks.

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


text:
10 bit PWM on Arduino UNO
I am using this code to make 10 bit PWM on port number 9, it seems like everything printed is 0,1022 rather than printing 0, 512, 1023. Is there a problem in my code ?
I wired pin9 to A3 to get the output and print it.
  void setup() {
  Serial.begin(9600);
  pinMode(A3,INPUT);
  // Set PB1/2 as outputs.
  DDRB |= (1 << DDB1) | (1 << DDB2);

  TCCR1A =
      (1 << COM1A1) | (1 << COM1B1) |
      // Fast PWM mode.
      (1 << WGM11);
  TCCR1B =
      // Fast PWM mode.
      (1 << WGM12) | (1 << WGM13) |
      // No clock prescaling (fastest possible
      // freq).
      (1 << CS10);
  OCR1A = 0;
  // Set the counter value that corresponds to
  // full duty cycle. For 15-bit PWM use
  // 0x7fff, etc. A lower value for ICR1 will
  // allow a faster PWM frequency.
  ICR1 = 0x03ff;
}

void loop() {
  // Use OCR1A and OCR1B to control the PWM
  // duty cycle. Duty cycle = OCR1A / ICR1.
  // OCR1A controls PWM on pin 9 (PORTB1).
  // OCR1B controls PWM on pin 10 (PORTB2).
  OCR1A = 0x0000;
  delay(500);
  Serial.println(analogRead(A3));
  OCR1A = 0x0200;
  delay(500);
  Serial.println(analogRead(A3));
  OCR1A = 0x03ff;
  delay(500);
  Serial.println(analogRead(A3));
}

The output looks like that:
  0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

no data between 0 and 1022 are presented.
thanks.

Do you know even what PWM is...?

If you want, you can teach me

Or you could ask Google...

On your code, you using analogRead but declaring the pin (A3) as output. Change it to pinMode(A3,INPUT);
Aside from that, PWM is basically a digital output which changing (HIGH and LOW) at specified frequency. When the result you got is

0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

There's nothing wrong. 0 --> LOW, and 1021++ --> HIGH
If you want "measure" something from the PWM, use pulseIn() instead, you can check the documentation here.
If you want to measure the PWM value, I suggest you read:
Can I connect a PWM pin on one Arduino to an analog input on another?

Thanks for your note, I just got output like that, which is wrong I guess.
0
0
1022
1021
0
1022
1021
0
0
1021
0
1021
1021
0
0
1021
0
0
1022

I update my answer

Thank you, does that allow me to make arduino output analg data like a potentiometer ?

Based on @Russell answer from the link above, yes.

but, why I don't write that code when I use a potentiometer for example ?

unless you put capacitor and resistor, (to make the signal "less square"), analogRead will keep returning HIGH and LOW value. While the other way is measure the time difference between pulseIn(3,HIGH) and pulseIn(3,LOW). That way you can get the duty cycle, which mean, calculating the rest is possible.


text:
Arduino add two spi slaves that has no slave select pin
I am working on a project where Arduino is communicating with two devices using SPI. Unfortunately, these two devices has no ss(slave select) pin to communicate with each one separately.
How Can I solve this issue?
Sensor example
Thanks

Then, they are really not SPI devices.  Are you sure they are not I2C where different devices have different addresses?  More information like part numbers would help here.

No, They are using SPI serial interface

I just edited it to show example of SPI examples I mean

Ss or cs pin ISS not mandatory for SPI.
A few solutions.

Power on or off the devices. A group pin can do that.
Cut off mclk.
Have a separate sclk pins for individual chips. You will need to share the serial data pins, ored with some diodes or pull up.
Software SPI.

...
I'm sure others will come up with more solutions.

Looking at the MS5540C specifications and assuming there are no other significant parts on the PCB you identified, there does not appear to be a SPI port available.
Neither "SPI" not "I2C" appear in the document.  Please check your self to verify.
Instead there is a section on serial communication with the MS5540C part its self.  In this section there are a number of diagrams.  Here is one:

In the text we find this:

Every  communication  starts  with  an  instruction  sequence  at  pin
  DIN.  Fig.  6  shows  the  timing  diagrams  for  the  MS5540C.

Which is very nearly if not exactly how I2C works.
The text goes on to say:

he  device  does  not  need  a  ‘Chip  select’  signal.  Instead
  there  is  a  START  sequence  (3-Bit  high) before  each  SETUP
  sequence  and  STOP  sequence  (3-Bit  low)  after  each  SETUP
  sequence.  The  SETUP  sequence consists in 4-Bit that select a
  reading of pressure, temperature or calibration data. In case of
  pressure- (D1) or temperature- (D2) reading the module acknowledges
  the start of a conversion by a low to high transition at pin DOUT
  during the last bit of the STOP sequence.

Unfortunately, this design appears to prohibit using more than one identical device on the same serial bus.
Workarounds to this design flaw (if it truly exists) include blocking the SCLK or the DIN signal to the un-selected MS5540C.
In many other cases where multiple identical I2C devices are used on the same bus, vendors provide a pin on the device which can be used to alter the address of an individual device.

They also use 15 bit words, which I'm not even sure the Arduinos SPI supports. I'd just bitbang the protocol, and use different pins for the two sensors.

Sounds like a plan.  But again, it does not look like a SPI bus device.  I know the web page you linked to / bought the device from lists SPI.  But I believe this to be in error. The Chip Select or Slave Select line on a SPI bus is necessary!  It is the only way for the slave and master SPI devices to synchronize.  With out this line, if either device looses sync, they will never be able to talk to one another with out being power cycled.


text:
How do I know how many memory that Arduino is use after my code is running for a few time
When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload.
How do I know the current size of memory that Arduino is use?
I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.
Note: I am using the Board: Arduino Mega 2560.
I read the question and the answer for Measure SRAN usage
In the question @fuenfundachtzig ask:
Can I determine how much SRAM I have left in the live system?
In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.
I am tryin to know in an specific time what is the size of my memmory.
example...
void setup() { //doing some configuration };

void loop() {  // invoke some functions and evil function  };

// in other place a evil function

void evil(){
MyClass * instance = new MyClass();
//play with the instance and it class create other instances....
//and a dynamic memmory is used but not deleted.
}

I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.

memory used = total memory − free memory.

You should not just say your question is different, you should explain how it is different. Be specific about what you are asking for. At this point, it still looks like a duplicate.

Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.
You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).
You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.

I will try with the function that Edgar post, thank you for the answer and comments.

authors: Владимир Шопов


text:
How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?
I'm looking for a broadly applicable solution, one that can be adapted to a variety of projects.
I'm currently working on several projects that each require controlling devices ranging from 800mA to 2A from an Arduino Uno. One controls stepper motors, one controls 12vdc solenoid actuators, and one controls 12vdc pneumatic valves.
For example:
The Arduino monitors a button, and each time the button is pressed it triggers the solenoid actuator. Because the Arduino is unable to source the current required by the solenoid, a seperate power supply is required with the Arduino controlling a switch (relay, transistor, etc.) that allows the higher current to pass. For the stepper motor, the layout is more complex as there would need to be four pins controlling four separate switches (to maintain interoperability of the circuit). The relay controls an air valve and requires 12vdc as well.
I'm trying to figure out how to use a single circuit that can be used in each of these applications (and any future projects) that involve controlling higher current devices than the Arduino pins can handle.
Prototyping speed, standardized components, and low cost are the driving factors. Switching speed, useful life, and noise are also important.
Is there a breakout board, circuit, or component that can be connected to an Arduino pin and used to control a high current device? Ideally with a software controlled potentiometer so that the resistance for different projects could be set in the sketch itself.

So what would this board be controlling? The resistance or voltage? Or the device itself?

The board would be controlling the device itself. I've added details to the question.

Define "high current".

To drive such high currents, you may have to cascade several transistors (you can also use a Darlington transistor). There are arrays of Darlingtons mounted in a chip (e.g. the ULN2803A has 8 darlington transistors, but is limited to 500mA).
You probably will have to deal with higher power transistors; as an example I have found STMicroelectronics TIP110 which can support switching a 2A current (4A peak), but it would probably need a heatsink to dissipate heat.
Note that I wonder if your steppers really need 2A current (are they that big?). For steppers, you can generally find IC that can drive them easily, e.g. the L293D but this one can drive "only" 600mA).
As a conclusion, I am afraid you will not find a "one size fits all" solution, as all your devices are different and should be driven by the appropriate circuit.
Edit:
Since oversizing is not an issue in your prototyping case, then you could go with a MOSFET instead of usual bipolar transistors. A MOSFET will be able to drive higher currents and voltages than standard transistors.
The downside is you can use it as a switch only (like e.g. a relay) and thus can't really drive the exact power for your devices. I guess that does not matter for a Stepper motor, or a Solenoid, but that may be important for driving lights for instance.
However, the good point is that you can still use PWM for that as the MOSFET switching speed is good enough for such purposes.
Regarding price, there are many diferent kinds of MOSFET out there, but I guess you can find one that fits yours needs (12V, 2A) for less than $1.
I advise you to take a look at this great article about this topic.

The 2A is for the solenoids. I understand that one size fits all is a challenge and not ideal for production. In this case the purpose is faster prototyping, where over building is acceptable.

Note that even with a TIP110, you will probably have to add a smaller transistor in between it and the Arduino output pin, as a TIP110 can draw 50mA on its base, which is much too high for an Arduino pin.

I think TIP 120 is ideal for this, according to datasheet, it is capable of handling currents up to 5A & 6V - https://www.fairchildsemi.com/datasheets/TI/TIP120.pdf

There are lots of ways to switch higher loads, and jfpoilpret has described some good options. I'll summarise a couple of relay-based solutions, which are mainly appropriate for comparatively slow switching speeds (i.e. not usually suitable for PWM).
Solid State Relays
Solid State Relays (SSRs) are effectively semiconductor-based switches. They come in a wide variety of configurations, depending on your requirements, but the key factor is that they have no moving parts. This means they can be very reliable in the long run if used properly.
Internally, they are usually comprised of MOSFETs and thyristors or similar. This can let them achieve fairly high switching speeds in theory. In practice though, the more power it's designed for, the harder it is to switch quickly. That means high speed + high power can get quite expensive.
A critical factor to bear in mind is that you'll usually need a different type of SSR if you intended to switch AC instead of DC. It's also good to note that some will come with a built-in opto-isolator or similar to keep your power supplies separate.
Electro Mechanical Relays
This is the more 'traditional' approach. An Electro Mechanical Relay (EMR) is a fairly simple component, containing a mechanical switch, controlled by a electromagnetic coil. If the switch is normally open, the coil pulls it closed when a control current is applied. In contrast, a normally-closed switch would be pulled open when a control current is applied.
There are a number of advantages of EMRs over things like SSRs. The most obvious is cost -- their simplicity makes them quite cheap, and the cost doesn't rise so sharply for higher-power versions. Additionally, the control and load are inherently isolated, and they don't care whether you're switching AC or DC.
There are several disadvantages though. The mechanical aspect means that EMRs are usually much slower than non-mechanical switching solutions, and can suffer from contact bounce. Additionally, they can physically wear out, and they can be affected by things like shocks, vibrations, and (potentially) other magnetic fields.
When designing a circuit to use an EMR, it's essential to be aware of back-EMF (electromotive force). When a control current is applied, the coil acts as an inductor, storing charge electromagnetically. When the control current is stopped, the stored charge can surge back through the control circuit, creating a large negative voltage spike (potentially much larger than what was originally applied).
This spike can unfortunately damage/destroy any attached components or microcontroller pins. It is typically prevented/mitigated by putting a diode in reverse across the relay's control contacts. In this context, it's sometimes known as a flyback diode, and it allows the EMF to dissipate safely.

Would you say that a MOSFET used as described in the article linked by jfpoilpret would be a suitable alternative to the electromechanical relay for these applications?

Yes, for the applications you've described, I expect a MOSFET would be sufficient. Just remember that they're sensitive to static discharge though, so take suitable precautions when handling them.

As jfpoilpret already said, a power MOSFET is great for turning ON and OFF the 12 VDC power to devices that pull up to 44 A. There are dozens of such power MOSFETs for under $1 each. More expensive MOSFETs are available that can handle much higher current and voltage.
In principle it is possible to drive a stepper motor with a microcontroller and a handful of transistors and a few other little parts.
However, many people prefer to use a "stepper driver chip", so it is impossible for a software bug to accidentally turn on transistors in such a way as to short the power supply to ground (typically destroying at least 2 transistors).
Many recent stepper driver chips also handle microstepping, current limiting, thermal overload protection, and other nice features.
All the stepper driver chips that I've ever heard of, and a few off-the-shelf breakout boards using those chips, are listed at
http://reprap.org/wiki/stepper_motor_driver .
In particular, many of the RepRap 3D printers I've seen connect an Arduino to four Pololu stepper drivers (under $15 each) to drive five stepper motors.

I made an Arduino( Arduino Nano) circuit to power a 12V Peltier(which is also a high power source.) using a MTP3055V MOSFET 60V 12A transistor. And the circuit is operating very well.

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


text:
Arduino code (on board) runs really slow
Stumbled upon this weirdest behavior, from time to time, my Arduino (UNO) runs gode really slow.
Searching this issue didn't clarify anything, most people have problems with IDE itself. My issue is related to actual board.
Heres a sample of my flow:

I compile & upload my sketch, all good
first initiation of program on the board seems to be "fast"
when I start to "animate" the neopixels it goes 3-4 times slower than it should
I'll touch the board, and animation goes fast again.

Here's a clip of that, at the end you'll see the "slowness"

Test environment:

Live environment:

The Touching part, is almost like if I "add" static electricity from my finger to the board, it wakes up and behaves normally.
For you who are curious about (non related) what animation I'm doing on neopixels, I'm turning on 15 pixels from 0 to 54. Like a "slide effect".
(I'm not using delay, only a delay(30) in the loop, rest of the delays are based on millis())
Is there any general info / explanation that would explain this behavior, like in electronics, arduino boards specifically ?
EDIT: I should also add, when printing logs into serial monitor, that slowness also affects the  outputs... they appear as "slow" as the pixels flow. When all works normally, I see pixels change and logs 50 times per second (roughly), but in this slow motion, I see pixels change and logs around 20 times per second.  Taking out the Serial entirely from the code doesn't seem to have effect.
Code:
#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
#define LEFT_BLINK_IN 2
#define RIGHT_BLINK_IN 3
#define PIN           6
#define NUMPIXELS     54
Adafruit_NeoPixel     leftLight = Adafruit_NeoPixel(NUMPIXELS, 6, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel     rightLight = Adafruit_NeoPixel(NUMPIXELS, 10, NEO_GRB + NEO_KHZ800);
int leftBlinkCount   = 0;
int rightBlinkCount  = 0;
int PIXELTOSHOW      = 20;
bool OEM_RIGHT_ON    = false;
bool OEM_LEFT_ON     = false;
int R_PIXEL          = -1;
int L_PIXEL          = -1;
int G_PIXEL          = -1;
int D_PIXEL          = -1;
char LAST_COMMAND;
bool DRL_ON         = false;
int DRL_STARTPIXEL  = 35;
uint32_t COLOR_YEL = rightLight.Color(240, 120, 0);
uint32_t COLOR_RED = rightLight.Color(255, 0, 0);
uint32_t COLOR_BLU = rightLight.Color(0, 0, 255);
uint32_t COLOR_NON = rightLight.Color(0, 0, 0);
uint32_t COLOR_WHI = rightLight.Color(255, 255, 255);

unsigned long rightPrevMillis = 0;
unsigned long leftPrevMillis = 0;
unsigned long generalPrevMillis = 0;
const long PIXEL_SWITCH_INTERVAL = 5;

int DRL_RESETER_LEFT = 0;
int DRL_RESETER_RIGHT = 0;

void welcome()
{
  int totalPixels = (NUMPIXELS + PIXELTOSHOW);
  while (G_PIXEL < totalPixels) {
    unsigned long leftCurrentMillis = millis();
    if (leftCurrentMillis - leftPrevMillis >= 12) {
      leftLight.setPixelColor(totalPixels - G_PIXEL, COLOR_WHI);
      rightLight.setPixelColor(totalPixels - G_PIXEL, COLOR_WHI);
      if (G_PIXEL >= 10) {
        leftLight.setPixelColor(totalPixels - G_PIXEL + PIXELTOSHOW , COLOR_NON);
        rightLight.setPixelColor(totalPixels - G_PIXEL + PIXELTOSHOW , COLOR_NON);
      }
      leftLight.show();
      rightLight.show();
      G_PIXEL++;
      leftPrevMillis = leftCurrentMillis;
    }
  }
  G_PIXEL = 0;
  while (G_PIXEL < totalPixels) {
    unsigned long leftCurrentMillis = millis();
    if (leftCurrentMillis - leftPrevMillis >= 12) {
      leftLight.setPixelColor(G_PIXEL, COLOR_WHI);
      rightLight.setPixelColor(G_PIXEL, COLOR_WHI);
      if (G_PIXEL >= 10) {
        leftLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
        rightLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
      }
      leftLight.show();
      rightLight.show();
      G_PIXEL++;
      leftPrevMillis = leftCurrentMillis;
    }
  }
}

void blinkRight()
{

  //slidePixels(rightBlinkCount, R_PIXEL, rightLight);
  if (rightBlinkCount > 0 && R_PIXEL > -1)
  {
      //Serial.println("RIGHT "+String(rightBlinkCount));
    LAST_COMMAND = ' ';
    unsigned long rightCurrentMillis = millis();
    if (rightCurrentMillis - rightPrevMillis >= PIXEL_SWITCH_INTERVAL) {
      rightLight.setPixelColor(R_PIXEL, COLOR_YEL);
      if (R_PIXEL >= PIXELTOSHOW)
      {
        rightLight.setPixelColor(R_PIXEL - PIXELTOSHOW, COLOR_NON);
        if (G_PIXEL > -1 && DRL_ON == false) {
          leftLight.setPixelColor(R_PIXEL - PIXELTOSHOW, COLOR_NON);
        }
      }
      leftLight.show();
      rightLight.show();
      R_PIXEL++;
      rightPrevMillis = rightCurrentMillis;
    }
    if ( R_PIXEL >= (NUMPIXELS + PIXELTOSHOW)) {
      rightBlinkCount--;
      if ( rightBlinkCount > -1 ) {
        R_PIXEL = DRL_RESETER_RIGHT = 0;
      } else {
        L_PIXEL = G_PIXEL = -1;
      }
      if(DRL_ON){
        D_PIXEL=DRL_STARTPIXEL;
      }
    }
  }

  }

  void blinkLeft() {
  //  slidePixels(leftBlinkCount, L_PIXEL, leftLight);

    if (leftBlinkCount > 0 && L_PIXEL > -1)
  {
          //Serial.println("left  "+String(rightBlinkCount));
    LAST_COMMAND = ' ';
    unsigned long leftCurrentMillis = millis();
    if (leftCurrentMillis - leftPrevMillis >= PIXEL_SWITCH_INTERVAL) {
      leftLight.setPixelColor(L_PIXEL, COLOR_YEL);
      if (L_PIXEL >= PIXELTOSHOW)
      {
        Serial.print(" "+String(L_PIXEL));
        leftLight.setPixelColor(L_PIXEL - PIXELTOSHOW, COLOR_NON);
        if (G_PIXEL > -1 && DRL_ON == false) {
          rightLight.setPixelColor(L_PIXEL - PIXELTOSHOW, COLOR_NON);

        }
      }
      rightLight.show();
      leftLight.show();
      L_PIXEL++;
      leftPrevMillis = leftCurrentMillis;
    }
    if ( L_PIXEL >= (NUMPIXELS + PIXELTOSHOW) ) {
      leftBlinkCount--;
      Serial.println("Count "+leftBlinkCount);
      if ( leftBlinkCount > -1 ) {
        L_PIXEL = DRL_RESETER_LEFT = 0;
      } else {
        L_PIXEL = G_PIXEL = -1;
      }
      if(DRL_ON){
        D_PIXEL=DRL_STARTPIXEL;
      }
    }
  }

}

/*void slidePixels(int &blinkCount, int &blinkPixel, Adafruit_NeoPixel &sideLight){
  if (blinkCount > 0 && blinkPixel > -1)
  {
    LAST_COMMAND = ' ';
    unsigned long leftCurrentMillis = millis();
    if (leftCurrentMillis - leftPrevMillis >= PIXEL_SWITCH_INTERVAL) {
      sideLight.setPixelColor(blinkPixel, COLOR_YEL);
      if (blinkPixel >= PIXELTOSHOW)
      {
        if(G_PIXEL>-1){
          rightLight.setPixelColor(blinkPixel - PIXELTOSHOW, COLOR_NON);
          leftLight.setPixelColor(blinkPixel - PIXELTOSHOW, COLOR_NON);
        }
      }
      rightLight.show();
      leftLight.show();
      blinkPixel++;
      leftPrevMillis = leftCurrentMillis;
    }
    if ( blinkPixel >= (NUMPIXELS + PIXELTOSHOW) ) {
      blinkCount--;
      if ( blinkCount > -1 ) {
        blinkPixel = 0;
      } else {
        blinkPixel = -1;
        if(DRL_ON){
          G_PIXEL = -1;
        }
      }
    }
  }
}*/

int switchRB = 0; // 0 = red, 1 = blue
void slideBlueRed() {
  unsigned long currentMillis = millis();
  if (currentMillis - generalPrevMillis >= 100) {
    if (switchRB == 0) {
      leftLight.setPixelColor(G_PIXEL, COLOR_RED);
      rightLight.setPixelColor(G_PIXEL, COLOR_RED);
    } else {
      leftLight.setPixelColor(G_PIXEL, COLOR_BLU);
      rightLight.setPixelColor(G_PIXEL, COLOR_BLU);
    }
    if (G_PIXEL >= 10) {
      leftLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
      rightLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
    }
    leftLight.show();
    rightLight.show();
    G_PIXEL++;
    generalPrevMillis = currentMillis;
  }
}

void drlLight(){

  unsigned long currentMillis = millis();
  if (D_PIXEL < NUMPIXELS) {
    leftLight.setPixelColor(NUMPIXELS-DRL_RESETER_LEFT, DRL_ON == true ? COLOR_WHI : COLOR_NON);
    rightLight.setPixelColor(NUMPIXELS-DRL_RESETER_RIGHT, DRL_ON == true ? COLOR_WHI : COLOR_NON);
    rightLight.setBrightness(128);
    leftLight.setBrightness(128);
    rightLight.show();
    leftLight.show();
    D_PIXEL++;
   //x //Serial.println(String(DRL_RESETER_LEFT) + " "+ String(NUMPIXELS - DRL_STARTPIXEL));
    if(DRL_RESETER_LEFT+1 < (NUMPIXELS - DRL_STARTPIXEL)){
      DRL_RESETER_LEFT++;
    }
    if(DRL_RESETER_RIGHT+1 < (NUMPIXELS - DRL_STARTPIXEL)){
      DRL_RESETER_RIGHT++;
    }
    generalPrevMillis = currentMillis;
  }

}

void setup() {
  Serial.begin(115200);
  leftLight.begin();
  rightLight.begin();
  pinMode(LEFT_BLINK_IN, INPUT);
  pinMode(RIGHT_BLINK_IN, INPUT);
  delay(50);
  welcome();
}

void loop() {

  if (digitalRead(LEFT_BLINK_IN) == HIGH) {
    if ( OEM_LEFT_ON == false ) {
      OEM_LEFT_ON = true;
      leftBlinkCount++;
      //Serial.println("LEFT "+String(leftBlinkCount));
      if (leftBlinkCount == 1) {
        L_PIXEL = 0;
      }
    }
  } else {
    OEM_LEFT_ON = false;
  }

  if (digitalRead(RIGHT_BLINK_IN) == HIGH) {
    if ( OEM_RIGHT_ON == false ) {
      OEM_RIGHT_ON = true;
      rightBlinkCount++;

      if (rightBlinkCount == 1) {
        R_PIXEL = 0;
      }
    }
  } else {
    OEM_RIGHT_ON = false;
  }

  if(DRL_ON && leftBlinkCount < 1 && rightBlinkCount < 1){
    drlLight();
  }

  blinkRight();
  blinkLeft();
  if(rightBlinkCount < 1 || leftBlinkCount < 1){
    delay(30);
    switch (LAST_COMMAND) {
      case 'q':
      case '?': {
        for ( int gp = 0; gp < NUMPIXELS + PIXELTOSHOW; gp++) {
          leftLight.setPixelColor(gp, COLOR_NON);
          rightLight.setPixelColor(gp, COLOR_NON);
        }
        leftLight.show();
        rightLight.show();
        G_PIXEL = -1;
        break;
      }
      case 's': {
        slideBlueRed();
        //Serial.println("bluuu");
        if (G_PIXEL >= NUMPIXELS ) {
          G_PIXEL = -1;
          switchRB = switchRB == 0 ? 1 : 0;
        }
        break;
      }
      case 'w': {
        welcome();
        if (G_PIXEL >= NUMPIXELS + PIXELTOSHOW) {
          G_PIXEL = -1;
        }
        break;
      }
      case 'd': {
        if(DRL_ON==false){
          D_PIXEL = DRL_STARTPIXEL;
          DRL_ON = true;
          LAST_COMMAND = '-';
        }else{
          D_PIXEL = 0;
          DRL_ON = false;
        }
        break;
      }
    }
    if (Serial.available()) {
      LAST_COMMAND = '-';
      while (Serial.available()) {
        char command = Serial.read();
        G_PIXEL=-1;
        LAST_COMMAND = command;
      }
    }
  }
}

Btw, ignore the case where 12V and 3.3V are tied together, The button can be used for only testing  and transistor was ment to be used in live connections.

Is that schematic completely accurate? Especially the bit where you have the - of a 3.3V source connected to the +3.3V pin of the Arduino?

Actually, sorry thought the prev scheme was messy, heres is what had as live and (one of the) test ENV. d.pr/i/BTxm I ran out of trial time in circuit lab and couldnt add the dirty test env. That is connecting the v3.3 directly to D2 with jumper wire.

Is R3 really 220Ω or is it bigger?

Anyway, now that I have seen the schematic I have more of an idea.  Your code uses D3 for a right-hand shift or something, yes? You don't have anything attached to D3?

no I just tested around with some resistors to see how they behave and of they work (not my strongest area hehe). yeah the D2 is for one stripe of neo pixels and d3 is another stripe, but when testing I only use one at a time, mostly it is d2

You need to hold your unused input in a known state (pull it to ground) otherwise it will be floating and will be randomly triggering and picking up noise from the surrounding - from things like your hand when it's near.

ahhhhaaaaa, that makes kind of sense, tho o never suspected D3 to cause this. I'll test that out tomorrow and add your solution as new post to make it as answer. and to you who have edited my original post with correct images thank you so much, am still horrible noob on overflow/exchange  inline coding

I guess those schematics helped after all.  Thanks for posting this question.  I'm a bit new to building proper digital circuits, and I can so see myself making a mistake like this.  This will make it easier to recognize.

This kind of behavior is almost always caused by floating digital input pins. "floating" means not connected to either power or ground, so their voltage is free to float. These input puts have very high impedance (typically less than 1uA of leakage current), so bringing a charged object near them is more enough to change their state.
Probably the easiest way to nail down (and sometimes fix) this problem is to enable the pull-up resistors on the digital inputs.
In you program, this could be as easy changing the mode on the digital input pins from INPUT to INPUT-PULLUP...
void setup() {
  Serial.begin(115200);
  leftLight.begin();
  rightLight.begin();
  pinMode(LEFT_BLINK_IN, INPUT_PULLUP );
  pinMode(RIGHT_BLINK_IN, INPUT_PULLUP );
  delay(50);
  welcome();
}

This will almost certainly eliminate the intermittent behavior you are seeing.
What you end up with might not be what you want (you might want the pin to dault to 0 when not connected), in which case you can add an external pull-down resistor or change the software to work with default pull-up.

Yah, seems the floating input was causing this behavior.

Now, 3 years later, I found the actual source of your problem. I had a similar problem so I'm posting here for others to find this solution.
The problem is that the NeoPixel library disables ALL interrupts during the time it spends sending the pixel data. The millis() function is dependent on interrupts. It works by incrementing a counter once every millisecond, based on a interrupt, called from a hardware timer. If you disable all interrupts then the counter will not be incremented for the duration.
The NeoPixel library needs to disable them because NeoPixels need very accurate timing of the signals, and you'd suffer from visible intermittent glitches if not.
The millis() counter drops about 30 microseconds per a RGB pixel, or 40 microseconds for a RGBW pixel. You have 54 RGB pixels in your led strip. 54*0,030 = 1,62 ms. Which means that there's 1,62 milliseconds between each of your millis() updates. I.e. it updates too slow.
Your unstable button must've simply caused nonstop neopixel updates, due to some logic in your code.
There's no easy fix for this, but a few specialized alternative or companion libraries exist that use very device-specific peripherals to work around it. For example, you could use one of the hardware timers to measure the time spent sending NeoPixel data, and then manually go in and update the millis() counter accordingly when done. This requires hacking the NeoPixel library and reading the datasheets for your specific Arduino processor.

Thanks for getting back with update, definitely good research you've done! Kudos!


text:
Arduino with DS18b20 and ENC28J60 to thingspeak
Can anyone help me to make this work? I have been trying for a couple of days to make this work, but no luck. I use a DS18b20 Temperature sensor and an ENC28J60 Ethernet module. The last code that I find like close to work is:
/*
| Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
| ENC28J60 chip.
| Based on the Ethercard example from www.jeelabs.org
| Phil Grant Jan 2014
*/
#include <EtherCard.h>
// change these settings to match your own setup
#define APIKEY  "xxxx"

//DHT Setup
//#include "DHT.h"
//#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//DHT dht(DHTPIN, DHTTYPE);

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0x12,0x11,0x22,0x12,0x21,0x11 };
char website[] = "api.thingspeak.com";
byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

void setup () {
Serial.begin(57600);
//dht.begin(); //Initializate DHT
  Serial.println("\n[webClient]");
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");
  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());
  if (millis() > timer) {
    timer = millis() + 60000; //Transmit every minute
    delay(2000);  // Wait a few seconds between measurements.
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  char h_buffer[10];
  String Hstring = dtostrf(h,0,5,h_buffer);
  //Convert Humidity value to String
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //float f = dht.readTemperature(true);
  char t_buffer[10];
  String Tstring = dtostrf(t,0,5,t_buffer);
  //Convert Temperature value to String
  byte sd = stash.create();
  stash.print("field1=");
  stash.println(Hstring);
  stash.print("&field2=");
  stash.println(Tstring);
  stash.save();
  // generate the header with payload - note that the stash size is used,
  // and that a "stash descriptor" is passed in as argument using "$H"
  Stash::prepare(PSTR(
    "POST /update HTTP/1.1" "\r\n"
    "Host: $F" "\r\n"
    "Connection: close" "\r\n"
    "X-THINGSPEAKAPIKEY: $F" "\r\n"
    "Content-Type: application/x-www-form-urlencoded" "\r\n"
    "Content-Length: $D" "\r\n"
    "\r\n"
    "$H"),
    website, PSTR(APIKEY), stash.size(), sd);
    // send the packet - this also releases all stash buffers once done
    ether.tcpSend();
  }
}

But on the serial monitor I get this message:

[webClient]
IP:  192.168.88.252
GW:  192.168.88.1
DNS: 8.8.8.8
DNS failed
SRV: 0.0.0.0

I have try all of this network configurations and I am sure that arduino have access to internet from my home router. I can ping arduino IP address from other computers in my network and all computers have access to Internet from same router and same subnet with same DNS.
Any more ideas?

But on serial monitor I get msg: [webClient] IP: 192.168.88.252 GW: 192.168.88.1 DNS: 8.8.8.8 DNS failed SRV: 0.0.0.0

The line above shows that you have the Ethernet interface configured to use a private IP address (192.168.X.Y) and that you're trying to reach Google's DNS server at 8.8.8.8. That means that you've got to have a connection to the Internet accessible through your gateway (192.168.88.1). The gateway will have to be doing NAT since your router will not (should) not route traffic from private addresses to the Internet – and even if it did other routers would not be able to route traffic back to you.
The first thing to do is to confirm that you've got an Internet connection and that the address you're trying to reach exists. If you've got another computer on the same network that can reach the Internet try the address you're trying to reach (api.thingspeak.com) and confirm that the name resolves to an IP address. Then confirm that the gateway you're using on that machine matches what you've got configured on the Arduino.
Another good thing to check would be that the Arduino seems to be working on the wire. There are a number of ways that you could confirm this:

Check to see that you can ping it.
Check to see that it shows up in your ARP cache (use the command arp -a in the terminal if you're on Linux or OS X. You're looking to see that the IP address assigned to the Arduino is unique and that you get back the MAC address that you expect.
Try pointing your DNS at your router (assuming it is configured to act as a DNS server). That will let you see if you get a response from inside your network. Before doing this configure that api.thingspeak.com resolves using ping or by going there on another machine. If this works, you should try it pointing another machine at 8.8.8.8 as your DNS server – just to confirm that this works. If it works and the Arduino fails then it is getting more puzzling.

At this point you most likely will have identified the problem. If you haven't it would make sense to spend some time learning a bit about tcpdump or Wire Shark so that you can watch TCP traffic on the network. At the very least you'll want to be able to watch to see the basic DNS transaction. One possibility may be that the Arduino expects the DNS server to be on the local wire and that it is timing out too fast.


text:
RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?
I'm trying to implement a card reader (i.e. credit cards) for shopping purposes, and AFAIK those cards are ISO 14443-A compliant (Mifare Classic 1K). I already made an Android app that can send custom APDU to read specific sectors by using raw SendBytes().
Since I need to build a circuit with a custom antenna, I chose Arduino-uno with a NFC module (was thinking about StrongLink SL013), I wanted to know if it's possible to send raw bytes and receive the response from the tag. I only found some higher-level implementation (readSector, writeSector and so on).

Have you gone through the technical specifications? Have you read the ISO-14443-A definitions? This should be directly answerable from the specifications.

I found it's not part of the ISO specifications, it depends on the specific chipset/shield i'm using. NXP PN532 supports it.

RFID protocols require either passive or active tags.  Depending on which you use, either the tag or reader regularly transmits pulses.  Check www.rfidreader.com for more info.  https://www.rfidjournal.com provides valuable resources as well.
Many companies invest heavily in developing RFID technology.  You would be well advised not to reinvent wheels without reeeeally deeeeeep pockets.

This would differ per device/reader.
Currently, I'm in a project with a TRF7970a RFID reader. I've seen it it's datasheet that it does have options to send RAW values as it does not support every protocol (NXP has patent on one?) thus the chip doesn,t parse it, but can send it to the mcu completely.
In short, yes this is possible.
But using a reader that is compliant with your protocol might supress your development cost/time


text:
Connect Arduino to an external microSD card reader
I have a camera with a microSd card reader that is the only output type.
I want to read the microSd when the camera makes a photo.
How can I read it with an Arduino?
Duplicating the reader connections and join it to my Arduino microSd reader?
Or I can try to connect to the circuit (its very very small)?
Do you think I can put an ESP8266 to the camera?
Thanks for all!!!

Have a look into "Processing" and the camera libraries for it.

Or do you want to achieve something like: http://www.instructables.com/id/How-to-use-OV7670-Camera-Module-with-Arduino/

I'm voting to close this question as off-topic because it's unclear what the goal is and/or the current goal is beyond the capabilities of an Arduino

You cannot
SD cards cannot be shared between masters in operation, and it is unsafe to disconnect the card from the camera with an electronic switch when the camera is not expecting that.
Nor is an ordinary Arduino fast enough to passively snoop the data being written to the card by the camera (while a card will let an Arduino write to it quite slowly, any camera would do so far, far faster)
Nor is an ordinary Arduino able to do much of anything meaningful with the image files produced by a typical camera in real time.
Nor can an ESP8266 while running Arduino-based software; it apparently does have some high-speed I/O capabilities but that would require low-level rather than Arduino-port-based programming.
For all practical purposes, you'd need to power off the camera, remove the card, and place it in the Arduino reader.

I guess no is an answer as well :) I highly agree that it doesn't really make sense nor seems practically possible. A lot of camera's can be directly interfaced with an PC, that would be a better option.

For what it's worth, I personally believe that the question is not on topic for the Arduino site because the fundamental problem is that SD cards are not designed to be shared, and already voted accordingly to close it.  But since we seem to be very slow about closing such questions went ahead and posted a comprehensive explanation as to why it's not achievable with an Arduino or Arduino-based technology.

True, but wel it's a question on Arduino. If it was possible, it would be on topic? But I agree it's not really answerable in any further way than you just did.

the camera is in other circuit and I need to extract the images/videos

As already explained, it doesn't really matter what you need, SD cards simply cannot be shared.  You will have to find another way to share data, or power down both devices and move the card between them.


text:
externally powering the Arduino questions
I have several questions on externally powering the Arduino Uno

I have a 7.2V power source that is 6 rechargeable AA batteries together, 1.2V and 1300mA each. If i use a 4.70 and 1.5 ohm resistors together to give 1.16 amps, can I power the arduino with this?

Can I power a servo off the Arduino 5V rail If i place a 470uF or more capacitor alongside it?
Will anything heat or blow up or am I just being paranoid like always?

Why would you use resistors?

Is it a genuine Arduino Rev3, or a 'clone'? AFAICT, their are clones which are not electrically identical to a genuine Arduino/Genuino.

This question has been answered on electronics.stackexchange, e.g. How to provide separate voltages from a common power source
Daniel V has explained the main issues.
The 'killer' for most people is the resistors are always across the battery, and so they alone will take over 1A from the battery pack continuously, and hence run it flat in just over an hour. Further, they need to dissipate over 5W of heat, so they aren't that cheap either.
A NiMh rechargeable battery will have a voltage of about 1.4V when it's fully charged, dropping to under 1V before it is exhausted. So that would mean the resistor network needs to output 5V or less with an input voltage from 6x1.4V=8.2V down to under 6x1V=6V.
So the resistor ratio would need to handle 8.2V in and produce 5V out, and then 6V in would produce 3.66V. My reading of the ATmega sec is it might struggle to run at 16MHz at that 3.66V input voltage.
You might try to make a resistor-based voltage divider more efficient by increasing the total resistance.
However, as explained on the electronics.stackexchange, the load presented by the ATmega on an Arduino varies dynamically, from microsecond to microsecond, so it is very hard to choose resistors which would maintain the voltage within a reasonable operating range, while the current passing through the Arduino varies so much.
An Arduino has an on-board voltage regulator.
However, the typical 5V regulator on generic Arduino's have a drop-out voltage of 2V, i.e. the input voltage needs to be 7V or more. That means most of that battery pack capacity will provide less than 7V, so the voltage will start to drop.
You might be lucky and the on-board regulator will 'track' the input voltage down. That means it will fail below 5V as its input drops below 7V. You would need to test your Arduino; there is no guarantee that the regulator on the board does this. Further, it might struggle to run at 16MHz as the voltage approaches 4V.
So, if this is just a one-off hobby project, it might be reasonable to try that. However, if other people are going to use it, it might be too risky.
The ATmega can be run with anything between 5V and 1.8V if the clock is slow enough. Also you'd need to either modify the electronics, or change the bootloader of the Arduino to ensure it runs at a much lower clock frequency. So it is possible to run at a lower voltage than 5V, by changing the bootloader, but it seems like a strange exercise. Then a resistor divider (which wastes a lot of energy), or the on-board regulator could be used.
Instead, look at a Low-Drop-Out (LDO) voltage regulator. There are parts which will regulate anything from 8.4V down to 6V, or less, down to 5V. An Arduino alone uses well under 100mA, it is the electronics it is driving which uses the majority of an Arduino's specified 500mA.
So you look for a voltage regulator, which will take 9V in (as a safety margin) with a drop-out voltage of 0.7V (lots at this spec), 5V out, and 250mA or better. Most electronics distributors have a product selector which will help you find this, and you may find small ready-made modules which do exactly this (but not an LM111xx).
You don't post a link to the servo you're using.
Low-cost servo's typically take a lot of current as they move. I've measured some using a proper bench power-supply unit (bench PSU). They typically take well over 1A for periods long enough for me to see it happen. So the power supply would likely need to supply more than 1A for short periods, i.e. 10's of milliseconds. You will need quite a substantial capacitor to handle that.
Depending on the servo, you might be better to use 4xNiMh to power the servo directly, without any intermediate regulation, and a more modest capacitor. The ground (-) of that power supply needs to be connected to the GND of the Arduino so that the servo signal from the Arduino will drive the servo correctly.
In that case, you might use a low-cost (ebay) DC-DC step up (boost) switching regulator to provide the 5V to the Arduino. Their are lots available which are intended to power USB devices at 5V.

Your typical Arduino has a built-in 5V regulator. Just plug the batteries into the barrel jack - that is what it is for.
If you don't have a barrel jack on your Arduino (it's one of the little ones?) then you will need a voltage regulator. For battery usage you want a switching "buck" regulator.
You can find them cheaply enough under the name "UBEC" (Universal Battery Elimination Circuit) and are used for model aircraft etc.

You can connect the batteries fine into Vin or the barrel jack, however you will run into the issue that your battery voltage will sag. This will vary on what chemistry batteries you are using, NiMh voltage discharge sits on a bit of a plateau around 1.2V typically, alkaline has more of a gentle curve downwards and then drops off quite sharply around or below 1V.
The reason this is an issue is highlighted on the Arduino Uno page itself:

Input Voltage (recommended)   7-12V
Input Voltage (limit)  6-20V

and

The board can operate on an external supply from 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

The issue here is the dropout of the onboard regulator.
The solution is to use your own external regulator and connect it to the 5VDC pin.
You can use:

An external swithcmode DC-DC converter, you would be ideally after a buck boost. DC-DC converters are available from ICs for a full ground up DIY design to available on board modules and daughterboards and fully assembled circuits. Regarding the other answer a BEC or UBEC may not be suitable as typically they are buck converters and have higher minimum output voltages than that required by the OP, some however with careful selection may be alright to use.

Adafruit off the shelf buck-boost module:
https://www.adafruit.com/products/2190

An external linear LDO regulator, ideally with as low dropout as possible. You will need to pick this part to suit your input voltage range, this may be difficult as extremely low dropout parts are typically low current and not suitable if wanting to drive a servo. Something like a REG103 for example may work, depending on the dropout an LDO linear regulator may work down to around 5.2~5.3VDC minimum, which should be okay for most of the capacity of the batteries.

A premade shield, some may work for you, some to give you an idea of what is required.

DC-DC converter for battery shield:
https://www.wayneandlayne.com/projects/battery-booster-shield/
Adafruit has a lithium battery shield such as does Sparkfun (not enough rep for more links)
Itead has a AAA battery shield also.
Options here will depend on your design ability and assembly skills as to if you can DIY or need off the shelf.
Your servo will be fine connected to the external regulator as long as the option you use is rated to supply enough current.


text:
ESP8266 GET REPLY ERROR 501
I am trying to build a home automation system and i am unable to get data from a website using the arduino sketch, however i am able to get data from the website when i enter the AT commands into the serial monitor.Below is my sketch:
#include <SoftwareSerial.h>

SoftwareSerial esp8266(4,5);

void setup(){
  Serial.begin(9600);
  esp8266.begin(115200);
  esp8266.println("AT+CIPMUX=1\r\n");
  delay(2000);
  esp8266.println("AT+CIPSTART=0,\"TCP\",\"www.homeautomationserver.com\",80 \r\n");
  delay(2000);
  esp8266.println("AT+CIPSEND=0,75");
  esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
  esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");
}

void loop(){

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

I get a 501 not Implemented error from the server.
Please Help.
Thanks

http://www.computerhope.com/issues/ch001020.htm

You should really include Connection: close in your headers as well, so the server doesn't try and keep the connection open longer than needed.

Content-length: ??? might help too.  (??? should be the message size)

@Matt Content-length would be 0 - there is no body there to have a length. It's not strictly needed, especially if the sending pipe is manually closed by the client.

Maybe you should replace esp8266.println() with esp8266.print(), because you already append "\r\n" in your strings.

Can you use you favourite web browser and retrieve the page http://www.homeautomationserver.com/f/pw9e1acqx7yb0gl.txt ?
If you can then the problem is with your client, if not its with the address you are requesting or the server.
The fact you are getting a 501 error indicates that GET is not supported for this resource.  So check that you are using the correct method?
Get yourself a REST console (there is an add-on for chrome and plenty of others) try typing the command in manually to see if you can identify the fault.
Look at Wikipedia for a list of error codes, it might give you a clue as to what is wrong.
And don't you need a AT+CIPSEND after you have printed the http packet?

And don't you need a AT+CIPSEND after you have printed the http packet? - no that comes beforehand. The numbers indicate how many bytes you are about to send so it knows how many to expect.

@Majenko - OK, thanks for the correction, I just saw an example that had the send after the header, maybe it was sending an empty body(?).

If the send is after any form of data (including the header) the data will be interpreted as ESP8266 AT commands and will fail. The example you found must be horribly broken.

Thanks for your reply , I have tried using your code and this time i am not receiving any reply from the server. i have also noticed that using my code i sometimes receive a 400 error -bad request as well followed by the 501 error after a few tries .i am so confused with the error codes generated by the server.

Sorry Matt i was trying to reply to Majenko and thank you for your reply as well, I know the issue is with my sketch but cannot figure out what exactly is the problem.

Your problem lies in these lines:
esp8266.println("AT+CIPSEND=0,75");
esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");

You are mistakenly using println() instead of print() when sending the data. That imposes its own <CR><LF> sequence on the end of the lines, yet you are adding the <CR><LF> manually.  You are also incorrectly specifying 75 characters to send, so the result of all that is:
GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
\r\n                                                  2
Host:www.homeautomationserver.com\r\n                35
\r                                                    1
                                                   ----
                                                     75

I.e., your request is garbled. You need to change the println() to print() for the data printing and make sure the character count is correct:
esp8266.println("AT+CIPSEND=0,74");
esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.print("Host:www.homeautomationserver.com\r\n\r\n");

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
Host:www.homeautomationserver.com\r\n                35
\r\n                                                  2
                                                   ----
                                                     74

You should also include more detail and commands in your headers. Things like the length of the body (0 bytes) and the fact that the connection should be closed, and there really should be a space after the colon on the Host: header:
esp8266.println("AT+CIPSEND=0,113");
esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.print("Connection: close\r\n");
esp8266.print("Content-Length: 0\r\n");
esp8266.print("Host: www.homeautomationserver.com\r\n\r\n");

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
Connection: close\r\n                                19
Content-Length: 0\r\n                                19
Host: www.homeautomationserver.com\r\n               36
\r\n                                                  2
                                                  -----
                                                    113

Thanks for your reply , I have tried using your code and this time i am not receiving any reply from the server. i have also noticed that using my code i sometimes receive a 400 error -bad request as well followed by the 501 error after a few tries .i am so confused with the error codes generated by the server.


text:
Arduino servo motor on pushbutton
I'm working on my first arduino project and i have my first problem dealing with servo motor , i'm trying to control the servo from my pc with this code but it just spining :
  #include <Servo.h>

Servo servo1;
long num;

void setup()
{
   servo1.attach(7);
   Serial.begin(9600);
   Serial.print("Enter Position = ");
}

void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

this is my setup

I have reformatted your code and the problem becomes very clear (to me).
void loop()
{
  while(Serial.available()>0)
  {
    num= Serial.parseInt();
    Serial.print(num);
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

You are getting some input from the user and then setting the servo to that point.
When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position.  In short move the servo1.write(num); line inside the } of the while loop.
Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in num which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin.  ALWAYS INITIALIES VARIABLES BEFORE USE :)
A minor point, your while loop could be, probably should be an if statement.  That will prevent a cat sitting on the keyboard and blocking the servo movement.

i changed the while with if and moved servo1.write(num) and initiales num but as soon as i upload it it starts moving slowly and when i enter a position it just spins faster...

What about long num = 0;

What happens if you take the wire out of pin 7 and leave it disconnected?


text:
How can I test/demonstrate what the serial input and output buffers are?
Serial is causing me a lot of pain, and I think there are certain basic principles that I simple have not understood. I hope that by understanding how to test/demonstrate the buffer size, I will come one big step closer to understanding how serial works.
I suspect it is only possible to demonstrate this by writing a piece of software for "the other end"; the pc. I do understand Python, and to some extent how to work with serial on Python, so if possible, please write the pc code in Python.
If you supply an example (piece of code), please explain how the example works.

What example are you talking about?

Do you mean what causes me problems? A lot of stuff does :) Basically my lack of understanding of how the buffer behaves is what causes me problems. I think it must be ok on SE to ask a question like this, analogues to http://stackoverflow.com/questions/12791864/c-program-to-check-little-vs-big-endian. Please elaborate if I misunderstood your comment.

In your last line you ask how "the example" works. Do you mean the Arduino serial example sketch?

Now I understand. I have edited my answer to make clear what I meant. Thx.

On the Arduinos with 1000 bytes of RAM or more, the hardware serial input and output buffers are both 64 bytes. For devices with less RAM they are 16 bytes. This information is in the file HardwareSerial.h

See https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h and https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp for the actual implementation.

You can think of the incoming serial buffer as a bucket of water under a dripping tap. Next to the bucket is a cup.
Water arrives through the tap and drips into the bucket. When you want to get some water, if there is enough water in the bucket, you dip the cup in and remove a cupful of water. If there isn't enough water you don't get anything in your cup.
If you don't dip the cup in for a while too much water will dribble into the bucket and it will overflow all over the floor.
It's exactly the same with serial data. It arrives through the UART hardware and is placed into the "bucket" by the UART receive interrupt. If you don't dip your cup in fast enough (Serial.read()) the bucket will overflow and any new data that arrives will spill onto the metaphorical floor.
To test this out you can just send more data to the Arduino than will fit into the serial buffer (typically 64 bytes) without reading any. Then after you have finished flooding the buffer you can read what is actually in the buffer and send it back again (maybe formatted nicely) so you can see what has actually ended up in the buffer and what hasn't.
One quick and dirty test would be to send the raw bytes 0 to 255 to the Arduino, then after a delay read them back and display the DEC values for them (Serial.print(Serial.read(), DEC))) to see exactly which bytes arrived and which didn't (hint: you should see the numbers 0 to 63 if the buffer is 64 bytes big).

For the transmit buffer it's slightly different.  You can think of it more as a bucket with a small hole in the bottom.
You pour data (water) in the top at whatever speed you want, and it trickles out of the bottom at a pre-set rate (the baud rate - the size of the hole). You don't like wet messes though, so if the bucket is full you wait a while before putting more water into it. Just like with serial - if the transmit buffer is full any attempts to add to it will block until data has been sent out by the UART transmit interrupt.

How about a library like ArduinoJson, with the prettyPrintTo(Serial) command, how does it make sure that it does not write too fast to the serial?

It doesn't. It just writes to the serial object when the serial object allows it to.

What do you mean "allows it to"? Does ArduinoJson in some way query if it is allowed to?

The key word in my answer is the one in italics: blocking. That is it stops and waits until there is room.

Ok, so it is simply not possible to spill over when Arduino is writing. It just blocks if the buffer is full. I see it clearly in your answer now. Thanks.

That is correct. The buffer is emptied asynchronously using an interrupt, so the write function just uses a simple while loop to wait for room to be made for another character.


text:
How to use two Sonar's
I'm using a single sonar, but I want to use two sonar to know another distance.
Here is how I use my single sonar:
    #include <NewPing.h>

    #define TRIGGER_PIN  9
    #define ECHO_PIN  10
    #define MAX_DISTANCE  100 // in CM
    ...
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
    ...
    delay(100);
    unsigned int uS = sonar.ping();
    int cm = uS / US_ROUNDTRIP_CM;

But I Want to use a second one to calculate another distance, how to?
#define TRIGGER_PIN_2  11
#define ECHO_PIN_2  12
...
new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE);
...
???

Thanks in advance
EDIT:
Maybe this one, I'll try this when I will get my second sonar
#define SONAR_NUM     2
#define MAX_DISTANCE 200
...
NewPing sonar[SONAR_NUM] = {
  NewPing(9, 10, MAX_DISTANCE),
  NewPing(11, 12, MAX_DISTANCE)
};
...
delay(100);
unsigned int uS1 = sonar[0].ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar[1].ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

Who's sonar device are you using? Can you provide a link to the website?

@Duncan: I used this kind of untrasonic sonar http://www.hitronics.net/image/cache/data/Arduino/Ultrasonic%20Module/F90JYNWH7UR7RCS.LARGE[1]-500x500.jpg, and And I found Library here: https://code.google.com/p/arduino-new-ping/, http://playground.arduino.cc/Code/NewPing .

Thanks for the reply. Can you send a link to a source of the module rather than just a picture of it?

@Duncan : source is here: https://code.google.com/p/arduino-new-ping/downloads/list

Maybe this one, I'll try this when I will get my second sonar

Ding ding ding! Yeah, this would be one way to do that. That creates an array so you can reference the sonar with sonar[i], where i is either 0 or 1 for the first or second number.
For only two sensors, it might be easier just to do something like this:
NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Then you can run the other code like this:
delay(100);
unsigned int uS1 = sonar1.ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar2.ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

A little less code to read, whichever one you want.
The reason you can do this is you can replace the sonar with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it Arduino_Sonar if you wanted to.
The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do int numbers[500]; to declare them. An array might be more useful if you're expanding your circuit, but either is correct.

@Annonomous : Thanks, What a great price! I prefer your version, only two sonar's :-) Thanks for the support!


text:
Arduino motor shield will only work in one direction
I have this Arduino motor shield which is hooked up with two DC motors. The board is the same as this one from Sparkfun.
A PWM output controls the speed of the motor, and a digital out controls the direction. The problem is that it only works in one direction, namely if the direction pin is high.
With the direction pin HIGH and 255 is written to the PWM pin, Vout on the terminals is similar to Vin. If I reverse the direction by setting the direction pin LOW I would expect Vout to be -Vin, ie. the polarity reversed. But not so. I get a little more than zero volt across the terminals.
It's the same for both channels.
Edit: The setup is powered from a 9V power adaptor through the barrel jack on Arduino.

Is the board defective, or am I misunderstanding something?
SOLUTION: Thanks to the edited post (especially #3) in the accepted answer, I not only looked at the schematic (again), I actually understood it. I had already noticed the jumper called V-LOGIC which on the picture from Sparkfun was set to 5V where it on my shield was not set. I really didn't know what it was used for, but I set it to 5V so it was the same. But by looking at the schematic and the inverters, I realized that the inverter was fed from V-LOGIC which was connected to 5V. And bingo: I had not connected the 5V pin on the shield, only vIN which I assumed would be sufficient. The thing is, I am awaiting a set of stackable headers instead of the ones supplied, so I only connected the minimum numbers of pins because I will need to desolder them when I get the new headers.

How have you hooked up the motor?

Sounds like something is hooked up wrong. Please add a photo or a diagram of your wiring. Also, what happens with the LEDs on the shield?

The motor is connected between 1 & 2 on the terminal. Or 3 & 4 for motor B. The LEDs light up for the direction that works (with the DIR pin high). For the other direction there is no light in the LEDs. Will add some photos tomorrow as it's late now. But thanks so far.

Added an image of the setup. Here the motor is connected to terminal A, but it's the same with B. Only works in one direction; the same applies to the LED.

Have you verified that the motor rotates in both directions independent of the board?

I think the problem is with your motor. What is the blue wire that's not connected to anything? I think this is not a 'simple' DC motor. It's not a brushless though, or it wouldn't run at all. I would try a different motor in this situation.

@Jasmine: If you look at the motor itself it only has 2 leads. The blue wire is likely an unused conductor in a 3-conductor cable.

I considered that, but then I also considered we only see one side of it in the photo. And, that it really should work, it's wired up fine, so something must be wrong with the motor, or the shield is broken and that's less likely.

The blue wire it not used. There are three wires in the cable and I just used the two of them. The motor spins fine in both direction if I reverse the wires, so it's definetely not the motor. Besides, I have 4 motors and it's the same for all of them! Also, as noted, I have measured the voltage across the terminal and I only get a reading for one direction (DIR pin is high). For the other, there is 0 V across the terminal. My best guess is that the shield is broken, it's just very unlike that BOTH channels would be broken, but of course not impossible.

Also, there is only light in the LEDs for one direction.

OK that sounds all good. Where is the power source for the motors? I don't see the 12V source for the motors in the picture? I can see that you're powering it from the USB, which is only 5V, and might not be enough voltage.

That the LED's won't light for reverse on either channel suggests you are doing something wrong - for example, you could be swapping direction and enable.  You might try looking up the L298 pinout and probing the input signals there - be careful though as it is easily shorted so you might want to do that using a current limited 5v supply rather than a high current 9v one.

I think you may be having an issue with how you are powering the shield.  Are you trying to do it with just your USB connection?
In your photo, I do not see a connection to your Arduino's barrel jack or to the Vin connector of the shield itself.  According to the SparkFun site:

The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:

The barrel jack input on the Arduino.
The Vin input on the shield

If you don’t want to use the Arduino’s barrel jack input, you can use the Vin input on the shield instead. This voltage input will supply both the shield and the Arduino. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.
Do not supply power to both the Arduino barrel jack input and Vin on the shield!

I hope this helps!
EDIT BASED ON COMMENTS
Since you are properly powering the shield, I would recommend the following (see the shield's schematic for specifics):

Maintaining the connection shown above (with the addition of the 9V power supply connected to the barrel jack) ensure that you are able to properly set the DIRA input.  You can check this with a multimeter on pin 7 of the LN298 whenever you are trying to switch directions.
If you are getting the expected results on pin 7 (pin goes HI when your code wants the motor to go one direction and pin goes LOW for the other) - check pin 9... the value here should always be the opposite of what you are setting for DIRA on pin 7.  If that is all good, then you probably have an issue with the LN298.
If you are not getting the expected results at pin 9, but pin 7 looks good, then you are having a problem with the 74HC1G04 IC (although I would doubt this since you are having problems with both the A and B motor outputs).
If you are not getting the expected results at pin 7, then double check the code to make sure you have set and cleared the correct output pin.  I would also check the solder joints of the connectors on the shield - you can set a multimeter to do a resistance check from the shield's connector (pin 12) to the direction input on the LN298 (pin 7).  If the continuity is measuring close to 0 ohms then there is probably an issue with your code.
If your code looks good, I have also had issues with bad outputs on the Arduino - you can check to see if you are properly toggling the direction pin (pin 12) on the Arduino without the shield connected.  Then, if the pin is not toggling, there is probably an issue with your Arduino - try toggling a different (unused) pin and jumpering it.

I power the setup from a 9V power source via the barrel jack. Should have mentioned that, sorry. However, the shield works just the same powered from USB, only the motors spins somewhat slower.

"However, the shield works just the same powered from USB, only the motors spins somewhat slower" - and apparently in only one direction. The effect of lower voltage can be "doesn't work at all" it's not always just "weak"

Yes, but I do power it from a 9V external power source! I only say that it works the same powered from USB, because I tried that also :-)

@embedded_guy: Thanks for your thorough advice. Pin 7 goes HI and LO as expected, with the motor and LED on when hi. However, pin 9 stays LO all the time. And it's the same for driver B: Pin 13 goes HI and LO, but 15 stays LO. So two dead 74HC1G04 ICs?

Hooray! Problem solved. See my updated question.

@marlar Outstanding troubleshooting, I am glad that it is working for you now!